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/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/IR/IntrinsicsR600.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/KnownBits.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "si-lower"
35 
36 STATISTIC(NumTailCalls, "Number of tail calls");
37 
38 static cl::opt<bool> DisableLoopAlignment(
39   "amdgpu-disable-loop-alignment",
40   cl::desc("Do not align and prefetch loops"),
41   cl::init(false));
42 
43 static cl::opt<bool> VGPRReserveforSGPRSpill(
44     "amdgpu-reserve-vgpr-for-sgpr-spill",
45     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
46 
47 static cl::opt<bool> UseDivergentRegisterIndexing(
48   "amdgpu-use-divergent-register-indexing",
49   cl::Hidden,
50   cl::desc("Use indirect register addressing for divergent indexes"),
51   cl::init(false));
52 
53 static bool hasFP32Denormals(const MachineFunction &MF) {
54   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
55   return Info->getMode().allFP32Denormals();
56 }
57 
58 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
59   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
60   return Info->getMode().allFP64FP16Denormals();
61 }
62 
63 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
64   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
65   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
66     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
67       return AMDGPU::SGPR0 + Reg;
68     }
69   }
70   llvm_unreachable("Cannot allocate sgpr");
71 }
72 
73 SITargetLowering::SITargetLowering(const TargetMachine &TM,
74                                    const GCNSubtarget &STI)
75     : AMDGPUTargetLowering(TM, STI),
76       Subtarget(&STI) {
77   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
78   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
79 
80   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
81   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
82 
83   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
84   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
86 
87   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
88   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
89 
90   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
91   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
92 
93   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
94   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
95 
96   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
97   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
98 
99   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
100   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
101 
102   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
103   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
104 
105   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
106   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
107 
108   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
109   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
110 
111   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
112   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
113 
114   if (Subtarget->has16BitInsts()) {
115     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
116     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
117 
118     // Unless there are also VOP3P operations, not operations are really legal.
119     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
120     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
121     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
122     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
123   }
124 
125   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
126   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
127 
128   computeRegisterProperties(Subtarget->getRegisterInfo());
129 
130   // The boolean content concept here is too inflexible. Compares only ever
131   // really produce a 1-bit result. Any copy/extend from these will turn into a
132   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
133   // it's what most targets use.
134   setBooleanContents(ZeroOrOneBooleanContent);
135   setBooleanVectorContents(ZeroOrOneBooleanContent);
136 
137   // We need to custom lower vector stores from local memory
138   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
139   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
140   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
141   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
142   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
143   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
144   setOperationAction(ISD::LOAD, MVT::i1, Custom);
145   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
146 
147   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
148   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
149   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
150   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
151   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
152   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
153   setOperationAction(ISD::STORE, MVT::i1, Custom);
154   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
155 
156   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
157   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
158   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
159   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
160   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
161   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
162   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
163   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
164   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
165   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
166   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
167   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
168   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
169   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
170   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
171   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
172 
173   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
174   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
175   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
176   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
177   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
178 
179   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
180   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
181 
182   setOperationAction(ISD::SELECT, MVT::i1, Promote);
183   setOperationAction(ISD::SELECT, MVT::i64, Custom);
184   setOperationAction(ISD::SELECT, MVT::f64, Promote);
185   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
186 
187   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
188   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
189   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
190   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
191   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
192 
193   setOperationAction(ISD::SETCC, MVT::i1, Promote);
194   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
195   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
196   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
197 
198   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
199   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
200   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
201   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
202   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
203   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
204   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
205   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
206 
207   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
208   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
209   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
210   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
215 
216   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
217   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
218   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
219   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
220   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
221   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
222 
223   setOperationAction(ISD::UADDO, MVT::i32, Legal);
224   setOperationAction(ISD::USUBO, MVT::i32, Legal);
225 
226   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
227   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
228 
229   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
230   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
231   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
232 
233 #if 0
234   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
235   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
236 #endif
237 
238   // We only support LOAD/STORE and vector manipulation ops for vectors
239   // with > 4 elements.
240   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
241                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
242                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
243                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
244     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245       switch (Op) {
246       case ISD::LOAD:
247       case ISD::STORE:
248       case ISD::BUILD_VECTOR:
249       case ISD::BITCAST:
250       case ISD::EXTRACT_VECTOR_ELT:
251       case ISD::INSERT_VECTOR_ELT:
252       case ISD::INSERT_SUBVECTOR:
253       case ISD::EXTRACT_SUBVECTOR:
254       case ISD::SCALAR_TO_VECTOR:
255         break;
256       case ISD::CONCAT_VECTORS:
257         setOperationAction(Op, VT, Custom);
258         break;
259       default:
260         setOperationAction(Op, VT, Expand);
261         break;
262       }
263     }
264   }
265 
266   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
267 
268   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269   // is expanded to avoid having two separate loops in case the index is a VGPR.
270 
271   // Most operations are naturally 32-bit vector operations. We only support
272   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
276 
277     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
279 
280     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
285   }
286 
287   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
288     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
289     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
290 
291     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
292     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
293 
294     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
295     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
296 
297     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
298     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
299   }
300 
301   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
302     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
303     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
304 
305     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
306     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
307 
308     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
309     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
310 
311     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
312     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
313   }
314 
315   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
316     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
318 
319     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
320     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
321 
322     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
323     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
324 
325     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
327   }
328 
329   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
330   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
331   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
332   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
333 
334   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
335   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
336 
337   // Avoid stack access for these.
338   // TODO: Generalize to more vector types.
339   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
340   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
341   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
342   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
343 
344   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
345   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
346   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
347   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
348   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
349 
350   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
351   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
352   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
353 
354   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
355   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
356   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
357   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
358 
359   // Deal with vec3 vector operations when widened to vec4.
360   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
361   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
362   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
363   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
364 
365   // Deal with vec5 vector operations when widened to vec8.
366   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
367   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
368   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
369   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
370 
371   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
372   // and output demarshalling
373   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
374   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
375 
376   // We can't return success/failure, only the old value,
377   // let LLVM add the comparison
378   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
379   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
380 
381   if (Subtarget->hasFlatAddressSpace()) {
382     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
383     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
384   }
385 
386   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
387 
388   // FIXME: This should be narrowed to i32, but that only happens if i64 is
389   // illegal.
390   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
391   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
392   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
393 
394   // On SI this is s_memtime and s_memrealtime on VI.
395   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
396   setOperationAction(ISD::TRAP, MVT::Other, Custom);
397   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
398 
399   if (Subtarget->has16BitInsts()) {
400     setOperationAction(ISD::FPOW, MVT::f16, Promote);
401     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
402     setOperationAction(ISD::FLOG, MVT::f16, Custom);
403     setOperationAction(ISD::FEXP, MVT::f16, Custom);
404     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
405   }
406 
407   if (Subtarget->hasMadMacF32Insts())
408     setOperationAction(ISD::FMAD, MVT::f32, Legal);
409 
410   if (!Subtarget->hasBFI()) {
411     // fcopysign can be done in a single instruction with BFI.
412     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
413     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
414   }
415 
416   if (!Subtarget->hasBCNT(32))
417     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
418 
419   if (!Subtarget->hasBCNT(64))
420     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
421 
422   if (Subtarget->hasFFBH())
423     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
424 
425   if (Subtarget->hasFFBL())
426     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
427 
428   // We only really have 32-bit BFE instructions (and 16-bit on VI).
429   //
430   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
431   // effort to match them now. We want this to be false for i64 cases when the
432   // extraction isn't restricted to the upper or lower half. Ideally we would
433   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
434   // span the midpoint are probably relatively rare, so don't worry about them
435   // for now.
436   if (Subtarget->hasBFE())
437     setHasExtractBitsInsn(true);
438 
439   // Clamp modifier on add/sub
440   if (Subtarget->hasIntClamp()) {
441     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
442     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
443   }
444 
445   if (Subtarget->hasAddNoCarry()) {
446     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
447     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
448     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
449     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
450   }
451 
452   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
453   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
454   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
455   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
456 
457 
458   // These are really only legal for ieee_mode functions. We should be avoiding
459   // them for functions that don't have ieee_mode enabled, so just say they are
460   // legal.
461   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
462   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
463   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
464   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
465 
466 
467   if (Subtarget->haveRoundOpsF64()) {
468     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
469     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
470     setOperationAction(ISD::FRINT, MVT::f64, Legal);
471   } else {
472     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
473     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
474     setOperationAction(ISD::FRINT, MVT::f64, Custom);
475     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
476   }
477 
478   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
479 
480   setOperationAction(ISD::FSIN, MVT::f32, Custom);
481   setOperationAction(ISD::FCOS, MVT::f32, Custom);
482   setOperationAction(ISD::FDIV, MVT::f32, Custom);
483   setOperationAction(ISD::FDIV, MVT::f64, Custom);
484 
485   if (Subtarget->has16BitInsts()) {
486     setOperationAction(ISD::Constant, MVT::i16, Legal);
487 
488     setOperationAction(ISD::SMIN, MVT::i16, Legal);
489     setOperationAction(ISD::SMAX, MVT::i16, Legal);
490 
491     setOperationAction(ISD::UMIN, MVT::i16, Legal);
492     setOperationAction(ISD::UMAX, MVT::i16, Legal);
493 
494     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
495     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
496 
497     setOperationAction(ISD::ROTR, MVT::i16, Expand);
498     setOperationAction(ISD::ROTL, MVT::i16, Expand);
499 
500     setOperationAction(ISD::SDIV, MVT::i16, Promote);
501     setOperationAction(ISD::UDIV, MVT::i16, Promote);
502     setOperationAction(ISD::SREM, MVT::i16, Promote);
503     setOperationAction(ISD::UREM, MVT::i16, Promote);
504     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
505     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
506 
507     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
508 
509     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
510     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
511     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
513     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
514 
515     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
516 
517     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
518 
519     setOperationAction(ISD::LOAD, MVT::i16, Custom);
520 
521     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
522 
523     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
524     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
525     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
526     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
527 
528     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
529     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
530 
531     // F16 - Constant Actions.
532     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
533 
534     // F16 - Load/Store Actions.
535     setOperationAction(ISD::LOAD, MVT::f16, Promote);
536     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
537     setOperationAction(ISD::STORE, MVT::f16, Promote);
538     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
539 
540     // F16 - VOP1 Actions.
541     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
542     setOperationAction(ISD::FCOS, MVT::f16, Custom);
543     setOperationAction(ISD::FSIN, MVT::f16, Custom);
544 
545     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
546     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
547 
548     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
549     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
550     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
551     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
552     setOperationAction(ISD::FROUND, MVT::f16, Custom);
553 
554     // F16 - VOP2 Actions.
555     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
556     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
557 
558     setOperationAction(ISD::FDIV, MVT::f16, Custom);
559 
560     // F16 - VOP3 Actions.
561     setOperationAction(ISD::FMA, MVT::f16, Legal);
562     if (STI.hasMadF16())
563       setOperationAction(ISD::FMAD, MVT::f16, Legal);
564 
565     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
566       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
567         switch (Op) {
568         case ISD::LOAD:
569         case ISD::STORE:
570         case ISD::BUILD_VECTOR:
571         case ISD::BITCAST:
572         case ISD::EXTRACT_VECTOR_ELT:
573         case ISD::INSERT_VECTOR_ELT:
574         case ISD::INSERT_SUBVECTOR:
575         case ISD::EXTRACT_SUBVECTOR:
576         case ISD::SCALAR_TO_VECTOR:
577           break;
578         case ISD::CONCAT_VECTORS:
579           setOperationAction(Op, VT, Custom);
580           break;
581         default:
582           setOperationAction(Op, VT, Expand);
583           break;
584         }
585       }
586     }
587 
588     // v_perm_b32 can handle either of these.
589     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
590     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
591     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
592 
593     // XXX - Do these do anything? Vector constants turn into build_vector.
594     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
595     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
596 
597     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
598     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
599 
600     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
601     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
602     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
603     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
604 
605     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
606     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
607     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
608     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
609 
610     setOperationAction(ISD::AND, MVT::v2i16, Promote);
611     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
612     setOperationAction(ISD::OR, MVT::v2i16, Promote);
613     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
614     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
615     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
616 
617     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
618     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
619     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
620     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
621 
622     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
623     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
624     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
625     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
626 
627     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
628     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
629     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
630     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
631 
632     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
633     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
634     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
635 
636     if (!Subtarget->hasVOP3PInsts()) {
637       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
638       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
639     }
640 
641     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
642     // This isn't really legal, but this avoids the legalizer unrolling it (and
643     // allows matching fneg (fabs x) patterns)
644     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
645 
646     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
647     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
648     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
649     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
650 
651     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
652     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
653 
654     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
655     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
656   }
657 
658   if (Subtarget->hasVOP3PInsts()) {
659     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
660     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
661     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
662     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
663     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
664     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
665     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
666     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
667     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
668     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
669 
670     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
671     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
672     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
673     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
674 
675     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
676     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
677     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
678 
679     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
680     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
681 
682     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
683 
684     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
685     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
686 
687     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
688     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
689 
690     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
691     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
692     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
693     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
694     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
695     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
696 
697     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
698     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
699     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
700     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
701 
702     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
703     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
704     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
705     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
706 
707     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
708     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
709     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
710 
711     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
712     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
713 
714     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
715     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
716     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
717 
718     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
719     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
720     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
721   }
722 
723   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
724   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
725 
726   if (Subtarget->has16BitInsts()) {
727     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
728     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
729     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
730     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
731   } else {
732     // Legalization hack.
733     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
734     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
735 
736     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
737     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
738   }
739 
740   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
741     setOperationAction(ISD::SELECT, VT, Custom);
742   }
743 
744   setOperationAction(ISD::SMULO, MVT::i64, Custom);
745   setOperationAction(ISD::UMULO, MVT::i64, Custom);
746 
747   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
748   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
749   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
750   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
751   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
752   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
753   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
754 
755   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
756   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
757   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
758   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
759   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
760   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
761   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
762   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
763   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
764   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
765   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
766 
767   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
768   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
769   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
770   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
771   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
772   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
773   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
774   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
775   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
776   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
777 
778   setTargetDAGCombine(ISD::ADD);
779   setTargetDAGCombine(ISD::ADDCARRY);
780   setTargetDAGCombine(ISD::SUB);
781   setTargetDAGCombine(ISD::SUBCARRY);
782   setTargetDAGCombine(ISD::FADD);
783   setTargetDAGCombine(ISD::FSUB);
784   setTargetDAGCombine(ISD::FMINNUM);
785   setTargetDAGCombine(ISD::FMAXNUM);
786   setTargetDAGCombine(ISD::FMINNUM_IEEE);
787   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
788   setTargetDAGCombine(ISD::FMA);
789   setTargetDAGCombine(ISD::SMIN);
790   setTargetDAGCombine(ISD::SMAX);
791   setTargetDAGCombine(ISD::UMIN);
792   setTargetDAGCombine(ISD::UMAX);
793   setTargetDAGCombine(ISD::SETCC);
794   setTargetDAGCombine(ISD::AND);
795   setTargetDAGCombine(ISD::OR);
796   setTargetDAGCombine(ISD::XOR);
797   setTargetDAGCombine(ISD::SINT_TO_FP);
798   setTargetDAGCombine(ISD::UINT_TO_FP);
799   setTargetDAGCombine(ISD::FCANONICALIZE);
800   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
801   setTargetDAGCombine(ISD::ZERO_EXTEND);
802   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
803   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
804   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
805 
806   // All memory operations. Some folding on the pointer operand is done to help
807   // matching the constant offsets in the addressing modes.
808   setTargetDAGCombine(ISD::LOAD);
809   setTargetDAGCombine(ISD::STORE);
810   setTargetDAGCombine(ISD::ATOMIC_LOAD);
811   setTargetDAGCombine(ISD::ATOMIC_STORE);
812   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
813   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
814   setTargetDAGCombine(ISD::ATOMIC_SWAP);
815   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
816   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
817   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
818   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
819   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
820   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
821   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
822   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
823   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
824   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
825   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
826   setTargetDAGCombine(ISD::INTRINSIC_VOID);
827   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
828 
829   // FIXME: In other contexts we pretend this is a per-function property.
830   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
831 
832   setSchedulingPreference(Sched::RegPressure);
833 }
834 
835 const GCNSubtarget *SITargetLowering::getSubtarget() const {
836   return Subtarget;
837 }
838 
839 //===----------------------------------------------------------------------===//
840 // TargetLowering queries
841 //===----------------------------------------------------------------------===//
842 
843 // v_mad_mix* support a conversion from f16 to f32.
844 //
845 // There is only one special case when denormals are enabled we don't currently,
846 // where this is OK to use.
847 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
848                                        EVT DestVT, EVT SrcVT) const {
849   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
850           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
851     DestVT.getScalarType() == MVT::f32 &&
852     SrcVT.getScalarType() == MVT::f16 &&
853     // TODO: This probably only requires no input flushing?
854     !hasFP32Denormals(DAG.getMachineFunction());
855 }
856 
857 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
858   // SI has some legal vector types, but no legal vector operations. Say no
859   // shuffles are legal in order to prefer scalarizing some vector operations.
860   return false;
861 }
862 
863 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
864                                                     CallingConv::ID CC,
865                                                     EVT VT) const {
866   if (CC == CallingConv::AMDGPU_KERNEL)
867     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
868 
869   if (VT.isVector()) {
870     EVT ScalarVT = VT.getScalarType();
871     unsigned Size = ScalarVT.getSizeInBits();
872     if (Size == 16) {
873       if (Subtarget->has16BitInsts())
874         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
875       return VT.isInteger() ? MVT::i32 : MVT::f32;
876     }
877 
878     if (Size < 16)
879       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
880     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
881   }
882 
883   if (VT.getSizeInBits() > 32)
884     return MVT::i32;
885 
886   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
887 }
888 
889 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
890                                                          CallingConv::ID CC,
891                                                          EVT VT) const {
892   if (CC == CallingConv::AMDGPU_KERNEL)
893     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
894 
895   if (VT.isVector()) {
896     unsigned NumElts = VT.getVectorNumElements();
897     EVT ScalarVT = VT.getScalarType();
898     unsigned Size = ScalarVT.getSizeInBits();
899 
900     // FIXME: Should probably promote 8-bit vectors to i16.
901     if (Size == 16 && Subtarget->has16BitInsts())
902       return (NumElts + 1) / 2;
903 
904     if (Size <= 32)
905       return NumElts;
906 
907     if (Size > 32)
908       return NumElts * ((Size + 31) / 32);
909   } else if (VT.getSizeInBits() > 32)
910     return (VT.getSizeInBits() + 31) / 32;
911 
912   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
913 }
914 
915 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
916   LLVMContext &Context, CallingConv::ID CC,
917   EVT VT, EVT &IntermediateVT,
918   unsigned &NumIntermediates, MVT &RegisterVT) const {
919   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
920     unsigned NumElts = VT.getVectorNumElements();
921     EVT ScalarVT = VT.getScalarType();
922     unsigned Size = ScalarVT.getSizeInBits();
923     // FIXME: We should fix the ABI to be the same on targets without 16-bit
924     // support, but unless we can properly handle 3-vectors, it will be still be
925     // inconsistent.
926     if (Size == 16 && Subtarget->has16BitInsts()) {
927       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
928       IntermediateVT = RegisterVT;
929       NumIntermediates = (NumElts + 1) / 2;
930       return NumIntermediates;
931     }
932 
933     if (Size == 32) {
934       RegisterVT = ScalarVT.getSimpleVT();
935       IntermediateVT = RegisterVT;
936       NumIntermediates = NumElts;
937       return NumIntermediates;
938     }
939 
940     if (Size < 16 && Subtarget->has16BitInsts()) {
941       // FIXME: Should probably form v2i16 pieces
942       RegisterVT = MVT::i16;
943       IntermediateVT = ScalarVT;
944       NumIntermediates = NumElts;
945       return NumIntermediates;
946     }
947 
948 
949     if (Size != 16 && Size <= 32) {
950       RegisterVT = MVT::i32;
951       IntermediateVT = ScalarVT;
952       NumIntermediates = NumElts;
953       return NumIntermediates;
954     }
955 
956     if (Size > 32) {
957       RegisterVT = MVT::i32;
958       IntermediateVT = RegisterVT;
959       NumIntermediates = NumElts * ((Size + 31) / 32);
960       return NumIntermediates;
961     }
962   }
963 
964   return TargetLowering::getVectorTypeBreakdownForCallingConv(
965     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
966 }
967 
968 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
969   assert(DMaskLanes != 0);
970 
971   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
972     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
973     return EVT::getVectorVT(Ty->getContext(),
974                             EVT::getEVT(VT->getElementType()),
975                             NumElts);
976   }
977 
978   return EVT::getEVT(Ty);
979 }
980 
981 // Peek through TFE struct returns to only use the data size.
982 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
983   auto *ST = dyn_cast<StructType>(Ty);
984   if (!ST)
985     return memVTFromImageData(Ty, DMaskLanes);
986 
987   // Some intrinsics return an aggregate type - special case to work out the
988   // correct memVT.
989   //
990   // Only limited forms of aggregate type currently expected.
991   if (ST->getNumContainedTypes() != 2 ||
992       !ST->getContainedType(1)->isIntegerTy(32))
993     return EVT();
994   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
995 }
996 
997 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
998                                           const CallInst &CI,
999                                           MachineFunction &MF,
1000                                           unsigned IntrID) const {
1001   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1002           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1003     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1004                                                   (Intrinsic::ID)IntrID);
1005     if (Attr.hasFnAttribute(Attribute::ReadNone))
1006       return false;
1007 
1008     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1009 
1010     if (RsrcIntr->IsImage) {
1011       Info.ptrVal = MFI->getImagePSV(
1012         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1013         CI.getArgOperand(RsrcIntr->RsrcArg));
1014       Info.align.reset();
1015     } else {
1016       Info.ptrVal = MFI->getBufferPSV(
1017         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1018         CI.getArgOperand(RsrcIntr->RsrcArg));
1019     }
1020 
1021     Info.flags = MachineMemOperand::MODereferenceable;
1022     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1023       unsigned DMaskLanes = 4;
1024 
1025       if (RsrcIntr->IsImage) {
1026         const AMDGPU::ImageDimIntrinsicInfo *Intr
1027           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1028         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1029           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1030 
1031         if (!BaseOpcode->Gather4) {
1032           // If this isn't a gather, we may have excess loaded elements in the
1033           // IR type. Check the dmask for the real number of elements loaded.
1034           unsigned DMask
1035             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1036           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1037         }
1038 
1039         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1040       } else
1041         Info.memVT = EVT::getEVT(CI.getType());
1042 
1043       // FIXME: What does alignment mean for an image?
1044       Info.opc = ISD::INTRINSIC_W_CHAIN;
1045       Info.flags |= MachineMemOperand::MOLoad;
1046     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1047       Info.opc = ISD::INTRINSIC_VOID;
1048 
1049       Type *DataTy = CI.getArgOperand(0)->getType();
1050       if (RsrcIntr->IsImage) {
1051         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1052         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1053         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1054       } else
1055         Info.memVT = EVT::getEVT(DataTy);
1056 
1057       Info.flags |= MachineMemOperand::MOStore;
1058     } else {
1059       // Atomic
1060       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1061                                             ISD::INTRINSIC_W_CHAIN;
1062       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1063       Info.flags = MachineMemOperand::MOLoad |
1064                    MachineMemOperand::MOStore |
1065                    MachineMemOperand::MODereferenceable;
1066 
1067       // XXX - Should this be volatile without known ordering?
1068       Info.flags |= MachineMemOperand::MOVolatile;
1069     }
1070     return true;
1071   }
1072 
1073   switch (IntrID) {
1074   case Intrinsic::amdgcn_atomic_inc:
1075   case Intrinsic::amdgcn_atomic_dec:
1076   case Intrinsic::amdgcn_ds_ordered_add:
1077   case Intrinsic::amdgcn_ds_ordered_swap:
1078   case Intrinsic::amdgcn_ds_fadd:
1079   case Intrinsic::amdgcn_ds_fmin:
1080   case Intrinsic::amdgcn_ds_fmax: {
1081     Info.opc = ISD::INTRINSIC_W_CHAIN;
1082     Info.memVT = MVT::getVT(CI.getType());
1083     Info.ptrVal = CI.getOperand(0);
1084     Info.align.reset();
1085     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1086 
1087     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1088     if (!Vol->isZero())
1089       Info.flags |= MachineMemOperand::MOVolatile;
1090 
1091     return true;
1092   }
1093   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1094     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1095 
1096     Info.opc = ISD::INTRINSIC_W_CHAIN;
1097     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1098     Info.ptrVal = MFI->getBufferPSV(
1099       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1100       CI.getArgOperand(1));
1101     Info.align.reset();
1102     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1103 
1104     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1105     if (!Vol || !Vol->isZero())
1106       Info.flags |= MachineMemOperand::MOVolatile;
1107 
1108     return true;
1109   }
1110   case Intrinsic::amdgcn_ds_append:
1111   case Intrinsic::amdgcn_ds_consume: {
1112     Info.opc = ISD::INTRINSIC_W_CHAIN;
1113     Info.memVT = MVT::getVT(CI.getType());
1114     Info.ptrVal = CI.getOperand(0);
1115     Info.align.reset();
1116     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1117 
1118     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1119     if (!Vol->isZero())
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121 
1122     return true;
1123   }
1124   case Intrinsic::amdgcn_global_atomic_csub: {
1125     Info.opc = ISD::INTRINSIC_W_CHAIN;
1126     Info.memVT = MVT::getVT(CI.getType());
1127     Info.ptrVal = CI.getOperand(0);
1128     Info.align.reset();
1129     Info.flags = MachineMemOperand::MOLoad |
1130                  MachineMemOperand::MOStore |
1131                  MachineMemOperand::MOVolatile;
1132     return true;
1133   }
1134   case Intrinsic::amdgcn_global_atomic_fadd: {
1135     Info.opc = ISD::INTRINSIC_W_CHAIN;
1136     Info.memVT = MVT::getVT(CI.getType());
1137     Info.ptrVal = CI.getOperand(0);
1138     Info.align.reset();
1139     Info.flags = MachineMemOperand::MOLoad |
1140                  MachineMemOperand::MOStore |
1141                  MachineMemOperand::MODereferenceable |
1142                  MachineMemOperand::MOVolatile;
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147     Info.opc = ISD::INTRINSIC_W_CHAIN;
1148     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1149     Info.ptrVal = MFI->getImagePSV(
1150         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1151     Info.align.reset();
1152     Info.flags = MachineMemOperand::MOLoad |
1153                  MachineMemOperand::MODereferenceable;
1154     return true;
1155   }
1156   case Intrinsic::amdgcn_ds_gws_init:
1157   case Intrinsic::amdgcn_ds_gws_barrier:
1158   case Intrinsic::amdgcn_ds_gws_sema_v:
1159   case Intrinsic::amdgcn_ds_gws_sema_br:
1160   case Intrinsic::amdgcn_ds_gws_sema_p:
1161   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1162     Info.opc = ISD::INTRINSIC_VOID;
1163 
1164     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1165     Info.ptrVal =
1166         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1167 
1168     // This is an abstract access, but we need to specify a type and size.
1169     Info.memVT = MVT::i32;
1170     Info.size = 4;
1171     Info.align = Align(4);
1172 
1173     Info.flags = MachineMemOperand::MOStore;
1174     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1175       Info.flags = MachineMemOperand::MOLoad;
1176     return true;
1177   }
1178   default:
1179     return false;
1180   }
1181 }
1182 
1183 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1184                                             SmallVectorImpl<Value*> &Ops,
1185                                             Type *&AccessTy) const {
1186   switch (II->getIntrinsicID()) {
1187   case Intrinsic::amdgcn_atomic_inc:
1188   case Intrinsic::amdgcn_atomic_dec:
1189   case Intrinsic::amdgcn_ds_ordered_add:
1190   case Intrinsic::amdgcn_ds_ordered_swap:
1191   case Intrinsic::amdgcn_ds_append:
1192   case Intrinsic::amdgcn_ds_consume:
1193   case Intrinsic::amdgcn_ds_fadd:
1194   case Intrinsic::amdgcn_ds_fmin:
1195   case Intrinsic::amdgcn_ds_fmax:
1196   case Intrinsic::amdgcn_global_atomic_fadd:
1197   case Intrinsic::amdgcn_global_atomic_csub: {
1198     Value *Ptr = II->getArgOperand(0);
1199     AccessTy = II->getType();
1200     Ops.push_back(Ptr);
1201     return true;
1202   }
1203   default:
1204     return false;
1205   }
1206 }
1207 
1208 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1209   if (!Subtarget->hasFlatInstOffsets()) {
1210     // Flat instructions do not have offsets, and only have the register
1211     // address.
1212     return AM.BaseOffs == 0 && AM.Scale == 0;
1213   }
1214 
1215   return AM.Scale == 0 &&
1216          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1217                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1218                                   /*Signed=*/false));
1219 }
1220 
1221 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1222   if (Subtarget->hasFlatGlobalInsts())
1223     return AM.Scale == 0 &&
1224            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1225                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1226                                     /*Signed=*/true));
1227 
1228   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1229       // Assume the we will use FLAT for all global memory accesses
1230       // on VI.
1231       // FIXME: This assumption is currently wrong.  On VI we still use
1232       // MUBUF instructions for the r + i addressing mode.  As currently
1233       // implemented, the MUBUF instructions only work on buffer < 4GB.
1234       // It may be possible to support > 4GB buffers with MUBUF instructions,
1235       // by setting the stride value in the resource descriptor which would
1236       // increase the size limit to (stride * 4GB).  However, this is risky,
1237       // because it has never been validated.
1238     return isLegalFlatAddressingMode(AM);
1239   }
1240 
1241   return isLegalMUBUFAddressingMode(AM);
1242 }
1243 
1244 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1245   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1246   // additionally can do r + r + i with addr64. 32-bit has more addressing
1247   // mode options. Depending on the resource constant, it can also do
1248   // (i64 r0) + (i32 r1) * (i14 i).
1249   //
1250   // Private arrays end up using a scratch buffer most of the time, so also
1251   // assume those use MUBUF instructions. Scratch loads / stores are currently
1252   // implemented as mubuf instructions with offen bit set, so slightly
1253   // different than the normal addr64.
1254   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1255     return false;
1256 
1257   // FIXME: Since we can split immediate into soffset and immediate offset,
1258   // would it make sense to allow any immediate?
1259 
1260   switch (AM.Scale) {
1261   case 0: // r + i or just i, depending on HasBaseReg.
1262     return true;
1263   case 1:
1264     return true; // We have r + r or r + i.
1265   case 2:
1266     if (AM.HasBaseReg) {
1267       // Reject 2 * r + r.
1268       return false;
1269     }
1270 
1271     // Allow 2 * r as r + r
1272     // Or  2 * r + i is allowed as r + r + i.
1273     return true;
1274   default: // Don't allow n * r
1275     return false;
1276   }
1277 }
1278 
1279 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1280                                              const AddrMode &AM, Type *Ty,
1281                                              unsigned AS, Instruction *I) const {
1282   // No global is ever allowed as a base.
1283   if (AM.BaseGV)
1284     return false;
1285 
1286   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1287     return isLegalGlobalAddressingMode(AM);
1288 
1289   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1290       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1291       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1292     // If the offset isn't a multiple of 4, it probably isn't going to be
1293     // correctly aligned.
1294     // FIXME: Can we get the real alignment here?
1295     if (AM.BaseOffs % 4 != 0)
1296       return isLegalMUBUFAddressingMode(AM);
1297 
1298     // There are no SMRD extloads, so if we have to do a small type access we
1299     // will use a MUBUF load.
1300     // FIXME?: We also need to do this if unaligned, but we don't know the
1301     // alignment here.
1302     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1303       return isLegalGlobalAddressingMode(AM);
1304 
1305     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1306       // SMRD instructions have an 8-bit, dword offset on SI.
1307       if (!isUInt<8>(AM.BaseOffs / 4))
1308         return false;
1309     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1310       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1311       // in 8-bits, it can use a smaller encoding.
1312       if (!isUInt<32>(AM.BaseOffs / 4))
1313         return false;
1314     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1315       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1316       if (!isUInt<20>(AM.BaseOffs))
1317         return false;
1318     } else
1319       llvm_unreachable("unhandled generation");
1320 
1321     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1322       return true;
1323 
1324     if (AM.Scale == 1 && AM.HasBaseReg)
1325       return true;
1326 
1327     return false;
1328 
1329   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1330     return isLegalMUBUFAddressingMode(AM);
1331   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1332              AS == AMDGPUAS::REGION_ADDRESS) {
1333     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1334     // field.
1335     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1336     // an 8-bit dword offset but we don't know the alignment here.
1337     if (!isUInt<16>(AM.BaseOffs))
1338       return false;
1339 
1340     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1341       return true;
1342 
1343     if (AM.Scale == 1 && AM.HasBaseReg)
1344       return true;
1345 
1346     return false;
1347   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1348              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1349     // For an unknown address space, this usually means that this is for some
1350     // reason being used for pure arithmetic, and not based on some addressing
1351     // computation. We don't have instructions that compute pointers with any
1352     // addressing modes, so treat them as having no offset like flat
1353     // instructions.
1354     return isLegalFlatAddressingMode(AM);
1355   }
1356 
1357   // Assume a user alias of global for unknown address spaces.
1358   return isLegalGlobalAddressingMode(AM);
1359 }
1360 
1361 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1362                                         const SelectionDAG &DAG) const {
1363   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1364     return (MemVT.getSizeInBits() <= 4 * 32);
1365   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1366     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1367     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1368   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1369     return (MemVT.getSizeInBits() <= 2 * 32);
1370   }
1371   return true;
1372 }
1373 
1374 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1375     unsigned Size, unsigned AddrSpace, Align Alignment,
1376     MachineMemOperand::Flags Flags, bool *IsFast) const {
1377   if (IsFast)
1378     *IsFast = false;
1379 
1380   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1381       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1382     // Check if alignment requirements for ds_read/write instructions are
1383     // disabled.
1384     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1385         !Subtarget->hasLDSMisalignedBug()) {
1386       if (IsFast)
1387         *IsFast = Alignment != Align(2);
1388       return true;
1389     }
1390 
1391     if (Size == 64) {
1392       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1393       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1394       // with adjacent offsets.
1395       bool AlignedBy4 = Alignment >= Align(4);
1396       if (IsFast)
1397         *IsFast = AlignedBy4;
1398 
1399       return AlignedBy4;
1400     }
1401     if (Size == 96) {
1402       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1403       bool Aligned = Alignment >= Align(16);
1404       if (IsFast)
1405         *IsFast = Aligned;
1406 
1407       return Aligned;
1408     }
1409     if (Size == 128) {
1410       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1411       // can do a 8 byte aligned, 16 byte access in a single operation using
1412       // ds_read2/write2_b64.
1413       bool Aligned = Alignment >= Align(8);
1414       if (IsFast)
1415         *IsFast = Aligned;
1416 
1417       return Aligned;
1418     }
1419   }
1420 
1421   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1422     bool AlignedBy4 = Alignment >= Align(4);
1423     if (IsFast)
1424       *IsFast = AlignedBy4;
1425 
1426     return AlignedBy4 ||
1427            Subtarget->enableFlatScratch() ||
1428            Subtarget->hasUnalignedScratchAccess();
1429   }
1430 
1431   // FIXME: We have to be conservative here and assume that flat operations
1432   // will access scratch.  If we had access to the IR function, then we
1433   // could determine if any private memory was used in the function.
1434   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1435       !Subtarget->hasUnalignedScratchAccess()) {
1436     bool AlignedBy4 = Alignment >= Align(4);
1437     if (IsFast)
1438       *IsFast = AlignedBy4;
1439 
1440     return AlignedBy4;
1441   }
1442 
1443   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1444       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1445         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1446     // If we have an uniform constant load, it still requires using a slow
1447     // buffer instruction if unaligned.
1448     if (IsFast) {
1449       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1450       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1451       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1452                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1453         Alignment >= Align(4) : Alignment != Align(2);
1454     }
1455 
1456     return true;
1457   }
1458 
1459   // Smaller than dword value must be aligned.
1460   if (Size < 32)
1461     return false;
1462 
1463   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1464   // byte-address are ignored, thus forcing Dword alignment.
1465   // This applies to private, global, and constant memory.
1466   if (IsFast)
1467     *IsFast = true;
1468 
1469   return Size >= 32 && Alignment >= Align(4);
1470 }
1471 
1472 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1473     EVT VT, unsigned AddrSpace, unsigned Alignment,
1474     MachineMemOperand::Flags Flags, bool *IsFast) const {
1475   if (IsFast)
1476     *IsFast = false;
1477 
1478   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1479   // which isn't a simple VT.
1480   // Until MVT is extended to handle this, simply check for the size and
1481   // rely on the condition below: allow accesses if the size is a multiple of 4.
1482   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1483                            VT.getStoreSize() > 16)) {
1484     return false;
1485   }
1486 
1487   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1488                                             Align(Alignment), Flags, IsFast);
1489 }
1490 
1491 EVT SITargetLowering::getOptimalMemOpType(
1492     const MemOp &Op, const AttributeList &FuncAttributes) const {
1493   // FIXME: Should account for address space here.
1494 
1495   // The default fallback uses the private pointer size as a guess for a type to
1496   // use. Make sure we switch these to 64-bit accesses.
1497 
1498   if (Op.size() >= 16 &&
1499       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1500     return MVT::v4i32;
1501 
1502   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1503     return MVT::v2i32;
1504 
1505   // Use the default.
1506   return MVT::Other;
1507 }
1508 
1509 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1510   const MemSDNode *MemNode = cast<MemSDNode>(N);
1511   const Value *Ptr = MemNode->getMemOperand()->getValue();
1512   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1513   return I && I->getMetadata("amdgpu.noclobber");
1514 }
1515 
1516 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1517   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1518          AS == AMDGPUAS::PRIVATE_ADDRESS;
1519 }
1520 
1521 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1522                                            unsigned DestAS) const {
1523   // Flat -> private/local is a simple truncate.
1524   // Flat -> global is no-op
1525   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1526     return true;
1527 
1528   const GCNTargetMachine &TM =
1529       static_cast<const GCNTargetMachine &>(getTargetMachine());
1530   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1531 }
1532 
1533 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1534   const MemSDNode *MemNode = cast<MemSDNode>(N);
1535 
1536   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1537 }
1538 
1539 TargetLoweringBase::LegalizeTypeAction
1540 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1541   int NumElts = VT.getVectorNumElements();
1542   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1543     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1544   return TargetLoweringBase::getPreferredVectorAction(VT);
1545 }
1546 
1547 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1548                                                          Type *Ty) const {
1549   // FIXME: Could be smarter if called for vector constants.
1550   return true;
1551 }
1552 
1553 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1554   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1555     switch (Op) {
1556     case ISD::LOAD:
1557     case ISD::STORE:
1558 
1559     // These operations are done with 32-bit instructions anyway.
1560     case ISD::AND:
1561     case ISD::OR:
1562     case ISD::XOR:
1563     case ISD::SELECT:
1564       // TODO: Extensions?
1565       return true;
1566     default:
1567       return false;
1568     }
1569   }
1570 
1571   // SimplifySetCC uses this function to determine whether or not it should
1572   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1573   if (VT == MVT::i1 && Op == ISD::SETCC)
1574     return false;
1575 
1576   return TargetLowering::isTypeDesirableForOp(Op, VT);
1577 }
1578 
1579 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1580                                                    const SDLoc &SL,
1581                                                    SDValue Chain,
1582                                                    uint64_t Offset) const {
1583   const DataLayout &DL = DAG.getDataLayout();
1584   MachineFunction &MF = DAG.getMachineFunction();
1585   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1586 
1587   const ArgDescriptor *InputPtrReg;
1588   const TargetRegisterClass *RC;
1589   LLT ArgTy;
1590 
1591   std::tie(InputPtrReg, RC, ArgTy) =
1592       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1593 
1594   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1595   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1596   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1597     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1598 
1599   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1600 }
1601 
1602 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1603                                             const SDLoc &SL) const {
1604   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1605                                                FIRST_IMPLICIT);
1606   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1607 }
1608 
1609 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1610                                          const SDLoc &SL, SDValue Val,
1611                                          bool Signed,
1612                                          const ISD::InputArg *Arg) const {
1613   // First, if it is a widened vector, narrow it.
1614   if (VT.isVector() &&
1615       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1616     EVT NarrowedVT =
1617         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1618                          VT.getVectorNumElements());
1619     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1620                       DAG.getConstant(0, SL, MVT::i32));
1621   }
1622 
1623   // Then convert the vector elements or scalar value.
1624   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1625       VT.bitsLT(MemVT)) {
1626     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1627     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1628   }
1629 
1630   if (MemVT.isFloatingPoint())
1631     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1632   else if (Signed)
1633     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1634   else
1635     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1636 
1637   return Val;
1638 }
1639 
1640 SDValue SITargetLowering::lowerKernargMemParameter(
1641     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1642     uint64_t Offset, Align Alignment, bool Signed,
1643     const ISD::InputArg *Arg) const {
1644   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1645 
1646   // Try to avoid using an extload by loading earlier than the argument address,
1647   // and extracting the relevant bits. The load should hopefully be merged with
1648   // the previous argument.
1649   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1650     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1651     int64_t AlignDownOffset = alignDown(Offset, 4);
1652     int64_t OffsetDiff = Offset - AlignDownOffset;
1653 
1654     EVT IntVT = MemVT.changeTypeToInteger();
1655 
1656     // TODO: If we passed in the base kernel offset we could have a better
1657     // alignment than 4, but we don't really need it.
1658     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1659     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1660                                MachineMemOperand::MODereferenceable |
1661                                    MachineMemOperand::MOInvariant);
1662 
1663     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1664     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1665 
1666     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1667     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1668     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1669 
1670 
1671     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1672   }
1673 
1674   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1675   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1676                              MachineMemOperand::MODereferenceable |
1677                                  MachineMemOperand::MOInvariant);
1678 
1679   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1680   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1681 }
1682 
1683 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1684                                               const SDLoc &SL, SDValue Chain,
1685                                               const ISD::InputArg &Arg) const {
1686   MachineFunction &MF = DAG.getMachineFunction();
1687   MachineFrameInfo &MFI = MF.getFrameInfo();
1688 
1689   if (Arg.Flags.isByVal()) {
1690     unsigned Size = Arg.Flags.getByValSize();
1691     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1692     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1693   }
1694 
1695   unsigned ArgOffset = VA.getLocMemOffset();
1696   unsigned ArgSize = VA.getValVT().getStoreSize();
1697 
1698   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1699 
1700   // Create load nodes to retrieve arguments from the stack.
1701   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1702   SDValue ArgValue;
1703 
1704   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1705   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1706   MVT MemVT = VA.getValVT();
1707 
1708   switch (VA.getLocInfo()) {
1709   default:
1710     break;
1711   case CCValAssign::BCvt:
1712     MemVT = VA.getLocVT();
1713     break;
1714   case CCValAssign::SExt:
1715     ExtType = ISD::SEXTLOAD;
1716     break;
1717   case CCValAssign::ZExt:
1718     ExtType = ISD::ZEXTLOAD;
1719     break;
1720   case CCValAssign::AExt:
1721     ExtType = ISD::EXTLOAD;
1722     break;
1723   }
1724 
1725   ArgValue = DAG.getExtLoad(
1726     ExtType, SL, VA.getLocVT(), Chain, FIN,
1727     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1728     MemVT);
1729   return ArgValue;
1730 }
1731 
1732 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1733   const SIMachineFunctionInfo &MFI,
1734   EVT VT,
1735   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1736   const ArgDescriptor *Reg;
1737   const TargetRegisterClass *RC;
1738   LLT Ty;
1739 
1740   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1741   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1742 }
1743 
1744 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1745                                CallingConv::ID CallConv,
1746                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1747                                FunctionType *FType,
1748                                SIMachineFunctionInfo *Info) {
1749   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1750     const ISD::InputArg *Arg = &Ins[I];
1751 
1752     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1753            "vector type argument should have been split");
1754 
1755     // First check if it's a PS input addr.
1756     if (CallConv == CallingConv::AMDGPU_PS &&
1757         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1758       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1759 
1760       // Inconveniently only the first part of the split is marked as isSplit,
1761       // so skip to the end. We only want to increment PSInputNum once for the
1762       // entire split argument.
1763       if (Arg->Flags.isSplit()) {
1764         while (!Arg->Flags.isSplitEnd()) {
1765           assert((!Arg->VT.isVector() ||
1766                   Arg->VT.getScalarSizeInBits() == 16) &&
1767                  "unexpected vector split in ps argument type");
1768           if (!SkipArg)
1769             Splits.push_back(*Arg);
1770           Arg = &Ins[++I];
1771         }
1772       }
1773 
1774       if (SkipArg) {
1775         // We can safely skip PS inputs.
1776         Skipped.set(Arg->getOrigArgIndex());
1777         ++PSInputNum;
1778         continue;
1779       }
1780 
1781       Info->markPSInputAllocated(PSInputNum);
1782       if (Arg->Used)
1783         Info->markPSInputEnabled(PSInputNum);
1784 
1785       ++PSInputNum;
1786     }
1787 
1788     Splits.push_back(*Arg);
1789   }
1790 }
1791 
1792 // Allocate special inputs passed in VGPRs.
1793 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1794                                                       MachineFunction &MF,
1795                                                       const SIRegisterInfo &TRI,
1796                                                       SIMachineFunctionInfo &Info) const {
1797   const LLT S32 = LLT::scalar(32);
1798   MachineRegisterInfo &MRI = MF.getRegInfo();
1799 
1800   if (Info.hasWorkItemIDX()) {
1801     Register Reg = AMDGPU::VGPR0;
1802     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1803 
1804     CCInfo.AllocateReg(Reg);
1805     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1806   }
1807 
1808   if (Info.hasWorkItemIDY()) {
1809     Register Reg = AMDGPU::VGPR1;
1810     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1811 
1812     CCInfo.AllocateReg(Reg);
1813     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1814   }
1815 
1816   if (Info.hasWorkItemIDZ()) {
1817     Register Reg = AMDGPU::VGPR2;
1818     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1819 
1820     CCInfo.AllocateReg(Reg);
1821     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1822   }
1823 }
1824 
1825 // Try to allocate a VGPR at the end of the argument list, or if no argument
1826 // VGPRs are left allocating a stack slot.
1827 // If \p Mask is is given it indicates bitfield position in the register.
1828 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1829 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1830                                          ArgDescriptor Arg = ArgDescriptor()) {
1831   if (Arg.isSet())
1832     return ArgDescriptor::createArg(Arg, Mask);
1833 
1834   ArrayRef<MCPhysReg> ArgVGPRs
1835     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1836   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1837   if (RegIdx == ArgVGPRs.size()) {
1838     // Spill to stack required.
1839     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1840 
1841     return ArgDescriptor::createStack(Offset, Mask);
1842   }
1843 
1844   unsigned Reg = ArgVGPRs[RegIdx];
1845   Reg = CCInfo.AllocateReg(Reg);
1846   assert(Reg != AMDGPU::NoRegister);
1847 
1848   MachineFunction &MF = CCInfo.getMachineFunction();
1849   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1850   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1851   return ArgDescriptor::createRegister(Reg, Mask);
1852 }
1853 
1854 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1855                                              const TargetRegisterClass *RC,
1856                                              unsigned NumArgRegs) {
1857   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1858   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1859   if (RegIdx == ArgSGPRs.size())
1860     report_fatal_error("ran out of SGPRs for arguments");
1861 
1862   unsigned Reg = ArgSGPRs[RegIdx];
1863   Reg = CCInfo.AllocateReg(Reg);
1864   assert(Reg != AMDGPU::NoRegister);
1865 
1866   MachineFunction &MF = CCInfo.getMachineFunction();
1867   MF.addLiveIn(Reg, RC);
1868   return ArgDescriptor::createRegister(Reg);
1869 }
1870 
1871 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1872   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1873 }
1874 
1875 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1876   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1877 }
1878 
1879 /// Allocate implicit function VGPR arguments at the end of allocated user
1880 /// arguments.
1881 void SITargetLowering::allocateSpecialInputVGPRs(
1882   CCState &CCInfo, MachineFunction &MF,
1883   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1884   const unsigned Mask = 0x3ff;
1885   ArgDescriptor Arg;
1886 
1887   if (Info.hasWorkItemIDX()) {
1888     Arg = allocateVGPR32Input(CCInfo, Mask);
1889     Info.setWorkItemIDX(Arg);
1890   }
1891 
1892   if (Info.hasWorkItemIDY()) {
1893     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1894     Info.setWorkItemIDY(Arg);
1895   }
1896 
1897   if (Info.hasWorkItemIDZ())
1898     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1899 }
1900 
1901 /// Allocate implicit function VGPR arguments in fixed registers.
1902 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1903   CCState &CCInfo, MachineFunction &MF,
1904   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1905   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1906   if (!Reg)
1907     report_fatal_error("failed to allocated VGPR for implicit arguments");
1908 
1909   const unsigned Mask = 0x3ff;
1910   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1911   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1912   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1913 }
1914 
1915 void SITargetLowering::allocateSpecialInputSGPRs(
1916   CCState &CCInfo,
1917   MachineFunction &MF,
1918   const SIRegisterInfo &TRI,
1919   SIMachineFunctionInfo &Info) const {
1920   auto &ArgInfo = Info.getArgInfo();
1921 
1922   // TODO: Unify handling with private memory pointers.
1923 
1924   if (Info.hasDispatchPtr())
1925     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1926 
1927   if (Info.hasQueuePtr())
1928     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1929 
1930   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1931   // constant offset from the kernarg segment.
1932   if (Info.hasImplicitArgPtr())
1933     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1934 
1935   if (Info.hasDispatchID())
1936     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1937 
1938   // flat_scratch_init is not applicable for non-kernel functions.
1939 
1940   if (Info.hasWorkGroupIDX())
1941     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1942 
1943   if (Info.hasWorkGroupIDY())
1944     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1945 
1946   if (Info.hasWorkGroupIDZ())
1947     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1948 }
1949 
1950 // Allocate special inputs passed in user SGPRs.
1951 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1952                                             MachineFunction &MF,
1953                                             const SIRegisterInfo &TRI,
1954                                             SIMachineFunctionInfo &Info) const {
1955   if (Info.hasImplicitBufferPtr()) {
1956     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1957     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1958     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1959   }
1960 
1961   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1962   if (Info.hasPrivateSegmentBuffer()) {
1963     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1964     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1965     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1966   }
1967 
1968   if (Info.hasDispatchPtr()) {
1969     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
1970     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1971     CCInfo.AllocateReg(DispatchPtrReg);
1972   }
1973 
1974   if (Info.hasQueuePtr()) {
1975     Register QueuePtrReg = Info.addQueuePtr(TRI);
1976     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1977     CCInfo.AllocateReg(QueuePtrReg);
1978   }
1979 
1980   if (Info.hasKernargSegmentPtr()) {
1981     MachineRegisterInfo &MRI = MF.getRegInfo();
1982     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1983     CCInfo.AllocateReg(InputPtrReg);
1984 
1985     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1986     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1987   }
1988 
1989   if (Info.hasDispatchID()) {
1990     Register DispatchIDReg = Info.addDispatchID(TRI);
1991     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1992     CCInfo.AllocateReg(DispatchIDReg);
1993   }
1994 
1995   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
1996     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1997     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1998     CCInfo.AllocateReg(FlatScratchInitReg);
1999   }
2000 
2001   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2002   // these from the dispatch pointer.
2003 }
2004 
2005 // Allocate special input registers that are initialized per-wave.
2006 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2007                                            MachineFunction &MF,
2008                                            SIMachineFunctionInfo &Info,
2009                                            CallingConv::ID CallConv,
2010                                            bool IsShader) const {
2011   if (Info.hasWorkGroupIDX()) {
2012     Register Reg = Info.addWorkGroupIDX();
2013     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2014     CCInfo.AllocateReg(Reg);
2015   }
2016 
2017   if (Info.hasWorkGroupIDY()) {
2018     Register Reg = Info.addWorkGroupIDY();
2019     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2020     CCInfo.AllocateReg(Reg);
2021   }
2022 
2023   if (Info.hasWorkGroupIDZ()) {
2024     Register Reg = Info.addWorkGroupIDZ();
2025     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2026     CCInfo.AllocateReg(Reg);
2027   }
2028 
2029   if (Info.hasWorkGroupInfo()) {
2030     Register Reg = Info.addWorkGroupInfo();
2031     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2032     CCInfo.AllocateReg(Reg);
2033   }
2034 
2035   if (Info.hasPrivateSegmentWaveByteOffset()) {
2036     // Scratch wave offset passed in system SGPR.
2037     unsigned PrivateSegmentWaveByteOffsetReg;
2038 
2039     if (IsShader) {
2040       PrivateSegmentWaveByteOffsetReg =
2041         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2042 
2043       // This is true if the scratch wave byte offset doesn't have a fixed
2044       // location.
2045       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2046         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2047         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2048       }
2049     } else
2050       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2051 
2052     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2053     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2054   }
2055 }
2056 
2057 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2058                                      MachineFunction &MF,
2059                                      const SIRegisterInfo &TRI,
2060                                      SIMachineFunctionInfo &Info) {
2061   // Now that we've figured out where the scratch register inputs are, see if
2062   // should reserve the arguments and use them directly.
2063   MachineFrameInfo &MFI = MF.getFrameInfo();
2064   bool HasStackObjects = MFI.hasStackObjects();
2065   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2066 
2067   // Record that we know we have non-spill stack objects so we don't need to
2068   // check all stack objects later.
2069   if (HasStackObjects)
2070     Info.setHasNonSpillStackObjects(true);
2071 
2072   // Everything live out of a block is spilled with fast regalloc, so it's
2073   // almost certain that spilling will be required.
2074   if (TM.getOptLevel() == CodeGenOpt::None)
2075     HasStackObjects = true;
2076 
2077   // For now assume stack access is needed in any callee functions, so we need
2078   // the scratch registers to pass in.
2079   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2080 
2081   if (!ST.enableFlatScratch()) {
2082     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2083       // If we have stack objects, we unquestionably need the private buffer
2084       // resource. For the Code Object V2 ABI, this will be the first 4 user
2085       // SGPR inputs. We can reserve those and use them directly.
2086 
2087       Register PrivateSegmentBufferReg =
2088           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2089       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2090     } else {
2091       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2092       // We tentatively reserve the last registers (skipping the last registers
2093       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2094       // we'll replace these with the ones immediately after those which were
2095       // really allocated. In the prologue copies will be inserted from the
2096       // argument to these reserved registers.
2097 
2098       // Without HSA, relocations are used for the scratch pointer and the
2099       // buffer resource setup is always inserted in the prologue. Scratch wave
2100       // offset is still in an input SGPR.
2101       Info.setScratchRSrcReg(ReservedBufferReg);
2102     }
2103   }
2104 
2105   MachineRegisterInfo &MRI = MF.getRegInfo();
2106 
2107   // For entry functions we have to set up the stack pointer if we use it,
2108   // whereas non-entry functions get this "for free". This means there is no
2109   // intrinsic advantage to using S32 over S34 in cases where we do not have
2110   // calls but do need a frame pointer (i.e. if we are requested to have one
2111   // because frame pointer elimination is disabled). To keep things simple we
2112   // only ever use S32 as the call ABI stack pointer, and so using it does not
2113   // imply we need a separate frame pointer.
2114   //
2115   // Try to use s32 as the SP, but move it if it would interfere with input
2116   // arguments. This won't work with calls though.
2117   //
2118   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2119   // registers.
2120   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2121     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2122   } else {
2123     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2124 
2125     if (MFI.hasCalls())
2126       report_fatal_error("call in graphics shader with too many input SGPRs");
2127 
2128     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2129       if (!MRI.isLiveIn(Reg)) {
2130         Info.setStackPtrOffsetReg(Reg);
2131         break;
2132       }
2133     }
2134 
2135     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2136       report_fatal_error("failed to find register for SP");
2137   }
2138 
2139   // hasFP should be accurate for entry functions even before the frame is
2140   // finalized, because it does not rely on the known stack size, only
2141   // properties like whether variable sized objects are present.
2142   if (ST.getFrameLowering()->hasFP(MF)) {
2143     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2144   }
2145 }
2146 
2147 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2148   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2149   return !Info->isEntryFunction();
2150 }
2151 
2152 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2153 
2154 }
2155 
2156 void SITargetLowering::insertCopiesSplitCSR(
2157   MachineBasicBlock *Entry,
2158   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2159   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2160 
2161   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2162   if (!IStart)
2163     return;
2164 
2165   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2166   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2167   MachineBasicBlock::iterator MBBI = Entry->begin();
2168   for (const MCPhysReg *I = IStart; *I; ++I) {
2169     const TargetRegisterClass *RC = nullptr;
2170     if (AMDGPU::SReg_64RegClass.contains(*I))
2171       RC = &AMDGPU::SGPR_64RegClass;
2172     else if (AMDGPU::SReg_32RegClass.contains(*I))
2173       RC = &AMDGPU::SGPR_32RegClass;
2174     else
2175       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2176 
2177     Register NewVR = MRI->createVirtualRegister(RC);
2178     // Create copy from CSR to a virtual register.
2179     Entry->addLiveIn(*I);
2180     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2181       .addReg(*I);
2182 
2183     // Insert the copy-back instructions right before the terminator.
2184     for (auto *Exit : Exits)
2185       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2186               TII->get(TargetOpcode::COPY), *I)
2187         .addReg(NewVR);
2188   }
2189 }
2190 
2191 SDValue SITargetLowering::LowerFormalArguments(
2192     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2193     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2194     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2195   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2196 
2197   MachineFunction &MF = DAG.getMachineFunction();
2198   const Function &Fn = MF.getFunction();
2199   FunctionType *FType = MF.getFunction().getFunctionType();
2200   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2201 
2202   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2203     DiagnosticInfoUnsupported NoGraphicsHSA(
2204         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2205     DAG.getContext()->diagnose(NoGraphicsHSA);
2206     return DAG.getEntryNode();
2207   }
2208 
2209   SmallVector<ISD::InputArg, 16> Splits;
2210   SmallVector<CCValAssign, 16> ArgLocs;
2211   BitVector Skipped(Ins.size());
2212   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2213                  *DAG.getContext());
2214 
2215   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2216   bool IsKernel = AMDGPU::isKernel(CallConv);
2217   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2218 
2219   if (IsGraphics) {
2220     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2221            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2222            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2223            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2224            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2225            !Info->hasWorkItemIDZ());
2226   }
2227 
2228   if (CallConv == CallingConv::AMDGPU_PS) {
2229     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2230 
2231     // At least one interpolation mode must be enabled or else the GPU will
2232     // hang.
2233     //
2234     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2235     // set PSInputAddr, the user wants to enable some bits after the compilation
2236     // based on run-time states. Since we can't know what the final PSInputEna
2237     // will look like, so we shouldn't do anything here and the user should take
2238     // responsibility for the correct programming.
2239     //
2240     // Otherwise, the following restrictions apply:
2241     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2242     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2243     //   enabled too.
2244     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2245         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2246       CCInfo.AllocateReg(AMDGPU::VGPR0);
2247       CCInfo.AllocateReg(AMDGPU::VGPR1);
2248       Info->markPSInputAllocated(0);
2249       Info->markPSInputEnabled(0);
2250     }
2251     if (Subtarget->isAmdPalOS()) {
2252       // For isAmdPalOS, the user does not enable some bits after compilation
2253       // based on run-time states; the register values being generated here are
2254       // the final ones set in hardware. Therefore we need to apply the
2255       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2256       // a bit is set in PSInputAddr but not PSInputEnable is where the
2257       // frontend set up an input arg for a particular interpolation mode, but
2258       // nothing uses that input arg. Really we should have an earlier pass
2259       // that removes such an arg.)
2260       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2261       if ((PsInputBits & 0x7F) == 0 ||
2262           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2263         Info->markPSInputEnabled(
2264             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2265     }
2266   } else if (IsKernel) {
2267     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2268   } else {
2269     Splits.append(Ins.begin(), Ins.end());
2270   }
2271 
2272   if (IsEntryFunc) {
2273     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2274     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2275   } else {
2276     // For the fixed ABI, pass workitem IDs in the last argument register.
2277     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2278       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2279   }
2280 
2281   if (IsKernel) {
2282     analyzeFormalArgumentsCompute(CCInfo, Ins);
2283   } else {
2284     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2285     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2286   }
2287 
2288   SmallVector<SDValue, 16> Chains;
2289 
2290   // FIXME: This is the minimum kernel argument alignment. We should improve
2291   // this to the maximum alignment of the arguments.
2292   //
2293   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2294   // kern arg offset.
2295   const Align KernelArgBaseAlign = Align(16);
2296 
2297   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2298     const ISD::InputArg &Arg = Ins[i];
2299     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2300       InVals.push_back(DAG.getUNDEF(Arg.VT));
2301       continue;
2302     }
2303 
2304     CCValAssign &VA = ArgLocs[ArgIdx++];
2305     MVT VT = VA.getLocVT();
2306 
2307     if (IsEntryFunc && VA.isMemLoc()) {
2308       VT = Ins[i].VT;
2309       EVT MemVT = VA.getLocVT();
2310 
2311       const uint64_t Offset = VA.getLocMemOffset();
2312       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2313 
2314       if (Arg.Flags.isByRef()) {
2315         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2316 
2317         const GCNTargetMachine &TM =
2318             static_cast<const GCNTargetMachine &>(getTargetMachine());
2319         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2320                                     Arg.Flags.getPointerAddrSpace())) {
2321           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2322                                      Arg.Flags.getPointerAddrSpace());
2323         }
2324 
2325         InVals.push_back(Ptr);
2326         continue;
2327       }
2328 
2329       SDValue Arg = lowerKernargMemParameter(
2330         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2331       Chains.push_back(Arg.getValue(1));
2332 
2333       auto *ParamTy =
2334         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2335       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2336           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2337                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2338         // On SI local pointers are just offsets into LDS, so they are always
2339         // less than 16-bits.  On CI and newer they could potentially be
2340         // real pointers, so we can't guarantee their size.
2341         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2342                           DAG.getValueType(MVT::i16));
2343       }
2344 
2345       InVals.push_back(Arg);
2346       continue;
2347     } else if (!IsEntryFunc && VA.isMemLoc()) {
2348       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2349       InVals.push_back(Val);
2350       if (!Arg.Flags.isByVal())
2351         Chains.push_back(Val.getValue(1));
2352       continue;
2353     }
2354 
2355     assert(VA.isRegLoc() && "Parameter must be in a register!");
2356 
2357     Register Reg = VA.getLocReg();
2358     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2359     EVT ValVT = VA.getValVT();
2360 
2361     Reg = MF.addLiveIn(Reg, RC);
2362     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2363 
2364     if (Arg.Flags.isSRet()) {
2365       // The return object should be reasonably addressable.
2366 
2367       // FIXME: This helps when the return is a real sret. If it is a
2368       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2369       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2370       unsigned NumBits
2371         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2372       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2373         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2374     }
2375 
2376     // If this is an 8 or 16-bit value, it is really passed promoted
2377     // to 32 bits. Insert an assert[sz]ext to capture this, then
2378     // truncate to the right size.
2379     switch (VA.getLocInfo()) {
2380     case CCValAssign::Full:
2381       break;
2382     case CCValAssign::BCvt:
2383       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2384       break;
2385     case CCValAssign::SExt:
2386       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2387                         DAG.getValueType(ValVT));
2388       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2389       break;
2390     case CCValAssign::ZExt:
2391       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2392                         DAG.getValueType(ValVT));
2393       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2394       break;
2395     case CCValAssign::AExt:
2396       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2397       break;
2398     default:
2399       llvm_unreachable("Unknown loc info!");
2400     }
2401 
2402     InVals.push_back(Val);
2403   }
2404 
2405   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2406     // Special inputs come after user arguments.
2407     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2408   }
2409 
2410   // Start adding system SGPRs.
2411   if (IsEntryFunc) {
2412     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2413   } else {
2414     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2415     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2416   }
2417 
2418   auto &ArgUsageInfo =
2419     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2420   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2421 
2422   unsigned StackArgSize = CCInfo.getNextStackOffset();
2423   Info->setBytesInStackArgArea(StackArgSize);
2424 
2425   return Chains.empty() ? Chain :
2426     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2427 }
2428 
2429 // TODO: If return values can't fit in registers, we should return as many as
2430 // possible in registers before passing on stack.
2431 bool SITargetLowering::CanLowerReturn(
2432   CallingConv::ID CallConv,
2433   MachineFunction &MF, bool IsVarArg,
2434   const SmallVectorImpl<ISD::OutputArg> &Outs,
2435   LLVMContext &Context) const {
2436   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2437   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2438   // for shaders. Vector types should be explicitly handled by CC.
2439   if (AMDGPU::isEntryFunctionCC(CallConv))
2440     return true;
2441 
2442   SmallVector<CCValAssign, 16> RVLocs;
2443   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2444   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2445 }
2446 
2447 SDValue
2448 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2449                               bool isVarArg,
2450                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2451                               const SmallVectorImpl<SDValue> &OutVals,
2452                               const SDLoc &DL, SelectionDAG &DAG) const {
2453   MachineFunction &MF = DAG.getMachineFunction();
2454   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2455 
2456   if (AMDGPU::isKernel(CallConv)) {
2457     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2458                                              OutVals, DL, DAG);
2459   }
2460 
2461   bool IsShader = AMDGPU::isShader(CallConv);
2462 
2463   Info->setIfReturnsVoid(Outs.empty());
2464   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2465 
2466   // CCValAssign - represent the assignment of the return value to a location.
2467   SmallVector<CCValAssign, 48> RVLocs;
2468   SmallVector<ISD::OutputArg, 48> Splits;
2469 
2470   // CCState - Info about the registers and stack slots.
2471   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2472                  *DAG.getContext());
2473 
2474   // Analyze outgoing return values.
2475   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2476 
2477   SDValue Flag;
2478   SmallVector<SDValue, 48> RetOps;
2479   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2480 
2481   // Add return address for callable functions.
2482   if (!Info->isEntryFunction()) {
2483     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2484     SDValue ReturnAddrReg = CreateLiveInRegister(
2485       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2486 
2487     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2488         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2489         MVT::i64);
2490     Chain =
2491         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2492     Flag = Chain.getValue(1);
2493     RetOps.push_back(ReturnAddrVirtualReg);
2494   }
2495 
2496   // Copy the result values into the output registers.
2497   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2498        ++I, ++RealRVLocIdx) {
2499     CCValAssign &VA = RVLocs[I];
2500     assert(VA.isRegLoc() && "Can only return in registers!");
2501     // TODO: Partially return in registers if return values don't fit.
2502     SDValue Arg = OutVals[RealRVLocIdx];
2503 
2504     // Copied from other backends.
2505     switch (VA.getLocInfo()) {
2506     case CCValAssign::Full:
2507       break;
2508     case CCValAssign::BCvt:
2509       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2510       break;
2511     case CCValAssign::SExt:
2512       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2513       break;
2514     case CCValAssign::ZExt:
2515       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2516       break;
2517     case CCValAssign::AExt:
2518       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2519       break;
2520     default:
2521       llvm_unreachable("Unknown loc info!");
2522     }
2523 
2524     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2525     Flag = Chain.getValue(1);
2526     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2527   }
2528 
2529   // FIXME: Does sret work properly?
2530   if (!Info->isEntryFunction()) {
2531     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2532     const MCPhysReg *I =
2533       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2534     if (I) {
2535       for (; *I; ++I) {
2536         if (AMDGPU::SReg_64RegClass.contains(*I))
2537           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2538         else if (AMDGPU::SReg_32RegClass.contains(*I))
2539           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2540         else
2541           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2542       }
2543     }
2544   }
2545 
2546   // Update chain and glue.
2547   RetOps[0] = Chain;
2548   if (Flag.getNode())
2549     RetOps.push_back(Flag);
2550 
2551   unsigned Opc = AMDGPUISD::ENDPGM;
2552   if (!IsWaveEnd)
2553     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2554   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2555 }
2556 
2557 SDValue SITargetLowering::LowerCallResult(
2558     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2559     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2560     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2561     SDValue ThisVal) const {
2562   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2563 
2564   // Assign locations to each value returned by this call.
2565   SmallVector<CCValAssign, 16> RVLocs;
2566   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2567                  *DAG.getContext());
2568   CCInfo.AnalyzeCallResult(Ins, RetCC);
2569 
2570   // Copy all of the result registers out of their specified physreg.
2571   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2572     CCValAssign VA = RVLocs[i];
2573     SDValue Val;
2574 
2575     if (VA.isRegLoc()) {
2576       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2577       Chain = Val.getValue(1);
2578       InFlag = Val.getValue(2);
2579     } else if (VA.isMemLoc()) {
2580       report_fatal_error("TODO: return values in memory");
2581     } else
2582       llvm_unreachable("unknown argument location type");
2583 
2584     switch (VA.getLocInfo()) {
2585     case CCValAssign::Full:
2586       break;
2587     case CCValAssign::BCvt:
2588       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2589       break;
2590     case CCValAssign::ZExt:
2591       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2592                         DAG.getValueType(VA.getValVT()));
2593       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2594       break;
2595     case CCValAssign::SExt:
2596       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2597                         DAG.getValueType(VA.getValVT()));
2598       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2599       break;
2600     case CCValAssign::AExt:
2601       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2602       break;
2603     default:
2604       llvm_unreachable("Unknown loc info!");
2605     }
2606 
2607     InVals.push_back(Val);
2608   }
2609 
2610   return Chain;
2611 }
2612 
2613 // Add code to pass special inputs required depending on used features separate
2614 // from the explicit user arguments present in the IR.
2615 void SITargetLowering::passSpecialInputs(
2616     CallLoweringInfo &CLI,
2617     CCState &CCInfo,
2618     const SIMachineFunctionInfo &Info,
2619     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2620     SmallVectorImpl<SDValue> &MemOpChains,
2621     SDValue Chain) const {
2622   // If we don't have a call site, this was a call inserted by
2623   // legalization. These can never use special inputs.
2624   if (!CLI.CB)
2625     return;
2626 
2627   SelectionDAG &DAG = CLI.DAG;
2628   const SDLoc &DL = CLI.DL;
2629 
2630   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2631   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2632 
2633   const AMDGPUFunctionArgInfo *CalleeArgInfo
2634     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2635   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2636     auto &ArgUsageInfo =
2637       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2638     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2639   }
2640 
2641   // TODO: Unify with private memory register handling. This is complicated by
2642   // the fact that at least in kernels, the input argument is not necessarily
2643   // in the same location as the input.
2644   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2645     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2646     AMDGPUFunctionArgInfo::QUEUE_PTR,
2647     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2648     AMDGPUFunctionArgInfo::DISPATCH_ID,
2649     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2650     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2651     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2652   };
2653 
2654   for (auto InputID : InputRegs) {
2655     const ArgDescriptor *OutgoingArg;
2656     const TargetRegisterClass *ArgRC;
2657     LLT ArgTy;
2658 
2659     std::tie(OutgoingArg, ArgRC, ArgTy) =
2660         CalleeArgInfo->getPreloadedValue(InputID);
2661     if (!OutgoingArg)
2662       continue;
2663 
2664     const ArgDescriptor *IncomingArg;
2665     const TargetRegisterClass *IncomingArgRC;
2666     LLT Ty;
2667     std::tie(IncomingArg, IncomingArgRC, Ty) =
2668         CallerArgInfo.getPreloadedValue(InputID);
2669     assert(IncomingArgRC == ArgRC);
2670 
2671     // All special arguments are ints for now.
2672     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2673     SDValue InputReg;
2674 
2675     if (IncomingArg) {
2676       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2677     } else {
2678       // The implicit arg ptr is special because it doesn't have a corresponding
2679       // input for kernels, and is computed from the kernarg segment pointer.
2680       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2681       InputReg = getImplicitArgPtr(DAG, DL);
2682     }
2683 
2684     if (OutgoingArg->isRegister()) {
2685       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2686       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2687         report_fatal_error("failed to allocate implicit input argument");
2688     } else {
2689       unsigned SpecialArgOffset =
2690           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2691       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2692                                               SpecialArgOffset);
2693       MemOpChains.push_back(ArgStore);
2694     }
2695   }
2696 
2697   // Pack workitem IDs into a single register or pass it as is if already
2698   // packed.
2699   const ArgDescriptor *OutgoingArg;
2700   const TargetRegisterClass *ArgRC;
2701   LLT Ty;
2702 
2703   std::tie(OutgoingArg, ArgRC, Ty) =
2704       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2705   if (!OutgoingArg)
2706     std::tie(OutgoingArg, ArgRC, Ty) =
2707         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2708   if (!OutgoingArg)
2709     std::tie(OutgoingArg, ArgRC, Ty) =
2710         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2711   if (!OutgoingArg)
2712     return;
2713 
2714   const ArgDescriptor *IncomingArgX = std::get<0>(
2715       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2716   const ArgDescriptor *IncomingArgY = std::get<0>(
2717       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2718   const ArgDescriptor *IncomingArgZ = std::get<0>(
2719       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2720 
2721   SDValue InputReg;
2722   SDLoc SL;
2723 
2724   // If incoming ids are not packed we need to pack them.
2725   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2726     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2727 
2728   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2729     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2730     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2731                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2732     InputReg = InputReg.getNode() ?
2733                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2734   }
2735 
2736   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2737     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2738     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2739                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2740     InputReg = InputReg.getNode() ?
2741                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2742   }
2743 
2744   if (!InputReg.getNode()) {
2745     // Workitem ids are already packed, any of present incoming arguments
2746     // will carry all required fields.
2747     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2748       IncomingArgX ? *IncomingArgX :
2749       IncomingArgY ? *IncomingArgY :
2750                      *IncomingArgZ, ~0u);
2751     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2752   }
2753 
2754   if (OutgoingArg->isRegister()) {
2755     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2756     CCInfo.AllocateReg(OutgoingArg->getRegister());
2757   } else {
2758     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2759     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2760                                             SpecialArgOffset);
2761     MemOpChains.push_back(ArgStore);
2762   }
2763 }
2764 
2765 static bool canGuaranteeTCO(CallingConv::ID CC) {
2766   return CC == CallingConv::Fast;
2767 }
2768 
2769 /// Return true if we might ever do TCO for calls with this calling convention.
2770 static bool mayTailCallThisCC(CallingConv::ID CC) {
2771   switch (CC) {
2772   case CallingConv::C:
2773     return true;
2774   default:
2775     return canGuaranteeTCO(CC);
2776   }
2777 }
2778 
2779 bool SITargetLowering::isEligibleForTailCallOptimization(
2780     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2781     const SmallVectorImpl<ISD::OutputArg> &Outs,
2782     const SmallVectorImpl<SDValue> &OutVals,
2783     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2784   if (!mayTailCallThisCC(CalleeCC))
2785     return false;
2786 
2787   MachineFunction &MF = DAG.getMachineFunction();
2788   const Function &CallerF = MF.getFunction();
2789   CallingConv::ID CallerCC = CallerF.getCallingConv();
2790   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2791   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2792 
2793   // Kernels aren't callable, and don't have a live in return address so it
2794   // doesn't make sense to do a tail call with entry functions.
2795   if (!CallerPreserved)
2796     return false;
2797 
2798   bool CCMatch = CallerCC == CalleeCC;
2799 
2800   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2801     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2802       return true;
2803     return false;
2804   }
2805 
2806   // TODO: Can we handle var args?
2807   if (IsVarArg)
2808     return false;
2809 
2810   for (const Argument &Arg : CallerF.args()) {
2811     if (Arg.hasByValAttr())
2812       return false;
2813   }
2814 
2815   LLVMContext &Ctx = *DAG.getContext();
2816 
2817   // Check that the call results are passed in the same way.
2818   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2819                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2820                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2821     return false;
2822 
2823   // The callee has to preserve all registers the caller needs to preserve.
2824   if (!CCMatch) {
2825     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2826     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2827       return false;
2828   }
2829 
2830   // Nothing more to check if the callee is taking no arguments.
2831   if (Outs.empty())
2832     return true;
2833 
2834   SmallVector<CCValAssign, 16> ArgLocs;
2835   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2836 
2837   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2838 
2839   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2840   // If the stack arguments for this call do not fit into our own save area then
2841   // the call cannot be made tail.
2842   // TODO: Is this really necessary?
2843   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2844     return false;
2845 
2846   const MachineRegisterInfo &MRI = MF.getRegInfo();
2847   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2848 }
2849 
2850 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2851   if (!CI->isTailCall())
2852     return false;
2853 
2854   const Function *ParentFn = CI->getParent()->getParent();
2855   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2856     return false;
2857   return true;
2858 }
2859 
2860 // The wave scratch offset register is used as the global base pointer.
2861 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2862                                     SmallVectorImpl<SDValue> &InVals) const {
2863   SelectionDAG &DAG = CLI.DAG;
2864   const SDLoc &DL = CLI.DL;
2865   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2866   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2867   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2868   SDValue Chain = CLI.Chain;
2869   SDValue Callee = CLI.Callee;
2870   bool &IsTailCall = CLI.IsTailCall;
2871   CallingConv::ID CallConv = CLI.CallConv;
2872   bool IsVarArg = CLI.IsVarArg;
2873   bool IsSibCall = false;
2874   bool IsThisReturn = false;
2875   MachineFunction &MF = DAG.getMachineFunction();
2876 
2877   if (Callee.isUndef() || isNullConstant(Callee)) {
2878     if (!CLI.IsTailCall) {
2879       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2880         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2881     }
2882 
2883     return Chain;
2884   }
2885 
2886   if (IsVarArg) {
2887     return lowerUnhandledCall(CLI, InVals,
2888                               "unsupported call to variadic function ");
2889   }
2890 
2891   if (!CLI.CB)
2892     report_fatal_error("unsupported libcall legalization");
2893 
2894   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2895       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2896     return lowerUnhandledCall(CLI, InVals,
2897                               "unsupported indirect call to function ");
2898   }
2899 
2900   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2901     return lowerUnhandledCall(CLI, InVals,
2902                               "unsupported required tail call to function ");
2903   }
2904 
2905   if (AMDGPU::isShader(CallConv)) {
2906     // Note the issue is with the CC of the called function, not of the call
2907     // itself.
2908     return lowerUnhandledCall(CLI, InVals,
2909                               "unsupported call to a shader function ");
2910   }
2911 
2912   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2913       CallConv != CallingConv::AMDGPU_Gfx) {
2914     // Only allow calls with specific calling conventions.
2915     return lowerUnhandledCall(CLI, InVals,
2916                               "unsupported calling convention for call from "
2917                               "graphics shader of function ");
2918   }
2919 
2920   if (IsTailCall) {
2921     IsTailCall = isEligibleForTailCallOptimization(
2922       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2923     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2924       report_fatal_error("failed to perform tail call elimination on a call "
2925                          "site marked musttail");
2926     }
2927 
2928     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2929 
2930     // A sibling call is one where we're under the usual C ABI and not planning
2931     // to change that but can still do a tail call:
2932     if (!TailCallOpt && IsTailCall)
2933       IsSibCall = true;
2934 
2935     if (IsTailCall)
2936       ++NumTailCalls;
2937   }
2938 
2939   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2940   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2941   SmallVector<SDValue, 8> MemOpChains;
2942 
2943   // Analyze operands of the call, assigning locations to each operand.
2944   SmallVector<CCValAssign, 16> ArgLocs;
2945   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2946   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2947 
2948   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
2949       CallConv != CallingConv::AMDGPU_Gfx) {
2950     // With a fixed ABI, allocate fixed registers before user arguments.
2951     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2952   }
2953 
2954   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2955 
2956   // Get a count of how many bytes are to be pushed on the stack.
2957   unsigned NumBytes = CCInfo.getNextStackOffset();
2958 
2959   if (IsSibCall) {
2960     // Since we're not changing the ABI to make this a tail call, the memory
2961     // operands are already available in the caller's incoming argument space.
2962     NumBytes = 0;
2963   }
2964 
2965   // FPDiff is the byte offset of the call's argument area from the callee's.
2966   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2967   // by this amount for a tail call. In a sibling call it must be 0 because the
2968   // caller will deallocate the entire stack and the callee still expects its
2969   // arguments to begin at SP+0. Completely unused for non-tail calls.
2970   int32_t FPDiff = 0;
2971   MachineFrameInfo &MFI = MF.getFrameInfo();
2972 
2973   // Adjust the stack pointer for the new arguments...
2974   // These operations are automatically eliminated by the prolog/epilog pass
2975   if (!IsSibCall) {
2976     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2977 
2978     if (!Subtarget->enableFlatScratch()) {
2979       SmallVector<SDValue, 4> CopyFromChains;
2980 
2981       // In the HSA case, this should be an identity copy.
2982       SDValue ScratchRSrcReg
2983         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2984       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2985       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2986       Chain = DAG.getTokenFactor(DL, CopyFromChains);
2987     }
2988   }
2989 
2990   MVT PtrVT = MVT::i32;
2991 
2992   // Walk the register/memloc assignments, inserting copies/loads.
2993   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994     CCValAssign &VA = ArgLocs[i];
2995     SDValue Arg = OutVals[i];
2996 
2997     // Promote the value if needed.
2998     switch (VA.getLocInfo()) {
2999     case CCValAssign::Full:
3000       break;
3001     case CCValAssign::BCvt:
3002       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3003       break;
3004     case CCValAssign::ZExt:
3005       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3006       break;
3007     case CCValAssign::SExt:
3008       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3009       break;
3010     case CCValAssign::AExt:
3011       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3012       break;
3013     case CCValAssign::FPExt:
3014       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3015       break;
3016     default:
3017       llvm_unreachable("Unknown loc info!");
3018     }
3019 
3020     if (VA.isRegLoc()) {
3021       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3022     } else {
3023       assert(VA.isMemLoc());
3024 
3025       SDValue DstAddr;
3026       MachinePointerInfo DstInfo;
3027 
3028       unsigned LocMemOffset = VA.getLocMemOffset();
3029       int32_t Offset = LocMemOffset;
3030 
3031       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3032       MaybeAlign Alignment;
3033 
3034       if (IsTailCall) {
3035         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3036         unsigned OpSize = Flags.isByVal() ?
3037           Flags.getByValSize() : VA.getValVT().getStoreSize();
3038 
3039         // FIXME: We can have better than the minimum byval required alignment.
3040         Alignment =
3041             Flags.isByVal()
3042                 ? Flags.getNonZeroByValAlign()
3043                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3044 
3045         Offset = Offset + FPDiff;
3046         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3047 
3048         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3049         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3050 
3051         // Make sure any stack arguments overlapping with where we're storing
3052         // are loaded before this eventual operation. Otherwise they'll be
3053         // clobbered.
3054 
3055         // FIXME: Why is this really necessary? This seems to just result in a
3056         // lot of code to copy the stack and write them back to the same
3057         // locations, which are supposed to be immutable?
3058         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3059       } else {
3060         DstAddr = PtrOff;
3061         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3062         Alignment =
3063             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3064       }
3065 
3066       if (Outs[i].Flags.isByVal()) {
3067         SDValue SizeNode =
3068             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3069         SDValue Cpy =
3070             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3071                           Outs[i].Flags.getNonZeroByValAlign(),
3072                           /*isVol = */ false, /*AlwaysInline = */ true,
3073                           /*isTailCall = */ false, DstInfo,
3074                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3075 
3076         MemOpChains.push_back(Cpy);
3077       } else {
3078         SDValue Store =
3079             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3080         MemOpChains.push_back(Store);
3081       }
3082     }
3083   }
3084 
3085   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3086       CallConv != CallingConv::AMDGPU_Gfx) {
3087     // Copy special input registers after user input arguments.
3088     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3089   }
3090 
3091   if (!MemOpChains.empty())
3092     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3093 
3094   // Build a sequence of copy-to-reg nodes chained together with token chain
3095   // and flag operands which copy the outgoing args into the appropriate regs.
3096   SDValue InFlag;
3097   for (auto &RegToPass : RegsToPass) {
3098     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3099                              RegToPass.second, InFlag);
3100     InFlag = Chain.getValue(1);
3101   }
3102 
3103 
3104   SDValue PhysReturnAddrReg;
3105   if (IsTailCall) {
3106     // Since the return is being combined with the call, we need to pass on the
3107     // return address.
3108 
3109     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3110     SDValue ReturnAddrReg = CreateLiveInRegister(
3111       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3112 
3113     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3114                                         MVT::i64);
3115     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3116     InFlag = Chain.getValue(1);
3117   }
3118 
3119   // We don't usually want to end the call-sequence here because we would tidy
3120   // the frame up *after* the call, however in the ABI-changing tail-call case
3121   // we've carefully laid out the parameters so that when sp is reset they'll be
3122   // in the correct location.
3123   if (IsTailCall && !IsSibCall) {
3124     Chain = DAG.getCALLSEQ_END(Chain,
3125                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3126                                DAG.getTargetConstant(0, DL, MVT::i32),
3127                                InFlag, DL);
3128     InFlag = Chain.getValue(1);
3129   }
3130 
3131   std::vector<SDValue> Ops;
3132   Ops.push_back(Chain);
3133   Ops.push_back(Callee);
3134   // Add a redundant copy of the callee global which will not be legalized, as
3135   // we need direct access to the callee later.
3136   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3137     const GlobalValue *GV = GSD->getGlobal();
3138     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3139   } else {
3140     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3141   }
3142 
3143   if (IsTailCall) {
3144     // Each tail call may have to adjust the stack by a different amount, so
3145     // this information must travel along with the operation for eventual
3146     // consumption by emitEpilogue.
3147     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3148 
3149     Ops.push_back(PhysReturnAddrReg);
3150   }
3151 
3152   // Add argument registers to the end of the list so that they are known live
3153   // into the call.
3154   for (auto &RegToPass : RegsToPass) {
3155     Ops.push_back(DAG.getRegister(RegToPass.first,
3156                                   RegToPass.second.getValueType()));
3157   }
3158 
3159   // Add a register mask operand representing the call-preserved registers.
3160 
3161   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3162   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3163   assert(Mask && "Missing call preserved mask for calling convention");
3164   Ops.push_back(DAG.getRegisterMask(Mask));
3165 
3166   if (InFlag.getNode())
3167     Ops.push_back(InFlag);
3168 
3169   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3170 
3171   // If we're doing a tall call, use a TC_RETURN here rather than an
3172   // actual call instruction.
3173   if (IsTailCall) {
3174     MFI.setHasTailCall();
3175     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3176   }
3177 
3178   // Returns a chain and a flag for retval copy to use.
3179   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3180   Chain = Call.getValue(0);
3181   InFlag = Call.getValue(1);
3182 
3183   uint64_t CalleePopBytes = NumBytes;
3184   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3185                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3186                              InFlag, DL);
3187   if (!Ins.empty())
3188     InFlag = Chain.getValue(1);
3189 
3190   // Handle result values, copying them out of physregs into vregs that we
3191   // return.
3192   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3193                          InVals, IsThisReturn,
3194                          IsThisReturn ? OutVals[0] : SDValue());
3195 }
3196 
3197 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3198 // except for applying the wave size scale to the increment amount.
3199 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3200     SDValue Op, SelectionDAG &DAG) const {
3201   const MachineFunction &MF = DAG.getMachineFunction();
3202   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3203 
3204   SDLoc dl(Op);
3205   EVT VT = Op.getValueType();
3206   SDValue Tmp1 = Op;
3207   SDValue Tmp2 = Op.getValue(1);
3208   SDValue Tmp3 = Op.getOperand(2);
3209   SDValue Chain = Tmp1.getOperand(0);
3210 
3211   Register SPReg = Info->getStackPtrOffsetReg();
3212 
3213   // Chain the dynamic stack allocation so that it doesn't modify the stack
3214   // pointer when other instructions are using the stack.
3215   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3216 
3217   SDValue Size  = Tmp2.getOperand(1);
3218   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3219   Chain = SP.getValue(1);
3220   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3221   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3222   const TargetFrameLowering *TFL = ST.getFrameLowering();
3223   unsigned Opc =
3224     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3225     ISD::ADD : ISD::SUB;
3226 
3227   SDValue ScaledSize = DAG.getNode(
3228       ISD::SHL, dl, VT, Size,
3229       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3230 
3231   Align StackAlign = TFL->getStackAlign();
3232   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3233   if (Alignment && *Alignment > StackAlign) {
3234     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3235                        DAG.getConstant(-(uint64_t)Alignment->value()
3236                                            << ST.getWavefrontSizeLog2(),
3237                                        dl, VT));
3238   }
3239 
3240   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3241   Tmp2 = DAG.getCALLSEQ_END(
3242       Chain, DAG.getIntPtrConstant(0, dl, true),
3243       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3244 
3245   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3246 }
3247 
3248 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3249                                                   SelectionDAG &DAG) const {
3250   // We only handle constant sizes here to allow non-entry block, static sized
3251   // allocas. A truly dynamic value is more difficult to support because we
3252   // don't know if the size value is uniform or not. If the size isn't uniform,
3253   // we would need to do a wave reduction to get the maximum size to know how
3254   // much to increment the uniform stack pointer.
3255   SDValue Size = Op.getOperand(1);
3256   if (isa<ConstantSDNode>(Size))
3257       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3258 
3259   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3260 }
3261 
3262 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3263                                              const MachineFunction &MF) const {
3264   Register Reg = StringSwitch<Register>(RegName)
3265     .Case("m0", AMDGPU::M0)
3266     .Case("exec", AMDGPU::EXEC)
3267     .Case("exec_lo", AMDGPU::EXEC_LO)
3268     .Case("exec_hi", AMDGPU::EXEC_HI)
3269     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3270     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3271     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3272     .Default(Register());
3273 
3274   if (Reg == AMDGPU::NoRegister) {
3275     report_fatal_error(Twine("invalid register name \""
3276                              + StringRef(RegName)  + "\"."));
3277 
3278   }
3279 
3280   if (!Subtarget->hasFlatScrRegister() &&
3281        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3282     report_fatal_error(Twine("invalid register \""
3283                              + StringRef(RegName)  + "\" for subtarget."));
3284   }
3285 
3286   switch (Reg) {
3287   case AMDGPU::M0:
3288   case AMDGPU::EXEC_LO:
3289   case AMDGPU::EXEC_HI:
3290   case AMDGPU::FLAT_SCR_LO:
3291   case AMDGPU::FLAT_SCR_HI:
3292     if (VT.getSizeInBits() == 32)
3293       return Reg;
3294     break;
3295   case AMDGPU::EXEC:
3296   case AMDGPU::FLAT_SCR:
3297     if (VT.getSizeInBits() == 64)
3298       return Reg;
3299     break;
3300   default:
3301     llvm_unreachable("missing register type checking");
3302   }
3303 
3304   report_fatal_error(Twine("invalid type for register \""
3305                            + StringRef(RegName) + "\"."));
3306 }
3307 
3308 // If kill is not the last instruction, split the block so kill is always a
3309 // proper terminator.
3310 MachineBasicBlock *
3311 SITargetLowering::splitKillBlock(MachineInstr &MI,
3312                                  MachineBasicBlock *BB) const {
3313   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3314   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3315   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3316   return SplitBB;
3317 }
3318 
3319 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3320 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3321 // be the first instruction in the remainder block.
3322 //
3323 /// \returns { LoopBody, Remainder }
3324 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3325 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3326   MachineFunction *MF = MBB.getParent();
3327   MachineBasicBlock::iterator I(&MI);
3328 
3329   // To insert the loop we need to split the block. Move everything after this
3330   // point to a new block, and insert a new empty block between the two.
3331   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3332   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3333   MachineFunction::iterator MBBI(MBB);
3334   ++MBBI;
3335 
3336   MF->insert(MBBI, LoopBB);
3337   MF->insert(MBBI, RemainderBB);
3338 
3339   LoopBB->addSuccessor(LoopBB);
3340   LoopBB->addSuccessor(RemainderBB);
3341 
3342   // Move the rest of the block into a new block.
3343   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3344 
3345   if (InstInLoop) {
3346     auto Next = std::next(I);
3347 
3348     // Move instruction to loop body.
3349     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3350 
3351     // Move the rest of the block.
3352     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3353   } else {
3354     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3355   }
3356 
3357   MBB.addSuccessor(LoopBB);
3358 
3359   return std::make_pair(LoopBB, RemainderBB);
3360 }
3361 
3362 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3363 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3364   MachineBasicBlock *MBB = MI.getParent();
3365   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3366   auto I = MI.getIterator();
3367   auto E = std::next(I);
3368 
3369   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3370     .addImm(0);
3371 
3372   MIBundleBuilder Bundler(*MBB, I, E);
3373   finalizeBundle(*MBB, Bundler.begin());
3374 }
3375 
3376 MachineBasicBlock *
3377 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3378                                          MachineBasicBlock *BB) const {
3379   const DebugLoc &DL = MI.getDebugLoc();
3380 
3381   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3382 
3383   MachineBasicBlock *LoopBB;
3384   MachineBasicBlock *RemainderBB;
3385   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3386 
3387   // Apparently kill flags are only valid if the def is in the same block?
3388   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3389     Src->setIsKill(false);
3390 
3391   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3392 
3393   MachineBasicBlock::iterator I = LoopBB->end();
3394 
3395   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3396     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3397 
3398   // Clear TRAP_STS.MEM_VIOL
3399   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3400     .addImm(0)
3401     .addImm(EncodedReg);
3402 
3403   bundleInstWithWaitcnt(MI);
3404 
3405   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3406 
3407   // Load and check TRAP_STS.MEM_VIOL
3408   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3409     .addImm(EncodedReg);
3410 
3411   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3412   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3413     .addReg(Reg, RegState::Kill)
3414     .addImm(0);
3415   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3416     .addMBB(LoopBB);
3417 
3418   return RemainderBB;
3419 }
3420 
3421 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3422 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3423 // will only do one iteration. In the worst case, this will loop 64 times.
3424 //
3425 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3426 static MachineBasicBlock::iterator
3427 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3428                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3429                        const DebugLoc &DL, const MachineOperand &Idx,
3430                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3431                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3432                        Register &SGPRIdxReg) {
3433 
3434   MachineFunction *MF = OrigBB.getParent();
3435   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3436   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3437   MachineBasicBlock::iterator I = LoopBB.begin();
3438 
3439   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3440   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3441   Register NewExec = MRI.createVirtualRegister(BoolRC);
3442   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3443   Register CondReg = MRI.createVirtualRegister(BoolRC);
3444 
3445   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3446     .addReg(InitReg)
3447     .addMBB(&OrigBB)
3448     .addReg(ResultReg)
3449     .addMBB(&LoopBB);
3450 
3451   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3452     .addReg(InitSaveExecReg)
3453     .addMBB(&OrigBB)
3454     .addReg(NewExec)
3455     .addMBB(&LoopBB);
3456 
3457   // Read the next variant <- also loop target.
3458   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3459       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3460 
3461   // Compare the just read M0 value to all possible Idx values.
3462   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3463       .addReg(CurrentIdxReg)
3464       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3465 
3466   // Update EXEC, save the original EXEC value to VCC.
3467   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3468                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3469           NewExec)
3470     .addReg(CondReg, RegState::Kill);
3471 
3472   MRI.setSimpleHint(NewExec, CondReg);
3473 
3474   if (UseGPRIdxMode) {
3475     if (Offset == 0) {
3476       SGPRIdxReg = CurrentIdxReg;
3477     } else {
3478       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3479       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3480           .addReg(CurrentIdxReg, RegState::Kill)
3481           .addImm(Offset);
3482     }
3483   } else {
3484     // Move index from VCC into M0
3485     if (Offset == 0) {
3486       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3487         .addReg(CurrentIdxReg, RegState::Kill);
3488     } else {
3489       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3490         .addReg(CurrentIdxReg, RegState::Kill)
3491         .addImm(Offset);
3492     }
3493   }
3494 
3495   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3496   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3497   MachineInstr *InsertPt =
3498     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3499                                                   : AMDGPU::S_XOR_B64_term), Exec)
3500       .addReg(Exec)
3501       .addReg(NewExec);
3502 
3503   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3504   // s_cbranch_scc0?
3505 
3506   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3507   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3508     .addMBB(&LoopBB);
3509 
3510   return InsertPt->getIterator();
3511 }
3512 
3513 // This has slightly sub-optimal regalloc when the source vector is killed by
3514 // the read. The register allocator does not understand that the kill is
3515 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3516 // subregister from it, using 1 more VGPR than necessary. This was saved when
3517 // this was expanded after register allocation.
3518 static MachineBasicBlock::iterator
3519 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3520                unsigned InitResultReg, unsigned PhiReg, int Offset,
3521                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3522   MachineFunction *MF = MBB.getParent();
3523   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3524   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3525   MachineRegisterInfo &MRI = MF->getRegInfo();
3526   const DebugLoc &DL = MI.getDebugLoc();
3527   MachineBasicBlock::iterator I(&MI);
3528 
3529   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3530   Register DstReg = MI.getOperand(0).getReg();
3531   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3532   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3533   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3534   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3535 
3536   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3537 
3538   // Save the EXEC mask
3539   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3540     .addReg(Exec);
3541 
3542   MachineBasicBlock *LoopBB;
3543   MachineBasicBlock *RemainderBB;
3544   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3545 
3546   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3547 
3548   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3549                                       InitResultReg, DstReg, PhiReg, TmpExec,
3550                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3551 
3552   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3553   MachineFunction::iterator MBBI(LoopBB);
3554   ++MBBI;
3555   MF->insert(MBBI, LandingPad);
3556   LoopBB->removeSuccessor(RemainderBB);
3557   LandingPad->addSuccessor(RemainderBB);
3558   LoopBB->addSuccessor(LandingPad);
3559   MachineBasicBlock::iterator First = LandingPad->begin();
3560   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3561     .addReg(SaveExec);
3562 
3563   return InsPt;
3564 }
3565 
3566 // Returns subreg index, offset
3567 static std::pair<unsigned, int>
3568 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3569                             const TargetRegisterClass *SuperRC,
3570                             unsigned VecReg,
3571                             int Offset) {
3572   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3573 
3574   // Skip out of bounds offsets, or else we would end up using an undefined
3575   // register.
3576   if (Offset >= NumElts || Offset < 0)
3577     return std::make_pair(AMDGPU::sub0, Offset);
3578 
3579   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3580 }
3581 
3582 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3583                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3584                                  int Offset) {
3585   MachineBasicBlock *MBB = MI.getParent();
3586   const DebugLoc &DL = MI.getDebugLoc();
3587   MachineBasicBlock::iterator I(&MI);
3588 
3589   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3590 
3591   assert(Idx->getReg() != AMDGPU::NoRegister);
3592 
3593   if (Offset == 0) {
3594     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3595   } else {
3596     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3597         .add(*Idx)
3598         .addImm(Offset);
3599   }
3600 }
3601 
3602 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3603                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3604                                    int Offset) {
3605   MachineBasicBlock *MBB = MI.getParent();
3606   const DebugLoc &DL = MI.getDebugLoc();
3607   MachineBasicBlock::iterator I(&MI);
3608 
3609   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3610 
3611   if (Offset == 0)
3612     return Idx->getReg();
3613 
3614   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3615   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3616       .add(*Idx)
3617       .addImm(Offset);
3618   return Tmp;
3619 }
3620 
3621 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3622                                           MachineBasicBlock &MBB,
3623                                           const GCNSubtarget &ST) {
3624   const SIInstrInfo *TII = ST.getInstrInfo();
3625   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3626   MachineFunction *MF = MBB.getParent();
3627   MachineRegisterInfo &MRI = MF->getRegInfo();
3628 
3629   Register Dst = MI.getOperand(0).getReg();
3630   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3631   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3632   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3633 
3634   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3635   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3636 
3637   unsigned SubReg;
3638   std::tie(SubReg, Offset)
3639     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3640 
3641   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3642 
3643   // Check for a SGPR index.
3644   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3645     MachineBasicBlock::iterator I(&MI);
3646     const DebugLoc &DL = MI.getDebugLoc();
3647 
3648     if (UseGPRIdxMode) {
3649       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3650       // to avoid interfering with other uses, so probably requires a new
3651       // optimization pass.
3652       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3653 
3654       const MCInstrDesc &GPRIDXDesc =
3655           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3656       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3657           .addReg(SrcReg)
3658           .addReg(Idx)
3659           .addImm(SubReg);
3660     } else {
3661       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3662 
3663       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3664         .addReg(SrcReg, 0, SubReg)
3665         .addReg(SrcReg, RegState::Implicit);
3666     }
3667 
3668     MI.eraseFromParent();
3669 
3670     return &MBB;
3671   }
3672 
3673   // Control flow needs to be inserted if indexing with a VGPR.
3674   const DebugLoc &DL = MI.getDebugLoc();
3675   MachineBasicBlock::iterator I(&MI);
3676 
3677   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3678   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3679 
3680   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3681 
3682   Register SGPRIdxReg;
3683   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3684                               UseGPRIdxMode, SGPRIdxReg);
3685 
3686   MachineBasicBlock *LoopBB = InsPt->getParent();
3687 
3688   if (UseGPRIdxMode) {
3689     const MCInstrDesc &GPRIDXDesc =
3690         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3691 
3692     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3693         .addReg(SrcReg)
3694         .addReg(SGPRIdxReg)
3695         .addImm(SubReg);
3696   } else {
3697     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3698       .addReg(SrcReg, 0, SubReg)
3699       .addReg(SrcReg, RegState::Implicit);
3700   }
3701 
3702   MI.eraseFromParent();
3703 
3704   return LoopBB;
3705 }
3706 
3707 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3708                                           MachineBasicBlock &MBB,
3709                                           const GCNSubtarget &ST) {
3710   const SIInstrInfo *TII = ST.getInstrInfo();
3711   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3712   MachineFunction *MF = MBB.getParent();
3713   MachineRegisterInfo &MRI = MF->getRegInfo();
3714 
3715   Register Dst = MI.getOperand(0).getReg();
3716   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3717   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3718   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3719   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3720   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3721   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3722 
3723   // This can be an immediate, but will be folded later.
3724   assert(Val->getReg());
3725 
3726   unsigned SubReg;
3727   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3728                                                          SrcVec->getReg(),
3729                                                          Offset);
3730   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3731 
3732   if (Idx->getReg() == AMDGPU::NoRegister) {
3733     MachineBasicBlock::iterator I(&MI);
3734     const DebugLoc &DL = MI.getDebugLoc();
3735 
3736     assert(Offset == 0);
3737 
3738     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3739         .add(*SrcVec)
3740         .add(*Val)
3741         .addImm(SubReg);
3742 
3743     MI.eraseFromParent();
3744     return &MBB;
3745   }
3746 
3747   // Check for a SGPR index.
3748   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3749     MachineBasicBlock::iterator I(&MI);
3750     const DebugLoc &DL = MI.getDebugLoc();
3751 
3752     if (UseGPRIdxMode) {
3753       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3754 
3755       const MCInstrDesc &GPRIDXDesc =
3756           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3757       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3758           .addReg(SrcVec->getReg())
3759           .add(*Val)
3760           .addReg(Idx)
3761           .addImm(SubReg);
3762     } else {
3763       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3764 
3765       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3766           TRI.getRegSizeInBits(*VecRC), 32, false);
3767       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3768           .addReg(SrcVec->getReg())
3769           .add(*Val)
3770           .addImm(SubReg);
3771     }
3772     MI.eraseFromParent();
3773     return &MBB;
3774   }
3775 
3776   // Control flow needs to be inserted if indexing with a VGPR.
3777   if (Val->isReg())
3778     MRI.clearKillFlags(Val->getReg());
3779 
3780   const DebugLoc &DL = MI.getDebugLoc();
3781 
3782   Register PhiReg = MRI.createVirtualRegister(VecRC);
3783 
3784   Register SGPRIdxReg;
3785   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3786                               UseGPRIdxMode, SGPRIdxReg);
3787   MachineBasicBlock *LoopBB = InsPt->getParent();
3788 
3789   if (UseGPRIdxMode) {
3790     const MCInstrDesc &GPRIDXDesc =
3791         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3792 
3793     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3794         .addReg(PhiReg)
3795         .add(*Val)
3796         .addReg(SGPRIdxReg)
3797         .addImm(AMDGPU::sub0);
3798   } else {
3799     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3800         TRI.getRegSizeInBits(*VecRC), 32, false);
3801     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3802         .addReg(PhiReg)
3803         .add(*Val)
3804         .addImm(AMDGPU::sub0);
3805   }
3806 
3807   MI.eraseFromParent();
3808   return LoopBB;
3809 }
3810 
3811 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3812   MachineInstr &MI, MachineBasicBlock *BB) const {
3813 
3814   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3815   MachineFunction *MF = BB->getParent();
3816   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3817 
3818   switch (MI.getOpcode()) {
3819   case AMDGPU::S_UADDO_PSEUDO:
3820   case AMDGPU::S_USUBO_PSEUDO: {
3821     const DebugLoc &DL = MI.getDebugLoc();
3822     MachineOperand &Dest0 = MI.getOperand(0);
3823     MachineOperand &Dest1 = MI.getOperand(1);
3824     MachineOperand &Src0 = MI.getOperand(2);
3825     MachineOperand &Src1 = MI.getOperand(3);
3826 
3827     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3828                        ? AMDGPU::S_ADD_I32
3829                        : AMDGPU::S_SUB_I32;
3830     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3831 
3832     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3833         .addImm(1)
3834         .addImm(0);
3835 
3836     MI.eraseFromParent();
3837     return BB;
3838   }
3839   case AMDGPU::S_ADD_U64_PSEUDO:
3840   case AMDGPU::S_SUB_U64_PSEUDO: {
3841     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3842     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3843     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3844     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3845     const DebugLoc &DL = MI.getDebugLoc();
3846 
3847     MachineOperand &Dest = MI.getOperand(0);
3848     MachineOperand &Src0 = MI.getOperand(1);
3849     MachineOperand &Src1 = MI.getOperand(2);
3850 
3851     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3852     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3853 
3854     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3855         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3856     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3857         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3858 
3859     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3860         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3861     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3862         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3863 
3864     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3865 
3866     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3867     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3868     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3869     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3870     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3871         .addReg(DestSub0)
3872         .addImm(AMDGPU::sub0)
3873         .addReg(DestSub1)
3874         .addImm(AMDGPU::sub1);
3875     MI.eraseFromParent();
3876     return BB;
3877   }
3878   case AMDGPU::V_ADD_U64_PSEUDO:
3879   case AMDGPU::V_SUB_U64_PSEUDO: {
3880     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3881     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3882     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3883     const DebugLoc &DL = MI.getDebugLoc();
3884 
3885     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3886 
3887     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3888 
3889     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3890     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3891 
3892     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3893     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3894 
3895     MachineOperand &Dest = MI.getOperand(0);
3896     MachineOperand &Src0 = MI.getOperand(1);
3897     MachineOperand &Src1 = MI.getOperand(2);
3898 
3899     const TargetRegisterClass *Src0RC = Src0.isReg()
3900                                             ? MRI.getRegClass(Src0.getReg())
3901                                             : &AMDGPU::VReg_64RegClass;
3902     const TargetRegisterClass *Src1RC = Src1.isReg()
3903                                             ? MRI.getRegClass(Src1.getReg())
3904                                             : &AMDGPU::VReg_64RegClass;
3905 
3906     const TargetRegisterClass *Src0SubRC =
3907         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3908     const TargetRegisterClass *Src1SubRC =
3909         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3910 
3911     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3912         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3913     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3914         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3915 
3916     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3917         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3918     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3919         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3920 
3921     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3922     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3923                                .addReg(CarryReg, RegState::Define)
3924                                .add(SrcReg0Sub0)
3925                                .add(SrcReg1Sub0)
3926                                .addImm(0); // clamp bit
3927 
3928     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3929     MachineInstr *HiHalf =
3930         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3931             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3932             .add(SrcReg0Sub1)
3933             .add(SrcReg1Sub1)
3934             .addReg(CarryReg, RegState::Kill)
3935             .addImm(0); // clamp bit
3936 
3937     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3938         .addReg(DestSub0)
3939         .addImm(AMDGPU::sub0)
3940         .addReg(DestSub1)
3941         .addImm(AMDGPU::sub1);
3942     TII->legalizeOperands(*LoHalf);
3943     TII->legalizeOperands(*HiHalf);
3944     MI.eraseFromParent();
3945     return BB;
3946   }
3947   case AMDGPU::S_ADD_CO_PSEUDO:
3948   case AMDGPU::S_SUB_CO_PSEUDO: {
3949     // This pseudo has a chance to be selected
3950     // only from uniform add/subcarry node. All the VGPR operands
3951     // therefore assumed to be splat vectors.
3952     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3953     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3954     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3955     MachineBasicBlock::iterator MII = MI;
3956     const DebugLoc &DL = MI.getDebugLoc();
3957     MachineOperand &Dest = MI.getOperand(0);
3958     MachineOperand &CarryDest = MI.getOperand(1);
3959     MachineOperand &Src0 = MI.getOperand(2);
3960     MachineOperand &Src1 = MI.getOperand(3);
3961     MachineOperand &Src2 = MI.getOperand(4);
3962     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3963                        ? AMDGPU::S_ADDC_U32
3964                        : AMDGPU::S_SUBB_U32;
3965     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3966       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3967       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3968           .addReg(Src0.getReg());
3969       Src0.setReg(RegOp0);
3970     }
3971     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3972       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3973       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3974           .addReg(Src1.getReg());
3975       Src1.setReg(RegOp1);
3976     }
3977     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3978     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3979       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3980           .addReg(Src2.getReg());
3981       Src2.setReg(RegOp2);
3982     }
3983 
3984     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
3985     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
3986       if (ST.hasScalarCompareEq64()) {
3987         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3988             .addReg(Src2.getReg())
3989             .addImm(0);
3990       } else {
3991         const TargetRegisterClass *SubRC =
3992             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
3993         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
3994             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
3995         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
3996             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
3997         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3998 
3999         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4000             .add(Src2Sub0)
4001             .add(Src2Sub1);
4002 
4003         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4004             .addReg(Src2_32, RegState::Kill)
4005             .addImm(0);
4006       }
4007     } else {
4008       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4009           .addReg(Src2.getReg())
4010           .addImm(0);
4011     }
4012 
4013     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4014 
4015     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4016       .addReg(AMDGPU::SCC);
4017     MI.eraseFromParent();
4018     return BB;
4019   }
4020   case AMDGPU::SI_INIT_M0: {
4021     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4022             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4023         .add(MI.getOperand(0));
4024     MI.eraseFromParent();
4025     return BB;
4026   }
4027   case AMDGPU::SI_INIT_EXEC:
4028     // This should be before all vector instructions.
4029     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4030             AMDGPU::EXEC)
4031         .addImm(MI.getOperand(0).getImm());
4032     MI.eraseFromParent();
4033     return BB;
4034 
4035   case AMDGPU::SI_INIT_EXEC_LO:
4036     // This should be before all vector instructions.
4037     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4038             AMDGPU::EXEC_LO)
4039         .addImm(MI.getOperand(0).getImm());
4040     MI.eraseFromParent();
4041     return BB;
4042 
4043   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4044     // Extract the thread count from an SGPR input and set EXEC accordingly.
4045     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4046     //
4047     // S_BFE_U32 count, input, {shift, 7}
4048     // S_BFM_B64 exec, count, 0
4049     // S_CMP_EQ_U32 count, 64
4050     // S_CMOV_B64 exec, -1
4051     MachineInstr *FirstMI = &*BB->begin();
4052     MachineRegisterInfo &MRI = MF->getRegInfo();
4053     Register InputReg = MI.getOperand(0).getReg();
4054     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4055     bool Found = false;
4056 
4057     // Move the COPY of the input reg to the beginning, so that we can use it.
4058     for (auto I = BB->begin(); I != &MI; I++) {
4059       if (I->getOpcode() != TargetOpcode::COPY ||
4060           I->getOperand(0).getReg() != InputReg)
4061         continue;
4062 
4063       if (I == FirstMI) {
4064         FirstMI = &*++BB->begin();
4065       } else {
4066         I->removeFromParent();
4067         BB->insert(FirstMI, &*I);
4068       }
4069       Found = true;
4070       break;
4071     }
4072     assert(Found);
4073     (void)Found;
4074 
4075     // This should be before all vector instructions.
4076     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4077     bool isWave32 = getSubtarget()->isWave32();
4078     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4079     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4080         .addReg(InputReg)
4081         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4082     BuildMI(*BB, FirstMI, DebugLoc(),
4083             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4084             Exec)
4085         .addReg(CountReg)
4086         .addImm(0);
4087     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4088         .addReg(CountReg, RegState::Kill)
4089         .addImm(getSubtarget()->getWavefrontSize());
4090     BuildMI(*BB, FirstMI, DebugLoc(),
4091             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4092             Exec)
4093         .addImm(-1);
4094     MI.eraseFromParent();
4095     return BB;
4096   }
4097 
4098   case AMDGPU::GET_GROUPSTATICSIZE: {
4099     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4100            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4101     DebugLoc DL = MI.getDebugLoc();
4102     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4103         .add(MI.getOperand(0))
4104         .addImm(MFI->getLDSSize());
4105     MI.eraseFromParent();
4106     return BB;
4107   }
4108   case AMDGPU::SI_INDIRECT_SRC_V1:
4109   case AMDGPU::SI_INDIRECT_SRC_V2:
4110   case AMDGPU::SI_INDIRECT_SRC_V4:
4111   case AMDGPU::SI_INDIRECT_SRC_V8:
4112   case AMDGPU::SI_INDIRECT_SRC_V16:
4113   case AMDGPU::SI_INDIRECT_SRC_V32:
4114     return emitIndirectSrc(MI, *BB, *getSubtarget());
4115   case AMDGPU::SI_INDIRECT_DST_V1:
4116   case AMDGPU::SI_INDIRECT_DST_V2:
4117   case AMDGPU::SI_INDIRECT_DST_V4:
4118   case AMDGPU::SI_INDIRECT_DST_V8:
4119   case AMDGPU::SI_INDIRECT_DST_V16:
4120   case AMDGPU::SI_INDIRECT_DST_V32:
4121     return emitIndirectDst(MI, *BB, *getSubtarget());
4122   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4123   case AMDGPU::SI_KILL_I1_PSEUDO:
4124     return splitKillBlock(MI, BB);
4125   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4126     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4127     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4128     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4129 
4130     Register Dst = MI.getOperand(0).getReg();
4131     Register Src0 = MI.getOperand(1).getReg();
4132     Register Src1 = MI.getOperand(2).getReg();
4133     const DebugLoc &DL = MI.getDebugLoc();
4134     Register SrcCond = MI.getOperand(3).getReg();
4135 
4136     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4137     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4138     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4139     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4140 
4141     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4142       .addReg(SrcCond);
4143     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4144       .addImm(0)
4145       .addReg(Src0, 0, AMDGPU::sub0)
4146       .addImm(0)
4147       .addReg(Src1, 0, AMDGPU::sub0)
4148       .addReg(SrcCondCopy);
4149     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4150       .addImm(0)
4151       .addReg(Src0, 0, AMDGPU::sub1)
4152       .addImm(0)
4153       .addReg(Src1, 0, AMDGPU::sub1)
4154       .addReg(SrcCondCopy);
4155 
4156     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4157       .addReg(DstLo)
4158       .addImm(AMDGPU::sub0)
4159       .addReg(DstHi)
4160       .addImm(AMDGPU::sub1);
4161     MI.eraseFromParent();
4162     return BB;
4163   }
4164   case AMDGPU::SI_BR_UNDEF: {
4165     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4166     const DebugLoc &DL = MI.getDebugLoc();
4167     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4168                            .add(MI.getOperand(0));
4169     Br->getOperand(1).setIsUndef(true); // read undef SCC
4170     MI.eraseFromParent();
4171     return BB;
4172   }
4173   case AMDGPU::ADJCALLSTACKUP:
4174   case AMDGPU::ADJCALLSTACKDOWN: {
4175     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4176     MachineInstrBuilder MIB(*MF, &MI);
4177     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4178        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4179     return BB;
4180   }
4181   case AMDGPU::SI_CALL_ISEL: {
4182     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4183     const DebugLoc &DL = MI.getDebugLoc();
4184 
4185     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4186 
4187     MachineInstrBuilder MIB;
4188     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4189 
4190     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4191       MIB.add(MI.getOperand(I));
4192 
4193     MIB.cloneMemRefs(MI);
4194     MI.eraseFromParent();
4195     return BB;
4196   }
4197   case AMDGPU::V_ADD_CO_U32_e32:
4198   case AMDGPU::V_SUB_CO_U32_e32:
4199   case AMDGPU::V_SUBREV_CO_U32_e32: {
4200     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4201     const DebugLoc &DL = MI.getDebugLoc();
4202     unsigned Opc = MI.getOpcode();
4203 
4204     bool NeedClampOperand = false;
4205     if (TII->pseudoToMCOpcode(Opc) == -1) {
4206       Opc = AMDGPU::getVOPe64(Opc);
4207       NeedClampOperand = true;
4208     }
4209 
4210     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4211     if (TII->isVOP3(*I)) {
4212       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4213       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4214       I.addReg(TRI->getVCC(), RegState::Define);
4215     }
4216     I.add(MI.getOperand(1))
4217      .add(MI.getOperand(2));
4218     if (NeedClampOperand)
4219       I.addImm(0); // clamp bit for e64 encoding
4220 
4221     TII->legalizeOperands(*I);
4222 
4223     MI.eraseFromParent();
4224     return BB;
4225   }
4226   case AMDGPU::DS_GWS_INIT:
4227   case AMDGPU::DS_GWS_SEMA_V:
4228   case AMDGPU::DS_GWS_SEMA_BR:
4229   case AMDGPU::DS_GWS_SEMA_P:
4230   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4231   case AMDGPU::DS_GWS_BARRIER:
4232     // A s_waitcnt 0 is required to be the instruction immediately following.
4233     if (getSubtarget()->hasGWSAutoReplay()) {
4234       bundleInstWithWaitcnt(MI);
4235       return BB;
4236     }
4237 
4238     return emitGWSMemViolTestLoop(MI, BB);
4239   case AMDGPU::S_SETREG_B32: {
4240     // Try to optimize cases that only set the denormal mode or rounding mode.
4241     //
4242     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4243     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4244     // instead.
4245     //
4246     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4247     // allow you to have a no side effect instruction in the output of a
4248     // sideeffecting pattern.
4249     unsigned ID, Offset, Width;
4250     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4251     if (ID != AMDGPU::Hwreg::ID_MODE)
4252       return BB;
4253 
4254     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4255     const unsigned SetMask = WidthMask << Offset;
4256 
4257     if (getSubtarget()->hasDenormModeInst()) {
4258       unsigned SetDenormOp = 0;
4259       unsigned SetRoundOp = 0;
4260 
4261       // The dedicated instructions can only set the whole denorm or round mode
4262       // at once, not a subset of bits in either.
4263       if (SetMask ==
4264           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4265         // If this fully sets both the round and denorm mode, emit the two
4266         // dedicated instructions for these.
4267         SetRoundOp = AMDGPU::S_ROUND_MODE;
4268         SetDenormOp = AMDGPU::S_DENORM_MODE;
4269       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4270         SetRoundOp = AMDGPU::S_ROUND_MODE;
4271       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4272         SetDenormOp = AMDGPU::S_DENORM_MODE;
4273       }
4274 
4275       if (SetRoundOp || SetDenormOp) {
4276         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4277         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4278         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4279           unsigned ImmVal = Def->getOperand(1).getImm();
4280           if (SetRoundOp) {
4281             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4282                 .addImm(ImmVal & 0xf);
4283 
4284             // If we also have the denorm mode, get just the denorm mode bits.
4285             ImmVal >>= 4;
4286           }
4287 
4288           if (SetDenormOp) {
4289             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4290                 .addImm(ImmVal & 0xf);
4291           }
4292 
4293           MI.eraseFromParent();
4294           return BB;
4295         }
4296       }
4297     }
4298 
4299     // If only FP bits are touched, used the no side effects pseudo.
4300     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4301                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4302       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4303 
4304     return BB;
4305   }
4306   default:
4307     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4308   }
4309 }
4310 
4311 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4312   return isTypeLegal(VT.getScalarType());
4313 }
4314 
4315 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4316   // This currently forces unfolding various combinations of fsub into fma with
4317   // free fneg'd operands. As long as we have fast FMA (controlled by
4318   // isFMAFasterThanFMulAndFAdd), we should perform these.
4319 
4320   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4321   // most of these combines appear to be cycle neutral but save on instruction
4322   // count / code size.
4323   return true;
4324 }
4325 
4326 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4327                                          EVT VT) const {
4328   if (!VT.isVector()) {
4329     return MVT::i1;
4330   }
4331   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4332 }
4333 
4334 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4335   // TODO: Should i16 be used always if legal? For now it would force VALU
4336   // shifts.
4337   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4338 }
4339 
4340 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4341   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4342              ? Ty.changeElementSize(16)
4343              : Ty.changeElementSize(32);
4344 }
4345 
4346 // Answering this is somewhat tricky and depends on the specific device which
4347 // have different rates for fma or all f64 operations.
4348 //
4349 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4350 // regardless of which device (although the number of cycles differs between
4351 // devices), so it is always profitable for f64.
4352 //
4353 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4354 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4355 // which we can always do even without fused FP ops since it returns the same
4356 // result as the separate operations and since it is always full
4357 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4358 // however does not support denormals, so we do report fma as faster if we have
4359 // a fast fma device and require denormals.
4360 //
4361 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4362                                                   EVT VT) const {
4363   VT = VT.getScalarType();
4364 
4365   switch (VT.getSimpleVT().SimpleTy) {
4366   case MVT::f32: {
4367     // If mad is not available this depends only on if f32 fma is full rate.
4368     if (!Subtarget->hasMadMacF32Insts())
4369       return Subtarget->hasFastFMAF32();
4370 
4371     // Otherwise f32 mad is always full rate and returns the same result as
4372     // the separate operations so should be preferred over fma.
4373     // However does not support denomals.
4374     if (hasFP32Denormals(MF))
4375       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4376 
4377     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4378     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4379   }
4380   case MVT::f64:
4381     return true;
4382   case MVT::f16:
4383     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4384   default:
4385     break;
4386   }
4387 
4388   return false;
4389 }
4390 
4391 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4392                                    const SDNode *N) const {
4393   // TODO: Check future ftz flag
4394   // v_mad_f32/v_mac_f32 do not support denormals.
4395   EVT VT = N->getValueType(0);
4396   if (VT == MVT::f32)
4397     return Subtarget->hasMadMacF32Insts() &&
4398            !hasFP32Denormals(DAG.getMachineFunction());
4399   if (VT == MVT::f16) {
4400     return Subtarget->hasMadF16() &&
4401            !hasFP64FP16Denormals(DAG.getMachineFunction());
4402   }
4403 
4404   return false;
4405 }
4406 
4407 //===----------------------------------------------------------------------===//
4408 // Custom DAG Lowering Operations
4409 //===----------------------------------------------------------------------===//
4410 
4411 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4412 // wider vector type is legal.
4413 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4414                                              SelectionDAG &DAG) const {
4415   unsigned Opc = Op.getOpcode();
4416   EVT VT = Op.getValueType();
4417   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4418 
4419   SDValue Lo, Hi;
4420   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4421 
4422   SDLoc SL(Op);
4423   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4424                              Op->getFlags());
4425   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4426                              Op->getFlags());
4427 
4428   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4429 }
4430 
4431 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4432 // wider vector type is legal.
4433 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4434                                               SelectionDAG &DAG) const {
4435   unsigned Opc = Op.getOpcode();
4436   EVT VT = Op.getValueType();
4437   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4438 
4439   SDValue Lo0, Hi0;
4440   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4441   SDValue Lo1, Hi1;
4442   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4443 
4444   SDLoc SL(Op);
4445 
4446   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4447                              Op->getFlags());
4448   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4449                              Op->getFlags());
4450 
4451   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4452 }
4453 
4454 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4455                                               SelectionDAG &DAG) const {
4456   unsigned Opc = Op.getOpcode();
4457   EVT VT = Op.getValueType();
4458   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4459 
4460   SDValue Lo0, Hi0;
4461   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4462   SDValue Lo1, Hi1;
4463   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4464   SDValue Lo2, Hi2;
4465   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4466 
4467   SDLoc SL(Op);
4468 
4469   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4470                              Op->getFlags());
4471   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4472                              Op->getFlags());
4473 
4474   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4475 }
4476 
4477 
4478 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4479   switch (Op.getOpcode()) {
4480   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4481   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4482   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4483   case ISD::LOAD: {
4484     SDValue Result = LowerLOAD(Op, DAG);
4485     assert((!Result.getNode() ||
4486             Result.getNode()->getNumValues() == 2) &&
4487            "Load should return a value and a chain");
4488     return Result;
4489   }
4490 
4491   case ISD::FSIN:
4492   case ISD::FCOS:
4493     return LowerTrig(Op, DAG);
4494   case ISD::SELECT: return LowerSELECT(Op, DAG);
4495   case ISD::FDIV: return LowerFDIV(Op, DAG);
4496   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4497   case ISD::STORE: return LowerSTORE(Op, DAG);
4498   case ISD::GlobalAddress: {
4499     MachineFunction &MF = DAG.getMachineFunction();
4500     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4501     return LowerGlobalAddress(MFI, Op, DAG);
4502   }
4503   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4504   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4505   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4506   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4507   case ISD::INSERT_SUBVECTOR:
4508     return lowerINSERT_SUBVECTOR(Op, DAG);
4509   case ISD::INSERT_VECTOR_ELT:
4510     return lowerINSERT_VECTOR_ELT(Op, DAG);
4511   case ISD::EXTRACT_VECTOR_ELT:
4512     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4513   case ISD::VECTOR_SHUFFLE:
4514     return lowerVECTOR_SHUFFLE(Op, DAG);
4515   case ISD::BUILD_VECTOR:
4516     return lowerBUILD_VECTOR(Op, DAG);
4517   case ISD::FP_ROUND:
4518     return lowerFP_ROUND(Op, DAG);
4519   case ISD::TRAP:
4520     return lowerTRAP(Op, DAG);
4521   case ISD::DEBUGTRAP:
4522     return lowerDEBUGTRAP(Op, DAG);
4523   case ISD::FABS:
4524   case ISD::FNEG:
4525   case ISD::FCANONICALIZE:
4526   case ISD::BSWAP:
4527     return splitUnaryVectorOp(Op, DAG);
4528   case ISD::FMINNUM:
4529   case ISD::FMAXNUM:
4530     return lowerFMINNUM_FMAXNUM(Op, DAG);
4531   case ISD::FMA:
4532     return splitTernaryVectorOp(Op, DAG);
4533   case ISD::SHL:
4534   case ISD::SRA:
4535   case ISD::SRL:
4536   case ISD::ADD:
4537   case ISD::SUB:
4538   case ISD::MUL:
4539   case ISD::SMIN:
4540   case ISD::SMAX:
4541   case ISD::UMIN:
4542   case ISD::UMAX:
4543   case ISD::FADD:
4544   case ISD::FMUL:
4545   case ISD::FMINNUM_IEEE:
4546   case ISD::FMAXNUM_IEEE:
4547   case ISD::UADDSAT:
4548   case ISD::USUBSAT:
4549   case ISD::SADDSAT:
4550   case ISD::SSUBSAT:
4551     return splitBinaryVectorOp(Op, DAG);
4552   case ISD::SMULO:
4553   case ISD::UMULO:
4554     return lowerXMULO(Op, DAG);
4555   case ISD::DYNAMIC_STACKALLOC:
4556     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4557   }
4558   return SDValue();
4559 }
4560 
4561 // Used for D16: Casts the result of an instruction into the right vector,
4562 // packs values if loads return unpacked values.
4563 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4564                                        const SDLoc &DL,
4565                                        SelectionDAG &DAG, bool Unpacked) {
4566   if (!LoadVT.isVector())
4567     return Result;
4568 
4569   // Cast back to the original packed type or to a larger type that is a
4570   // multiple of 32 bit for D16. Widening the return type is a required for
4571   // legalization.
4572   EVT FittingLoadVT = LoadVT;
4573   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4574     FittingLoadVT =
4575         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4576                          LoadVT.getVectorNumElements() + 1);
4577   }
4578 
4579   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4580     // Truncate to v2i16/v4i16.
4581     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4582 
4583     // Workaround legalizer not scalarizing truncate after vector op
4584     // legalization but not creating intermediate vector trunc.
4585     SmallVector<SDValue, 4> Elts;
4586     DAG.ExtractVectorElements(Result, Elts);
4587     for (SDValue &Elt : Elts)
4588       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4589 
4590     // Pad illegal v1i16/v3fi6 to v4i16
4591     if ((LoadVT.getVectorNumElements() % 2) == 1)
4592       Elts.push_back(DAG.getUNDEF(MVT::i16));
4593 
4594     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4595 
4596     // Bitcast to original type (v2f16/v4f16).
4597     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4598   }
4599 
4600   // Cast back to the original packed type.
4601   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4602 }
4603 
4604 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4605                                               MemSDNode *M,
4606                                               SelectionDAG &DAG,
4607                                               ArrayRef<SDValue> Ops,
4608                                               bool IsIntrinsic) const {
4609   SDLoc DL(M);
4610 
4611   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4612   EVT LoadVT = M->getValueType(0);
4613 
4614   EVT EquivLoadVT = LoadVT;
4615   if (LoadVT.isVector()) {
4616     if (Unpacked) {
4617       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4618                                      LoadVT.getVectorNumElements());
4619     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4620       // Widen v3f16 to legal type
4621       EquivLoadVT =
4622           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4623                            LoadVT.getVectorNumElements() + 1);
4624     }
4625   }
4626 
4627   // Change from v4f16/v2f16 to EquivLoadVT.
4628   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4629 
4630   SDValue Load
4631     = DAG.getMemIntrinsicNode(
4632       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4633       VTList, Ops, M->getMemoryVT(),
4634       M->getMemOperand());
4635 
4636   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4637 
4638   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4639 }
4640 
4641 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4642                                              SelectionDAG &DAG,
4643                                              ArrayRef<SDValue> Ops) const {
4644   SDLoc DL(M);
4645   EVT LoadVT = M->getValueType(0);
4646   EVT EltType = LoadVT.getScalarType();
4647   EVT IntVT = LoadVT.changeTypeToInteger();
4648 
4649   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4650 
4651   unsigned Opc =
4652       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4653 
4654   if (IsD16) {
4655     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4656   }
4657 
4658   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4659   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4660     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4661 
4662   if (isTypeLegal(LoadVT)) {
4663     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4664                                M->getMemOperand(), DAG);
4665   }
4666 
4667   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4668   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4669   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4670                                         M->getMemOperand(), DAG);
4671   return DAG.getMergeValues(
4672       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4673       DL);
4674 }
4675 
4676 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4677                                   SDNode *N, SelectionDAG &DAG) {
4678   EVT VT = N->getValueType(0);
4679   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4680   unsigned CondCode = CD->getZExtValue();
4681   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4682     return DAG.getUNDEF(VT);
4683 
4684   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4685 
4686   SDValue LHS = N->getOperand(1);
4687   SDValue RHS = N->getOperand(2);
4688 
4689   SDLoc DL(N);
4690 
4691   EVT CmpVT = LHS.getValueType();
4692   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4693     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4694       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4695     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4696     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4697   }
4698 
4699   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4700 
4701   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4702   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4703 
4704   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4705                               DAG.getCondCode(CCOpcode));
4706   if (VT.bitsEq(CCVT))
4707     return SetCC;
4708   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4709 }
4710 
4711 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4712                                   SDNode *N, SelectionDAG &DAG) {
4713   EVT VT = N->getValueType(0);
4714   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4715 
4716   unsigned CondCode = CD->getZExtValue();
4717   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4718     return DAG.getUNDEF(VT);
4719 
4720   SDValue Src0 = N->getOperand(1);
4721   SDValue Src1 = N->getOperand(2);
4722   EVT CmpVT = Src0.getValueType();
4723   SDLoc SL(N);
4724 
4725   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4726     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4727     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4728   }
4729 
4730   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4731   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4732   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4733   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4734   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4735                               Src1, DAG.getCondCode(CCOpcode));
4736   if (VT.bitsEq(CCVT))
4737     return SetCC;
4738   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4739 }
4740 
4741 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4742                                     SelectionDAG &DAG) {
4743   EVT VT = N->getValueType(0);
4744   SDValue Src = N->getOperand(1);
4745   SDLoc SL(N);
4746 
4747   if (Src.getOpcode() == ISD::SETCC) {
4748     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4749     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4750                        Src.getOperand(1), Src.getOperand(2));
4751   }
4752   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4753     // (ballot 0) -> 0
4754     if (Arg->isNullValue())
4755       return DAG.getConstant(0, SL, VT);
4756 
4757     // (ballot 1) -> EXEC/EXEC_LO
4758     if (Arg->isOne()) {
4759       Register Exec;
4760       if (VT.getScalarSizeInBits() == 32)
4761         Exec = AMDGPU::EXEC_LO;
4762       else if (VT.getScalarSizeInBits() == 64)
4763         Exec = AMDGPU::EXEC;
4764       else
4765         return SDValue();
4766 
4767       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4768     }
4769   }
4770 
4771   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4772   // ISD::SETNE)
4773   return DAG.getNode(
4774       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4775       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4776 }
4777 
4778 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4779                                           SmallVectorImpl<SDValue> &Results,
4780                                           SelectionDAG &DAG) const {
4781   switch (N->getOpcode()) {
4782   case ISD::INSERT_VECTOR_ELT: {
4783     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4784       Results.push_back(Res);
4785     return;
4786   }
4787   case ISD::EXTRACT_VECTOR_ELT: {
4788     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4789       Results.push_back(Res);
4790     return;
4791   }
4792   case ISD::INTRINSIC_WO_CHAIN: {
4793     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4794     switch (IID) {
4795     case Intrinsic::amdgcn_cvt_pkrtz: {
4796       SDValue Src0 = N->getOperand(1);
4797       SDValue Src1 = N->getOperand(2);
4798       SDLoc SL(N);
4799       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4800                                 Src0, Src1);
4801       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4802       return;
4803     }
4804     case Intrinsic::amdgcn_cvt_pknorm_i16:
4805     case Intrinsic::amdgcn_cvt_pknorm_u16:
4806     case Intrinsic::amdgcn_cvt_pk_i16:
4807     case Intrinsic::amdgcn_cvt_pk_u16: {
4808       SDValue Src0 = N->getOperand(1);
4809       SDValue Src1 = N->getOperand(2);
4810       SDLoc SL(N);
4811       unsigned Opcode;
4812 
4813       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4814         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4815       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4816         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4817       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4818         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4819       else
4820         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4821 
4822       EVT VT = N->getValueType(0);
4823       if (isTypeLegal(VT))
4824         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4825       else {
4826         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4827         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4828       }
4829       return;
4830     }
4831     }
4832     break;
4833   }
4834   case ISD::INTRINSIC_W_CHAIN: {
4835     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4836       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4837         // FIXME: Hacky
4838         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4839           Results.push_back(Res.getOperand(I));
4840         }
4841       } else {
4842         Results.push_back(Res);
4843         Results.push_back(Res.getValue(1));
4844       }
4845       return;
4846     }
4847 
4848     break;
4849   }
4850   case ISD::SELECT: {
4851     SDLoc SL(N);
4852     EVT VT = N->getValueType(0);
4853     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4854     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4855     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4856 
4857     EVT SelectVT = NewVT;
4858     if (NewVT.bitsLT(MVT::i32)) {
4859       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4860       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4861       SelectVT = MVT::i32;
4862     }
4863 
4864     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4865                                     N->getOperand(0), LHS, RHS);
4866 
4867     if (NewVT != SelectVT)
4868       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4869     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4870     return;
4871   }
4872   case ISD::FNEG: {
4873     if (N->getValueType(0) != MVT::v2f16)
4874       break;
4875 
4876     SDLoc SL(N);
4877     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4878 
4879     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4880                              BC,
4881                              DAG.getConstant(0x80008000, SL, MVT::i32));
4882     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4883     return;
4884   }
4885   case ISD::FABS: {
4886     if (N->getValueType(0) != MVT::v2f16)
4887       break;
4888 
4889     SDLoc SL(N);
4890     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4891 
4892     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4893                              BC,
4894                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4895     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4896     return;
4897   }
4898   default:
4899     break;
4900   }
4901 }
4902 
4903 /// Helper function for LowerBRCOND
4904 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4905 
4906   SDNode *Parent = Value.getNode();
4907   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4908        I != E; ++I) {
4909 
4910     if (I.getUse().get() != Value)
4911       continue;
4912 
4913     if (I->getOpcode() == Opcode)
4914       return *I;
4915   }
4916   return nullptr;
4917 }
4918 
4919 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4920   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4921     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4922     case Intrinsic::amdgcn_if:
4923       return AMDGPUISD::IF;
4924     case Intrinsic::amdgcn_else:
4925       return AMDGPUISD::ELSE;
4926     case Intrinsic::amdgcn_loop:
4927       return AMDGPUISD::LOOP;
4928     case Intrinsic::amdgcn_end_cf:
4929       llvm_unreachable("should not occur");
4930     default:
4931       return 0;
4932     }
4933   }
4934 
4935   // break, if_break, else_break are all only used as inputs to loop, not
4936   // directly as branch conditions.
4937   return 0;
4938 }
4939 
4940 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4941   const Triple &TT = getTargetMachine().getTargetTriple();
4942   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4943           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4944          AMDGPU::shouldEmitConstantsToTextSection(TT);
4945 }
4946 
4947 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4948   // FIXME: Either avoid relying on address space here or change the default
4949   // address space for functions to avoid the explicit check.
4950   return (GV->getValueType()->isFunctionTy() ||
4951           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4952          !shouldEmitFixup(GV) &&
4953          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4954 }
4955 
4956 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4957   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4958 }
4959 
4960 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4961   if (!GV->hasExternalLinkage())
4962     return true;
4963 
4964   const auto OS = getTargetMachine().getTargetTriple().getOS();
4965   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4966 }
4967 
4968 /// This transforms the control flow intrinsics to get the branch destination as
4969 /// last parameter, also switches branch target with BR if the need arise
4970 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4971                                       SelectionDAG &DAG) const {
4972   SDLoc DL(BRCOND);
4973 
4974   SDNode *Intr = BRCOND.getOperand(1).getNode();
4975   SDValue Target = BRCOND.getOperand(2);
4976   SDNode *BR = nullptr;
4977   SDNode *SetCC = nullptr;
4978 
4979   if (Intr->getOpcode() == ISD::SETCC) {
4980     // As long as we negate the condition everything is fine
4981     SetCC = Intr;
4982     Intr = SetCC->getOperand(0).getNode();
4983 
4984   } else {
4985     // Get the target from BR if we don't negate the condition
4986     BR = findUser(BRCOND, ISD::BR);
4987     assert(BR && "brcond missing unconditional branch user");
4988     Target = BR->getOperand(1);
4989   }
4990 
4991   unsigned CFNode = isCFIntrinsic(Intr);
4992   if (CFNode == 0) {
4993     // This is a uniform branch so we don't need to legalize.
4994     return BRCOND;
4995   }
4996 
4997   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4998                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4999 
5000   assert(!SetCC ||
5001         (SetCC->getConstantOperandVal(1) == 1 &&
5002          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5003                                                              ISD::SETNE));
5004 
5005   // operands of the new intrinsic call
5006   SmallVector<SDValue, 4> Ops;
5007   if (HaveChain)
5008     Ops.push_back(BRCOND.getOperand(0));
5009 
5010   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5011   Ops.push_back(Target);
5012 
5013   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5014 
5015   // build the new intrinsic call
5016   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5017 
5018   if (!HaveChain) {
5019     SDValue Ops[] =  {
5020       SDValue(Result, 0),
5021       BRCOND.getOperand(0)
5022     };
5023 
5024     Result = DAG.getMergeValues(Ops, DL).getNode();
5025   }
5026 
5027   if (BR) {
5028     // Give the branch instruction our target
5029     SDValue Ops[] = {
5030       BR->getOperand(0),
5031       BRCOND.getOperand(2)
5032     };
5033     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5034     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5035   }
5036 
5037   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5038 
5039   // Copy the intrinsic results to registers
5040   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5041     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5042     if (!CopyToReg)
5043       continue;
5044 
5045     Chain = DAG.getCopyToReg(
5046       Chain, DL,
5047       CopyToReg->getOperand(1),
5048       SDValue(Result, i - 1),
5049       SDValue());
5050 
5051     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5052   }
5053 
5054   // Remove the old intrinsic from the chain
5055   DAG.ReplaceAllUsesOfValueWith(
5056     SDValue(Intr, Intr->getNumValues() - 1),
5057     Intr->getOperand(0));
5058 
5059   return Chain;
5060 }
5061 
5062 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5063                                           SelectionDAG &DAG) const {
5064   MVT VT = Op.getSimpleValueType();
5065   SDLoc DL(Op);
5066   // Checking the depth
5067   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5068     return DAG.getConstant(0, DL, VT);
5069 
5070   MachineFunction &MF = DAG.getMachineFunction();
5071   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5072   // Check for kernel and shader functions
5073   if (Info->isEntryFunction())
5074     return DAG.getConstant(0, DL, VT);
5075 
5076   MachineFrameInfo &MFI = MF.getFrameInfo();
5077   // There is a call to @llvm.returnaddress in this function
5078   MFI.setReturnAddressIsTaken(true);
5079 
5080   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5081   // Get the return address reg and mark it as an implicit live-in
5082   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5083 
5084   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5085 }
5086 
5087 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5088                                             SDValue Op,
5089                                             const SDLoc &DL,
5090                                             EVT VT) const {
5091   return Op.getValueType().bitsLE(VT) ?
5092       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5093     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5094                 DAG.getTargetConstant(0, DL, MVT::i32));
5095 }
5096 
5097 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5098   assert(Op.getValueType() == MVT::f16 &&
5099          "Do not know how to custom lower FP_ROUND for non-f16 type");
5100 
5101   SDValue Src = Op.getOperand(0);
5102   EVT SrcVT = Src.getValueType();
5103   if (SrcVT != MVT::f64)
5104     return Op;
5105 
5106   SDLoc DL(Op);
5107 
5108   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5109   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5110   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5111 }
5112 
5113 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5114                                                SelectionDAG &DAG) const {
5115   EVT VT = Op.getValueType();
5116   const MachineFunction &MF = DAG.getMachineFunction();
5117   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5118   bool IsIEEEMode = Info->getMode().IEEE;
5119 
5120   // FIXME: Assert during selection that this is only selected for
5121   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5122   // mode functions, but this happens to be OK since it's only done in cases
5123   // where there is known no sNaN.
5124   if (IsIEEEMode)
5125     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5126 
5127   if (VT == MVT::v4f16)
5128     return splitBinaryVectorOp(Op, DAG);
5129   return Op;
5130 }
5131 
5132 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5133   EVT VT = Op.getValueType();
5134   SDLoc SL(Op);
5135   SDValue LHS = Op.getOperand(0);
5136   SDValue RHS = Op.getOperand(1);
5137   bool isSigned = Op.getOpcode() == ISD::SMULO;
5138 
5139   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5140     const APInt &C = RHSC->getAPIntValue();
5141     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5142     if (C.isPowerOf2()) {
5143       // smulo(x, signed_min) is same as umulo(x, signed_min).
5144       bool UseArithShift = isSigned && !C.isMinSignedValue();
5145       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5146       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5147       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5148           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5149                       SL, VT, Result, ShiftAmt),
5150           LHS, ISD::SETNE);
5151       return DAG.getMergeValues({ Result, Overflow }, SL);
5152     }
5153   }
5154 
5155   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5156   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5157                             SL, VT, LHS, RHS);
5158 
5159   SDValue Sign = isSigned
5160     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5161                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5162     : DAG.getConstant(0, SL, VT);
5163   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5164 
5165   return DAG.getMergeValues({ Result, Overflow }, SL);
5166 }
5167 
5168 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5169   SDLoc SL(Op);
5170   SDValue Chain = Op.getOperand(0);
5171 
5172   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5173       !Subtarget->isTrapHandlerEnabled())
5174     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5175 
5176   MachineFunction &MF = DAG.getMachineFunction();
5177   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5178   Register UserSGPR = Info->getQueuePtrUserSGPR();
5179   assert(UserSGPR != AMDGPU::NoRegister);
5180   SDValue QueuePtr = CreateLiveInRegister(
5181     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5182   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5183   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5184                                    QueuePtr, SDValue());
5185   SDValue Ops[] = {
5186     ToReg,
5187     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5188     SGPR01,
5189     ToReg.getValue(1)
5190   };
5191   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5192 }
5193 
5194 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5195   SDLoc SL(Op);
5196   SDValue Chain = Op.getOperand(0);
5197   MachineFunction &MF = DAG.getMachineFunction();
5198 
5199   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5200       !Subtarget->isTrapHandlerEnabled()) {
5201     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5202                                      "debugtrap handler not supported",
5203                                      Op.getDebugLoc(),
5204                                      DS_Warning);
5205     LLVMContext &Ctx = MF.getFunction().getContext();
5206     Ctx.diagnose(NoTrap);
5207     return Chain;
5208   }
5209 
5210   SDValue Ops[] = {
5211     Chain,
5212     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5213   };
5214   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5215 }
5216 
5217 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5218                                              SelectionDAG &DAG) const {
5219   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5220   if (Subtarget->hasApertureRegs()) {
5221     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5222         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5223         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5224     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5225         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5226         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5227     unsigned Encoding =
5228         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5229         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5230         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5231 
5232     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5233     SDValue ApertureReg = SDValue(
5234         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5235     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5236     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5237   }
5238 
5239   MachineFunction &MF = DAG.getMachineFunction();
5240   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5241   Register UserSGPR = Info->getQueuePtrUserSGPR();
5242   assert(UserSGPR != AMDGPU::NoRegister);
5243 
5244   SDValue QueuePtr = CreateLiveInRegister(
5245     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5246 
5247   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5248   // private_segment_aperture_base_hi.
5249   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5250 
5251   SDValue Ptr =
5252       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5253 
5254   // TODO: Use custom target PseudoSourceValue.
5255   // TODO: We should use the value from the IR intrinsic call, but it might not
5256   // be available and how do we get it?
5257   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5258   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5259                      commonAlignment(Align(64), StructOffset),
5260                      MachineMemOperand::MODereferenceable |
5261                          MachineMemOperand::MOInvariant);
5262 }
5263 
5264 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5265                                              SelectionDAG &DAG) const {
5266   SDLoc SL(Op);
5267   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5268 
5269   SDValue Src = ASC->getOperand(0);
5270   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5271 
5272   const AMDGPUTargetMachine &TM =
5273     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5274 
5275   // flat -> local/private
5276   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5277     unsigned DestAS = ASC->getDestAddressSpace();
5278 
5279     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5280         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5281       unsigned NullVal = TM.getNullPointerValue(DestAS);
5282       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5283       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5284       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5285 
5286       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5287                          NonNull, Ptr, SegmentNullPtr);
5288     }
5289   }
5290 
5291   // local/private -> flat
5292   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5293     unsigned SrcAS = ASC->getSrcAddressSpace();
5294 
5295     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5296         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5297       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5298       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5299 
5300       SDValue NonNull
5301         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5302 
5303       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5304       SDValue CvtPtr
5305         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5306 
5307       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5308                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5309                          FlatNullPtr);
5310     }
5311   }
5312 
5313   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5314       Src.getValueType() == MVT::i64)
5315     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5316 
5317   // global <-> flat are no-ops and never emitted.
5318 
5319   const MachineFunction &MF = DAG.getMachineFunction();
5320   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5321     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5322   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5323 
5324   return DAG.getUNDEF(ASC->getValueType(0));
5325 }
5326 
5327 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5328 // the small vector and inserting them into the big vector. That is better than
5329 // the default expansion of doing it via a stack slot. Even though the use of
5330 // the stack slot would be optimized away afterwards, the stack slot itself
5331 // remains.
5332 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5333                                                 SelectionDAG &DAG) const {
5334   SDValue Vec = Op.getOperand(0);
5335   SDValue Ins = Op.getOperand(1);
5336   SDValue Idx = Op.getOperand(2);
5337   EVT VecVT = Vec.getValueType();
5338   EVT InsVT = Ins.getValueType();
5339   EVT EltVT = VecVT.getVectorElementType();
5340   unsigned InsNumElts = InsVT.getVectorNumElements();
5341   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5342   SDLoc SL(Op);
5343 
5344   for (unsigned I = 0; I != InsNumElts; ++I) {
5345     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5346                               DAG.getConstant(I, SL, MVT::i32));
5347     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5348                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5349   }
5350   return Vec;
5351 }
5352 
5353 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5354                                                  SelectionDAG &DAG) const {
5355   SDValue Vec = Op.getOperand(0);
5356   SDValue InsVal = Op.getOperand(1);
5357   SDValue Idx = Op.getOperand(2);
5358   EVT VecVT = Vec.getValueType();
5359   EVT EltVT = VecVT.getVectorElementType();
5360   unsigned VecSize = VecVT.getSizeInBits();
5361   unsigned EltSize = EltVT.getSizeInBits();
5362 
5363 
5364   assert(VecSize <= 64);
5365 
5366   unsigned NumElts = VecVT.getVectorNumElements();
5367   SDLoc SL(Op);
5368   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5369 
5370   if (NumElts == 4 && EltSize == 16 && KIdx) {
5371     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5372 
5373     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5374                                  DAG.getConstant(0, SL, MVT::i32));
5375     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5376                                  DAG.getConstant(1, SL, MVT::i32));
5377 
5378     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5379     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5380 
5381     unsigned Idx = KIdx->getZExtValue();
5382     bool InsertLo = Idx < 2;
5383     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5384       InsertLo ? LoVec : HiVec,
5385       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5386       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5387 
5388     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5389 
5390     SDValue Concat = InsertLo ?
5391       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5392       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5393 
5394     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5395   }
5396 
5397   if (isa<ConstantSDNode>(Idx))
5398     return SDValue();
5399 
5400   MVT IntVT = MVT::getIntegerVT(VecSize);
5401 
5402   // Avoid stack access for dynamic indexing.
5403   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5404 
5405   // Create a congruent vector with the target value in each element so that
5406   // the required element can be masked and ORed into the target vector.
5407   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5408                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5409 
5410   assert(isPowerOf2_32(EltSize));
5411   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5412 
5413   // Convert vector index to bit-index.
5414   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5415 
5416   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5417   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5418                             DAG.getConstant(0xffff, SL, IntVT),
5419                             ScaledIdx);
5420 
5421   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5422   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5423                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5424 
5425   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5426   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5427 }
5428 
5429 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5430                                                   SelectionDAG &DAG) const {
5431   SDLoc SL(Op);
5432 
5433   EVT ResultVT = Op.getValueType();
5434   SDValue Vec = Op.getOperand(0);
5435   SDValue Idx = Op.getOperand(1);
5436   EVT VecVT = Vec.getValueType();
5437   unsigned VecSize = VecVT.getSizeInBits();
5438   EVT EltVT = VecVT.getVectorElementType();
5439   assert(VecSize <= 64);
5440 
5441   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5442 
5443   // Make sure we do any optimizations that will make it easier to fold
5444   // source modifiers before obscuring it with bit operations.
5445 
5446   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5447   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5448     return Combined;
5449 
5450   unsigned EltSize = EltVT.getSizeInBits();
5451   assert(isPowerOf2_32(EltSize));
5452 
5453   MVT IntVT = MVT::getIntegerVT(VecSize);
5454   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5455 
5456   // Convert vector index to bit-index (* EltSize)
5457   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5458 
5459   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5460   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5461 
5462   if (ResultVT == MVT::f16) {
5463     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5464     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5465   }
5466 
5467   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5468 }
5469 
5470 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5471   assert(Elt % 2 == 0);
5472   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5473 }
5474 
5475 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5476                                               SelectionDAG &DAG) const {
5477   SDLoc SL(Op);
5478   EVT ResultVT = Op.getValueType();
5479   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5480 
5481   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5482   EVT EltVT = PackVT.getVectorElementType();
5483   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5484 
5485   // vector_shuffle <0,1,6,7> lhs, rhs
5486   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5487   //
5488   // vector_shuffle <6,7,2,3> lhs, rhs
5489   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5490   //
5491   // vector_shuffle <6,7,0,1> lhs, rhs
5492   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5493 
5494   // Avoid scalarizing when both halves are reading from consecutive elements.
5495   SmallVector<SDValue, 4> Pieces;
5496   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5497     if (elementPairIsContiguous(SVN->getMask(), I)) {
5498       const int Idx = SVN->getMaskElt(I);
5499       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5500       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5501       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5502                                     PackVT, SVN->getOperand(VecIdx),
5503                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5504       Pieces.push_back(SubVec);
5505     } else {
5506       const int Idx0 = SVN->getMaskElt(I);
5507       const int Idx1 = SVN->getMaskElt(I + 1);
5508       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5509       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5510       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5511       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5512 
5513       SDValue Vec0 = SVN->getOperand(VecIdx0);
5514       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5515                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5516 
5517       SDValue Vec1 = SVN->getOperand(VecIdx1);
5518       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5519                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5520       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5521     }
5522   }
5523 
5524   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5525 }
5526 
5527 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5528                                             SelectionDAG &DAG) const {
5529   SDLoc SL(Op);
5530   EVT VT = Op.getValueType();
5531 
5532   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5533     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5534 
5535     // Turn into pair of packed build_vectors.
5536     // TODO: Special case for constants that can be materialized with s_mov_b64.
5537     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5538                                     { Op.getOperand(0), Op.getOperand(1) });
5539     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5540                                     { Op.getOperand(2), Op.getOperand(3) });
5541 
5542     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5543     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5544 
5545     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5546     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5547   }
5548 
5549   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5550   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5551 
5552   SDValue Lo = Op.getOperand(0);
5553   SDValue Hi = Op.getOperand(1);
5554 
5555   // Avoid adding defined bits with the zero_extend.
5556   if (Hi.isUndef()) {
5557     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5558     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5559     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5560   }
5561 
5562   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5563   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5564 
5565   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5566                               DAG.getConstant(16, SL, MVT::i32));
5567   if (Lo.isUndef())
5568     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5569 
5570   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5571   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5572 
5573   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5574   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5575 }
5576 
5577 bool
5578 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5579   // We can fold offsets for anything that doesn't require a GOT relocation.
5580   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5581           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5582           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5583          !shouldEmitGOTReloc(GA->getGlobal());
5584 }
5585 
5586 static SDValue
5587 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5588                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5589                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5590   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5591   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5592   // lowered to the following code sequence:
5593   //
5594   // For constant address space:
5595   //   s_getpc_b64 s[0:1]
5596   //   s_add_u32 s0, s0, $symbol
5597   //   s_addc_u32 s1, s1, 0
5598   //
5599   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5600   //   a fixup or relocation is emitted to replace $symbol with a literal
5601   //   constant, which is a pc-relative offset from the encoding of the $symbol
5602   //   operand to the global variable.
5603   //
5604   // For global address space:
5605   //   s_getpc_b64 s[0:1]
5606   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5607   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5608   //
5609   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5610   //   fixups or relocations are emitted to replace $symbol@*@lo and
5611   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5612   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5613   //   operand to the global variable.
5614   //
5615   // What we want here is an offset from the value returned by s_getpc
5616   // (which is the address of the s_add_u32 instruction) to the global
5617   // variable, but since the encoding of $symbol starts 4 bytes after the start
5618   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5619   // small. This requires us to add 4 to the global variable offset in order to
5620   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5621   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5622   // instruction.
5623   SDValue PtrLo =
5624       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5625   SDValue PtrHi;
5626   if (GAFlags == SIInstrInfo::MO_NONE) {
5627     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5628   } else {
5629     PtrHi =
5630         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5631   }
5632   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5633 }
5634 
5635 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5636                                              SDValue Op,
5637                                              SelectionDAG &DAG) const {
5638   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5639   SDLoc DL(GSD);
5640   EVT PtrVT = Op.getValueType();
5641 
5642   const GlobalValue *GV = GSD->getGlobal();
5643   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5644        shouldUseLDSConstAddress(GV)) ||
5645       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5646       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5647     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5648         GV->hasExternalLinkage()) {
5649       Type *Ty = GV->getValueType();
5650       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5651       // zero-sized type in other languages to declare the dynamic shared
5652       // memory which size is not known at the compile time. They will be
5653       // allocated by the runtime and placed directly after the static
5654       // allocated ones. They all share the same offset.
5655       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5656         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5657         // Adjust alignment for that dynamic shared memory array.
5658         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5659         return SDValue(
5660             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5661       }
5662     }
5663     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5664   }
5665 
5666   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5667     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5668                                             SIInstrInfo::MO_ABS32_LO);
5669     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5670   }
5671 
5672   if (shouldEmitFixup(GV))
5673     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5674   else if (shouldEmitPCReloc(GV))
5675     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5676                                    SIInstrInfo::MO_REL32);
5677 
5678   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5679                                             SIInstrInfo::MO_GOTPCREL32);
5680 
5681   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5682   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5683   const DataLayout &DataLayout = DAG.getDataLayout();
5684   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5685   MachinePointerInfo PtrInfo
5686     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5687 
5688   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5689                      MachineMemOperand::MODereferenceable |
5690                          MachineMemOperand::MOInvariant);
5691 }
5692 
5693 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5694                                    const SDLoc &DL, SDValue V) const {
5695   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5696   // the destination register.
5697   //
5698   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5699   // so we will end up with redundant moves to m0.
5700   //
5701   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5702 
5703   // A Null SDValue creates a glue result.
5704   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5705                                   V, Chain);
5706   return SDValue(M0, 0);
5707 }
5708 
5709 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5710                                                  SDValue Op,
5711                                                  MVT VT,
5712                                                  unsigned Offset) const {
5713   SDLoc SL(Op);
5714   SDValue Param = lowerKernargMemParameter(
5715       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5716   // The local size values will have the hi 16-bits as zero.
5717   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5718                      DAG.getValueType(VT));
5719 }
5720 
5721 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5722                                         EVT VT) {
5723   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5724                                       "non-hsa intrinsic with hsa target",
5725                                       DL.getDebugLoc());
5726   DAG.getContext()->diagnose(BadIntrin);
5727   return DAG.getUNDEF(VT);
5728 }
5729 
5730 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5731                                          EVT VT) {
5732   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5733                                       "intrinsic not supported on subtarget",
5734                                       DL.getDebugLoc());
5735   DAG.getContext()->diagnose(BadIntrin);
5736   return DAG.getUNDEF(VT);
5737 }
5738 
5739 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5740                                     ArrayRef<SDValue> Elts) {
5741   assert(!Elts.empty());
5742   MVT Type;
5743   unsigned NumElts;
5744 
5745   if (Elts.size() == 1) {
5746     Type = MVT::f32;
5747     NumElts = 1;
5748   } else if (Elts.size() == 2) {
5749     Type = MVT::v2f32;
5750     NumElts = 2;
5751   } else if (Elts.size() == 3) {
5752     Type = MVT::v3f32;
5753     NumElts = 3;
5754   } else if (Elts.size() <= 4) {
5755     Type = MVT::v4f32;
5756     NumElts = 4;
5757   } else if (Elts.size() <= 8) {
5758     Type = MVT::v8f32;
5759     NumElts = 8;
5760   } else {
5761     assert(Elts.size() <= 16);
5762     Type = MVT::v16f32;
5763     NumElts = 16;
5764   }
5765 
5766   SmallVector<SDValue, 16> VecElts(NumElts);
5767   for (unsigned i = 0; i < Elts.size(); ++i) {
5768     SDValue Elt = Elts[i];
5769     if (Elt.getValueType() != MVT::f32)
5770       Elt = DAG.getBitcast(MVT::f32, Elt);
5771     VecElts[i] = Elt;
5772   }
5773   for (unsigned i = Elts.size(); i < NumElts; ++i)
5774     VecElts[i] = DAG.getUNDEF(MVT::f32);
5775 
5776   if (NumElts == 1)
5777     return VecElts[0];
5778   return DAG.getBuildVector(Type, DL, VecElts);
5779 }
5780 
5781 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5782                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5783   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5784 
5785   uint64_t Value = CachePolicyConst->getZExtValue();
5786   SDLoc DL(CachePolicy);
5787   if (GLC) {
5788     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5789     Value &= ~(uint64_t)0x1;
5790   }
5791   if (SLC) {
5792     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5793     Value &= ~(uint64_t)0x2;
5794   }
5795   if (DLC) {
5796     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5797     Value &= ~(uint64_t)0x4;
5798   }
5799 
5800   return Value == 0;
5801 }
5802 
5803 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5804                               SDValue Src, int ExtraElts) {
5805   EVT SrcVT = Src.getValueType();
5806 
5807   SmallVector<SDValue, 8> Elts;
5808 
5809   if (SrcVT.isVector())
5810     DAG.ExtractVectorElements(Src, Elts);
5811   else
5812     Elts.push_back(Src);
5813 
5814   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5815   while (ExtraElts--)
5816     Elts.push_back(Undef);
5817 
5818   return DAG.getBuildVector(CastVT, DL, Elts);
5819 }
5820 
5821 // Re-construct the required return value for a image load intrinsic.
5822 // This is more complicated due to the optional use TexFailCtrl which means the required
5823 // return type is an aggregate
5824 static SDValue constructRetValue(SelectionDAG &DAG,
5825                                  MachineSDNode *Result,
5826                                  ArrayRef<EVT> ResultTypes,
5827                                  bool IsTexFail, bool Unpacked, bool IsD16,
5828                                  int DMaskPop, int NumVDataDwords,
5829                                  const SDLoc &DL, LLVMContext &Context) {
5830   // Determine the required return type. This is the same regardless of IsTexFail flag
5831   EVT ReqRetVT = ResultTypes[0];
5832   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5833   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5834     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5835 
5836   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5837     DMaskPop : (DMaskPop + 1) / 2;
5838 
5839   MVT DataDwordVT = NumDataDwords == 1 ?
5840     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5841 
5842   MVT MaskPopVT = MaskPopDwords == 1 ?
5843     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5844 
5845   SDValue Data(Result, 0);
5846   SDValue TexFail;
5847 
5848   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5849     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5850     if (MaskPopVT.isVector()) {
5851       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5852                          SDValue(Result, 0), ZeroIdx);
5853     } else {
5854       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5855                          SDValue(Result, 0), ZeroIdx);
5856     }
5857   }
5858 
5859   if (DataDwordVT.isVector())
5860     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5861                           NumDataDwords - MaskPopDwords);
5862 
5863   if (IsD16)
5864     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5865 
5866   EVT LegalReqRetVT = ReqRetVT;
5867   if (!ReqRetVT.isVector()) {
5868     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5869   } else {
5870     // We need to widen the return vector to a legal type
5871     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5872         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5873       LegalReqRetVT =
5874           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5875                            ReqRetVT.getVectorNumElements() + 1);
5876     }
5877   }
5878   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5879 
5880   if (IsTexFail) {
5881     TexFail =
5882         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5883                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5884 
5885     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5886   }
5887 
5888   if (Result->getNumValues() == 1)
5889     return Data;
5890 
5891   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5892 }
5893 
5894 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5895                          SDValue *LWE, bool &IsTexFail) {
5896   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5897 
5898   uint64_t Value = TexFailCtrlConst->getZExtValue();
5899   if (Value) {
5900     IsTexFail = true;
5901   }
5902 
5903   SDLoc DL(TexFailCtrlConst);
5904   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5905   Value &= ~(uint64_t)0x1;
5906   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5907   Value &= ~(uint64_t)0x2;
5908 
5909   return Value == 0;
5910 }
5911 
5912 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5913                                         MVT PackVectorVT,
5914                                         SmallVectorImpl<SDValue> &PackedAddrs,
5915                                         unsigned DimIdx, unsigned EndIdx,
5916                                         unsigned NumGradients) {
5917   SDLoc DL(Op);
5918   for (unsigned I = DimIdx; I < EndIdx; I++) {
5919     SDValue Addr = Op.getOperand(I);
5920 
5921     // Gradients are packed with undef for each coordinate.
5922     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5923     // 1D: undef,dx/dh; undef,dx/dv
5924     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5925     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5926     if (((I + 1) >= EndIdx) ||
5927         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5928                                          I == DimIdx + NumGradients - 1))) {
5929       if (Addr.getValueType() != MVT::i16)
5930         Addr = DAG.getBitcast(MVT::i16, Addr);
5931       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5932     } else {
5933       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5934       I++;
5935     }
5936     Addr = DAG.getBitcast(MVT::f32, Addr);
5937     PackedAddrs.push_back(Addr);
5938   }
5939 }
5940 
5941 SDValue SITargetLowering::lowerImage(SDValue Op,
5942                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5943                                      SelectionDAG &DAG, bool WithChain) const {
5944   SDLoc DL(Op);
5945   MachineFunction &MF = DAG.getMachineFunction();
5946   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5947   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5948       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5949   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5950   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5951       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5952   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5953       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5954   unsigned IntrOpcode = Intr->BaseOpcode;
5955   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5956 
5957   SmallVector<EVT, 3> ResultTypes(Op->values());
5958   SmallVector<EVT, 3> OrigResultTypes(Op->values());
5959   bool IsD16 = false;
5960   bool IsG16 = false;
5961   bool IsA16 = false;
5962   SDValue VData;
5963   int NumVDataDwords;
5964   bool AdjustRetType = false;
5965 
5966   // Offset of intrinsic arguments
5967   const unsigned ArgOffset = WithChain ? 2 : 1;
5968 
5969   unsigned DMask;
5970   unsigned DMaskLanes = 0;
5971 
5972   if (BaseOpcode->Atomic) {
5973     VData = Op.getOperand(2);
5974 
5975     bool Is64Bit = VData.getValueType() == MVT::i64;
5976     if (BaseOpcode->AtomicX2) {
5977       SDValue VData2 = Op.getOperand(3);
5978       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5979                                  {VData, VData2});
5980       if (Is64Bit)
5981         VData = DAG.getBitcast(MVT::v4i32, VData);
5982 
5983       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5984       DMask = Is64Bit ? 0xf : 0x3;
5985       NumVDataDwords = Is64Bit ? 4 : 2;
5986     } else {
5987       DMask = Is64Bit ? 0x3 : 0x1;
5988       NumVDataDwords = Is64Bit ? 2 : 1;
5989     }
5990   } else {
5991     auto *DMaskConst =
5992         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
5993     DMask = DMaskConst->getZExtValue();
5994     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5995 
5996     if (BaseOpcode->Store) {
5997       VData = Op.getOperand(2);
5998 
5999       MVT StoreVT = VData.getSimpleValueType();
6000       if (StoreVT.getScalarType() == MVT::f16) {
6001         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6002           return Op; // D16 is unsupported for this instruction
6003 
6004         IsD16 = true;
6005         VData = handleD16VData(VData, DAG, true);
6006       }
6007 
6008       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6009     } else {
6010       // Work out the num dwords based on the dmask popcount and underlying type
6011       // and whether packing is supported.
6012       MVT LoadVT = ResultTypes[0].getSimpleVT();
6013       if (LoadVT.getScalarType() == MVT::f16) {
6014         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6015           return Op; // D16 is unsupported for this instruction
6016 
6017         IsD16 = true;
6018       }
6019 
6020       // Confirm that the return type is large enough for the dmask specified
6021       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6022           (!LoadVT.isVector() && DMaskLanes > 1))
6023           return Op;
6024 
6025       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6026       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6027       // instructions.
6028       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6029           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6030         NumVDataDwords = (DMaskLanes + 1) / 2;
6031       else
6032         NumVDataDwords = DMaskLanes;
6033 
6034       AdjustRetType = true;
6035     }
6036   }
6037 
6038   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6039   SmallVector<SDValue, 4> VAddrs;
6040 
6041   // Optimize _L to _LZ when _L is zero
6042   if (LZMappingInfo) {
6043     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6044             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6045       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6046         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6047         VAddrEnd--;                      // remove 'lod'
6048       }
6049     }
6050   }
6051 
6052   // Optimize _mip away, when 'lod' is zero
6053   if (MIPMappingInfo) {
6054     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6055             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6056       if (ConstantLod->isNullValue()) {
6057         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6058         VAddrEnd--;                           // remove 'mip'
6059       }
6060     }
6061   }
6062 
6063   // Push back extra arguments.
6064   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6065     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6066 
6067   // Check for 16 bit addresses or derivatives and pack if true.
6068   MVT VAddrVT =
6069       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6070   MVT VAddrScalarVT = VAddrVT.getScalarType();
6071   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6072   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6073 
6074   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6075   VAddrScalarVT = VAddrVT.getScalarType();
6076   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6077   if (IsA16 || IsG16) {
6078     if (IsA16) {
6079       if (!ST->hasA16()) {
6080         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6081                              "support 16 bit addresses\n");
6082         return Op;
6083       }
6084       if (!IsG16) {
6085         LLVM_DEBUG(
6086             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6087                       "need 16 bit derivatives but got 32 bit derivatives\n");
6088         return Op;
6089       }
6090     } else if (!ST->hasG16()) {
6091       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6092                            "support 16 bit derivatives\n");
6093       return Op;
6094     }
6095 
6096     if (BaseOpcode->Gradients && !IsA16) {
6097       if (!ST->hasG16()) {
6098         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6099                              "support 16 bit derivatives\n");
6100         return Op;
6101       }
6102       // Activate g16
6103       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6104           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6105       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6106     }
6107 
6108     // Don't compress addresses for G16
6109     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6110     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6111                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6112                                 Intr->NumGradients);
6113 
6114     if (!IsA16) {
6115       // Add uncompressed address
6116       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6117         VAddrs.push_back(Op.getOperand(I));
6118     }
6119   } else {
6120     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6121       VAddrs.push_back(Op.getOperand(I));
6122   }
6123 
6124   // If the register allocator cannot place the address registers contiguously
6125   // without introducing moves, then using the non-sequential address encoding
6126   // is always preferable, since it saves VALU instructions and is usually a
6127   // wash in terms of code size or even better.
6128   //
6129   // However, we currently have no way of hinting to the register allocator that
6130   // MIMG addresses should be placed contiguously when it is possible to do so,
6131   // so force non-NSA for the common 2-address case as a heuristic.
6132   //
6133   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6134   // allocation when possible.
6135   bool UseNSA =
6136       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6137   SDValue VAddr;
6138   if (!UseNSA)
6139     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6140 
6141   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6142   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6143   SDValue Unorm;
6144   if (!BaseOpcode->Sampler) {
6145     Unorm = True;
6146   } else {
6147     auto UnormConst =
6148         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6149 
6150     Unorm = UnormConst->getZExtValue() ? True : False;
6151   }
6152 
6153   SDValue TFE;
6154   SDValue LWE;
6155   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6156   bool IsTexFail = false;
6157   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6158     return Op;
6159 
6160   if (IsTexFail) {
6161     if (!DMaskLanes) {
6162       // Expecting to get an error flag since TFC is on - and dmask is 0
6163       // Force dmask to be at least 1 otherwise the instruction will fail
6164       DMask = 0x1;
6165       DMaskLanes = 1;
6166       NumVDataDwords = 1;
6167     }
6168     NumVDataDwords += 1;
6169     AdjustRetType = true;
6170   }
6171 
6172   // Has something earlier tagged that the return type needs adjusting
6173   // This happens if the instruction is a load or has set TexFailCtrl flags
6174   if (AdjustRetType) {
6175     // NumVDataDwords reflects the true number of dwords required in the return type
6176     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6177       // This is a no-op load. This can be eliminated
6178       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6179       if (isa<MemSDNode>(Op))
6180         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6181       return Undef;
6182     }
6183 
6184     EVT NewVT = NumVDataDwords > 1 ?
6185                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6186                 : MVT::i32;
6187 
6188     ResultTypes[0] = NewVT;
6189     if (ResultTypes.size() == 3) {
6190       // Original result was aggregate type used for TexFailCtrl results
6191       // The actual instruction returns as a vector type which has now been
6192       // created. Remove the aggregate result.
6193       ResultTypes.erase(&ResultTypes[1]);
6194     }
6195   }
6196 
6197   SDValue GLC;
6198   SDValue SLC;
6199   SDValue DLC;
6200   if (BaseOpcode->Atomic) {
6201     GLC = True; // TODO no-return optimization
6202     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6203                           DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr))
6204       return Op;
6205   } else {
6206     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6207                           DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr))
6208       return Op;
6209   }
6210 
6211   SmallVector<SDValue, 26> Ops;
6212   if (BaseOpcode->Store || BaseOpcode->Atomic)
6213     Ops.push_back(VData); // vdata
6214   if (UseNSA) {
6215     for (const SDValue &Addr : VAddrs)
6216       Ops.push_back(Addr);
6217   } else {
6218     Ops.push_back(VAddr);
6219   }
6220   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6221   if (BaseOpcode->Sampler)
6222     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6223   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6224   if (IsGFX10Plus)
6225     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6226   Ops.push_back(Unorm);
6227   if (IsGFX10Plus)
6228     Ops.push_back(DLC);
6229   Ops.push_back(GLC);
6230   Ops.push_back(SLC);
6231   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6232                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6233   if (IsGFX10Plus)
6234     Ops.push_back(IsA16 ? True : False);
6235   Ops.push_back(TFE);
6236   Ops.push_back(LWE);
6237   if (!IsGFX10Plus)
6238     Ops.push_back(DimInfo->DA ? True : False);
6239   if (BaseOpcode->HasD16)
6240     Ops.push_back(IsD16 ? True : False);
6241   if (isa<MemSDNode>(Op))
6242     Ops.push_back(Op.getOperand(0)); // chain
6243 
6244   int NumVAddrDwords =
6245       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6246   int Opcode = -1;
6247 
6248   if (IsGFX10Plus) {
6249     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6250                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6251                                           : AMDGPU::MIMGEncGfx10Default,
6252                                    NumVDataDwords, NumVAddrDwords);
6253   } else {
6254     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6255       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6256                                      NumVDataDwords, NumVAddrDwords);
6257     if (Opcode == -1)
6258       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6259                                      NumVDataDwords, NumVAddrDwords);
6260   }
6261   assert(Opcode != -1);
6262 
6263   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6264   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6265     MachineMemOperand *MemRef = MemOp->getMemOperand();
6266     DAG.setNodeMemRefs(NewNode, {MemRef});
6267   }
6268 
6269   if (BaseOpcode->AtomicX2) {
6270     SmallVector<SDValue, 1> Elt;
6271     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6272     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6273   } else if (!BaseOpcode->Store) {
6274     return constructRetValue(DAG, NewNode,
6275                              OrigResultTypes, IsTexFail,
6276                              Subtarget->hasUnpackedD16VMem(), IsD16,
6277                              DMaskLanes, NumVDataDwords, DL,
6278                              *DAG.getContext());
6279   }
6280 
6281   return SDValue(NewNode, 0);
6282 }
6283 
6284 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6285                                        SDValue Offset, SDValue CachePolicy,
6286                                        SelectionDAG &DAG) const {
6287   MachineFunction &MF = DAG.getMachineFunction();
6288 
6289   const DataLayout &DataLayout = DAG.getDataLayout();
6290   Align Alignment =
6291       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6292 
6293   MachineMemOperand *MMO = MF.getMachineMemOperand(
6294       MachinePointerInfo(),
6295       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6296           MachineMemOperand::MOInvariant,
6297       VT.getStoreSize(), Alignment);
6298 
6299   if (!Offset->isDivergent()) {
6300     SDValue Ops[] = {
6301         Rsrc,
6302         Offset, // Offset
6303         CachePolicy
6304     };
6305 
6306     // Widen vec3 load to vec4.
6307     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6308       EVT WidenedVT =
6309           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6310       auto WidenedOp = DAG.getMemIntrinsicNode(
6311           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6312           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6313       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6314                                    DAG.getVectorIdxConstant(0, DL));
6315       return Subvector;
6316     }
6317 
6318     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6319                                    DAG.getVTList(VT), Ops, VT, MMO);
6320   }
6321 
6322   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6323   // assume that the buffer is unswizzled.
6324   SmallVector<SDValue, 4> Loads;
6325   unsigned NumLoads = 1;
6326   MVT LoadVT = VT.getSimpleVT();
6327   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6328   assert((LoadVT.getScalarType() == MVT::i32 ||
6329           LoadVT.getScalarType() == MVT::f32));
6330 
6331   if (NumElts == 8 || NumElts == 16) {
6332     NumLoads = NumElts / 4;
6333     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6334   }
6335 
6336   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6337   SDValue Ops[] = {
6338       DAG.getEntryNode(),                               // Chain
6339       Rsrc,                                             // rsrc
6340       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6341       {},                                               // voffset
6342       {},                                               // soffset
6343       {},                                               // offset
6344       CachePolicy,                                      // cachepolicy
6345       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6346   };
6347 
6348   // Use the alignment to ensure that the required offsets will fit into the
6349   // immediate offsets.
6350   setBufferOffsets(Offset, DAG, &Ops[3],
6351                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6352 
6353   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6354   for (unsigned i = 0; i < NumLoads; ++i) {
6355     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6356     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6357                                         LoadVT, MMO, DAG));
6358   }
6359 
6360   if (NumElts == 8 || NumElts == 16)
6361     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6362 
6363   return Loads[0];
6364 }
6365 
6366 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6367                                                   SelectionDAG &DAG) const {
6368   MachineFunction &MF = DAG.getMachineFunction();
6369   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6370 
6371   EVT VT = Op.getValueType();
6372   SDLoc DL(Op);
6373   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6374 
6375   // TODO: Should this propagate fast-math-flags?
6376 
6377   switch (IntrinsicID) {
6378   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6379     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6380       return emitNonHSAIntrinsicError(DAG, DL, VT);
6381     return getPreloadedValue(DAG, *MFI, VT,
6382                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6383   }
6384   case Intrinsic::amdgcn_dispatch_ptr:
6385   case Intrinsic::amdgcn_queue_ptr: {
6386     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6387       DiagnosticInfoUnsupported BadIntrin(
6388           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6389           DL.getDebugLoc());
6390       DAG.getContext()->diagnose(BadIntrin);
6391       return DAG.getUNDEF(VT);
6392     }
6393 
6394     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6395       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6396     return getPreloadedValue(DAG, *MFI, VT, RegID);
6397   }
6398   case Intrinsic::amdgcn_implicitarg_ptr: {
6399     if (MFI->isEntryFunction())
6400       return getImplicitArgPtr(DAG, DL);
6401     return getPreloadedValue(DAG, *MFI, VT,
6402                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6403   }
6404   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6405     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6406       // This only makes sense to call in a kernel, so just lower to null.
6407       return DAG.getConstant(0, DL, VT);
6408     }
6409 
6410     return getPreloadedValue(DAG, *MFI, VT,
6411                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6412   }
6413   case Intrinsic::amdgcn_dispatch_id: {
6414     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6415   }
6416   case Intrinsic::amdgcn_rcp:
6417     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6418   case Intrinsic::amdgcn_rsq:
6419     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6420   case Intrinsic::amdgcn_rsq_legacy:
6421     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6422       return emitRemovedIntrinsicError(DAG, DL, VT);
6423     return SDValue();
6424   case Intrinsic::amdgcn_rcp_legacy:
6425     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6426       return emitRemovedIntrinsicError(DAG, DL, VT);
6427     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6428   case Intrinsic::amdgcn_rsq_clamp: {
6429     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6430       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6431 
6432     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6433     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6434     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6435 
6436     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6437     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6438                               DAG.getConstantFP(Max, DL, VT));
6439     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6440                        DAG.getConstantFP(Min, DL, VT));
6441   }
6442   case Intrinsic::r600_read_ngroups_x:
6443     if (Subtarget->isAmdHsaOS())
6444       return emitNonHSAIntrinsicError(DAG, DL, VT);
6445 
6446     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6447                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6448                                     false);
6449   case Intrinsic::r600_read_ngroups_y:
6450     if (Subtarget->isAmdHsaOS())
6451       return emitNonHSAIntrinsicError(DAG, DL, VT);
6452 
6453     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6454                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6455                                     false);
6456   case Intrinsic::r600_read_ngroups_z:
6457     if (Subtarget->isAmdHsaOS())
6458       return emitNonHSAIntrinsicError(DAG, DL, VT);
6459 
6460     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6461                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6462                                     false);
6463   case Intrinsic::r600_read_global_size_x:
6464     if (Subtarget->isAmdHsaOS())
6465       return emitNonHSAIntrinsicError(DAG, DL, VT);
6466 
6467     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6468                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6469                                     Align(4), false);
6470   case Intrinsic::r600_read_global_size_y:
6471     if (Subtarget->isAmdHsaOS())
6472       return emitNonHSAIntrinsicError(DAG, DL, VT);
6473 
6474     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6475                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6476                                     Align(4), false);
6477   case Intrinsic::r600_read_global_size_z:
6478     if (Subtarget->isAmdHsaOS())
6479       return emitNonHSAIntrinsicError(DAG, DL, VT);
6480 
6481     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6482                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6483                                     Align(4), false);
6484   case Intrinsic::r600_read_local_size_x:
6485     if (Subtarget->isAmdHsaOS())
6486       return emitNonHSAIntrinsicError(DAG, DL, VT);
6487 
6488     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6489                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6490   case Intrinsic::r600_read_local_size_y:
6491     if (Subtarget->isAmdHsaOS())
6492       return emitNonHSAIntrinsicError(DAG, DL, VT);
6493 
6494     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6495                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6496   case Intrinsic::r600_read_local_size_z:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6501                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6502   case Intrinsic::amdgcn_workgroup_id_x:
6503     return getPreloadedValue(DAG, *MFI, VT,
6504                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6505   case Intrinsic::amdgcn_workgroup_id_y:
6506     return getPreloadedValue(DAG, *MFI, VT,
6507                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6508   case Intrinsic::amdgcn_workgroup_id_z:
6509     return getPreloadedValue(DAG, *MFI, VT,
6510                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6511   case Intrinsic::amdgcn_workitem_id_x:
6512     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6513                           SDLoc(DAG.getEntryNode()),
6514                           MFI->getArgInfo().WorkItemIDX);
6515   case Intrinsic::amdgcn_workitem_id_y:
6516     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6517                           SDLoc(DAG.getEntryNode()),
6518                           MFI->getArgInfo().WorkItemIDY);
6519   case Intrinsic::amdgcn_workitem_id_z:
6520     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6521                           SDLoc(DAG.getEntryNode()),
6522                           MFI->getArgInfo().WorkItemIDZ);
6523   case Intrinsic::amdgcn_wavefrontsize:
6524     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6525                            SDLoc(Op), MVT::i32);
6526   case Intrinsic::amdgcn_s_buffer_load: {
6527     bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6528     SDValue GLC;
6529     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6530     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6531                           IsGFX10Plus ? &DLC : nullptr))
6532       return Op;
6533     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6534                         DAG);
6535   }
6536   case Intrinsic::amdgcn_fdiv_fast:
6537     return lowerFDIV_FAST(Op, DAG);
6538   case Intrinsic::amdgcn_sin:
6539     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6540 
6541   case Intrinsic::amdgcn_cos:
6542     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6543 
6544   case Intrinsic::amdgcn_mul_u24:
6545     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6546   case Intrinsic::amdgcn_mul_i24:
6547     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6548 
6549   case Intrinsic::amdgcn_log_clamp: {
6550     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6551       return SDValue();
6552 
6553     return emitRemovedIntrinsicError(DAG, DL, VT);
6554   }
6555   case Intrinsic::amdgcn_ldexp:
6556     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6557                        Op.getOperand(1), Op.getOperand(2));
6558 
6559   case Intrinsic::amdgcn_fract:
6560     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6561 
6562   case Intrinsic::amdgcn_class:
6563     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6564                        Op.getOperand(1), Op.getOperand(2));
6565   case Intrinsic::amdgcn_div_fmas:
6566     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6567                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6568                        Op.getOperand(4));
6569 
6570   case Intrinsic::amdgcn_div_fixup:
6571     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6572                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6573 
6574   case Intrinsic::amdgcn_div_scale: {
6575     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6576 
6577     // Translate to the operands expected by the machine instruction. The
6578     // first parameter must be the same as the first instruction.
6579     SDValue Numerator = Op.getOperand(1);
6580     SDValue Denominator = Op.getOperand(2);
6581 
6582     // Note this order is opposite of the machine instruction's operations,
6583     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6584     // intrinsic has the numerator as the first operand to match a normal
6585     // division operation.
6586 
6587     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6588 
6589     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6590                        Denominator, Numerator);
6591   }
6592   case Intrinsic::amdgcn_icmp: {
6593     // There is a Pat that handles this variant, so return it as-is.
6594     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6595         Op.getConstantOperandVal(2) == 0 &&
6596         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6597       return Op;
6598     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6599   }
6600   case Intrinsic::amdgcn_fcmp: {
6601     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6602   }
6603   case Intrinsic::amdgcn_ballot:
6604     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6605   case Intrinsic::amdgcn_fmed3:
6606     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6607                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6608   case Intrinsic::amdgcn_fdot2:
6609     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6610                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6611                        Op.getOperand(4));
6612   case Intrinsic::amdgcn_fmul_legacy:
6613     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6614                        Op.getOperand(1), Op.getOperand(2));
6615   case Intrinsic::amdgcn_sffbh:
6616     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6617   case Intrinsic::amdgcn_sbfe:
6618     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6619                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6620   case Intrinsic::amdgcn_ubfe:
6621     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6622                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6623   case Intrinsic::amdgcn_cvt_pkrtz:
6624   case Intrinsic::amdgcn_cvt_pknorm_i16:
6625   case Intrinsic::amdgcn_cvt_pknorm_u16:
6626   case Intrinsic::amdgcn_cvt_pk_i16:
6627   case Intrinsic::amdgcn_cvt_pk_u16: {
6628     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6629     EVT VT = Op.getValueType();
6630     unsigned Opcode;
6631 
6632     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6633       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6634     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6635       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6636     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6637       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6638     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6639       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6640     else
6641       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6642 
6643     if (isTypeLegal(VT))
6644       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6645 
6646     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6647                                Op.getOperand(1), Op.getOperand(2));
6648     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6649   }
6650   case Intrinsic::amdgcn_fmad_ftz:
6651     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6652                        Op.getOperand(2), Op.getOperand(3));
6653 
6654   case Intrinsic::amdgcn_if_break:
6655     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6656                                       Op->getOperand(1), Op->getOperand(2)), 0);
6657 
6658   case Intrinsic::amdgcn_groupstaticsize: {
6659     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6660     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6661       return Op;
6662 
6663     const Module *M = MF.getFunction().getParent();
6664     const GlobalValue *GV =
6665         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6666     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6667                                             SIInstrInfo::MO_ABS32_LO);
6668     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6669   }
6670   case Intrinsic::amdgcn_is_shared:
6671   case Intrinsic::amdgcn_is_private: {
6672     SDLoc SL(Op);
6673     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6674       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6675     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6676     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6677                                  Op.getOperand(1));
6678 
6679     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6680                                 DAG.getConstant(1, SL, MVT::i32));
6681     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6682   }
6683   case Intrinsic::amdgcn_alignbit:
6684     return DAG.getNode(ISD::FSHR, DL, VT,
6685                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6686   case Intrinsic::amdgcn_reloc_constant: {
6687     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6688     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6689     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6690     auto RelocSymbol = cast<GlobalVariable>(
6691         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6692     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6693                                             SIInstrInfo::MO_ABS32_LO);
6694     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6695   }
6696   default:
6697     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6698             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6699       return lowerImage(Op, ImageDimIntr, DAG, false);
6700 
6701     return Op;
6702   }
6703 }
6704 
6705 // This function computes an appropriate offset to pass to
6706 // MachineMemOperand::setOffset() based on the offset inputs to
6707 // an intrinsic.  If any of the offsets are non-contstant or
6708 // if VIndex is non-zero then this function returns 0.  Otherwise,
6709 // it returns the sum of VOffset, SOffset, and Offset.
6710 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6711                                       SDValue SOffset,
6712                                       SDValue Offset,
6713                                       SDValue VIndex = SDValue()) {
6714 
6715   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6716       !isa<ConstantSDNode>(Offset))
6717     return 0;
6718 
6719   if (VIndex) {
6720     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6721       return 0;
6722   }
6723 
6724   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6725          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6726          cast<ConstantSDNode>(Offset)->getSExtValue();
6727 }
6728 
6729 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6730                                                      SelectionDAG &DAG,
6731                                                      unsigned NewOpcode) const {
6732   SDLoc DL(Op);
6733 
6734   SDValue VData = Op.getOperand(2);
6735   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6736   SDValue Ops[] = {
6737     Op.getOperand(0), // Chain
6738     VData,            // vdata
6739     Op.getOperand(3), // rsrc
6740     DAG.getConstant(0, DL, MVT::i32), // vindex
6741     Offsets.first,    // voffset
6742     Op.getOperand(5), // soffset
6743     Offsets.second,   // offset
6744     Op.getOperand(6), // cachepolicy
6745     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6746   };
6747 
6748   auto *M = cast<MemSDNode>(Op);
6749   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6750 
6751   EVT MemVT = VData.getValueType();
6752   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6753                                  M->getMemOperand());
6754 }
6755 
6756 SDValue
6757 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6758                                                 unsigned NewOpcode) const {
6759   SDLoc DL(Op);
6760 
6761   SDValue VData = Op.getOperand(2);
6762   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6763   SDValue Ops[] = {
6764     Op.getOperand(0), // Chain
6765     VData,            // vdata
6766     Op.getOperand(3), // rsrc
6767     Op.getOperand(4), // vindex
6768     Offsets.first,    // voffset
6769     Op.getOperand(6), // soffset
6770     Offsets.second,   // offset
6771     Op.getOperand(7), // cachepolicy
6772     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6773   };
6774 
6775   auto *M = cast<MemSDNode>(Op);
6776   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6777                                                       Ops[3]));
6778 
6779   EVT MemVT = VData.getValueType();
6780   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6781                                  M->getMemOperand());
6782 }
6783 
6784 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6785                                                  SelectionDAG &DAG) const {
6786   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6787   SDLoc DL(Op);
6788 
6789   switch (IntrID) {
6790   case Intrinsic::amdgcn_ds_ordered_add:
6791   case Intrinsic::amdgcn_ds_ordered_swap: {
6792     MemSDNode *M = cast<MemSDNode>(Op);
6793     SDValue Chain = M->getOperand(0);
6794     SDValue M0 = M->getOperand(2);
6795     SDValue Value = M->getOperand(3);
6796     unsigned IndexOperand = M->getConstantOperandVal(7);
6797     unsigned WaveRelease = M->getConstantOperandVal(8);
6798     unsigned WaveDone = M->getConstantOperandVal(9);
6799 
6800     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6801     IndexOperand &= ~0x3f;
6802     unsigned CountDw = 0;
6803 
6804     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6805       CountDw = (IndexOperand >> 24) & 0xf;
6806       IndexOperand &= ~(0xf << 24);
6807 
6808       if (CountDw < 1 || CountDw > 4) {
6809         report_fatal_error(
6810             "ds_ordered_count: dword count must be between 1 and 4");
6811       }
6812     }
6813 
6814     if (IndexOperand)
6815       report_fatal_error("ds_ordered_count: bad index operand");
6816 
6817     if (WaveDone && !WaveRelease)
6818       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6819 
6820     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6821     unsigned ShaderType =
6822         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6823     unsigned Offset0 = OrderedCountIndex << 2;
6824     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6825                        (Instruction << 4);
6826 
6827     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6828       Offset1 |= (CountDw - 1) << 6;
6829 
6830     unsigned Offset = Offset0 | (Offset1 << 8);
6831 
6832     SDValue Ops[] = {
6833       Chain,
6834       Value,
6835       DAG.getTargetConstant(Offset, DL, MVT::i16),
6836       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6837     };
6838     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6839                                    M->getVTList(), Ops, M->getMemoryVT(),
6840                                    M->getMemOperand());
6841   }
6842   case Intrinsic::amdgcn_ds_fadd: {
6843     MemSDNode *M = cast<MemSDNode>(Op);
6844     unsigned Opc;
6845     switch (IntrID) {
6846     case Intrinsic::amdgcn_ds_fadd:
6847       Opc = ISD::ATOMIC_LOAD_FADD;
6848       break;
6849     }
6850 
6851     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6852                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6853                          M->getMemOperand());
6854   }
6855   case Intrinsic::amdgcn_atomic_inc:
6856   case Intrinsic::amdgcn_atomic_dec:
6857   case Intrinsic::amdgcn_ds_fmin:
6858   case Intrinsic::amdgcn_ds_fmax: {
6859     MemSDNode *M = cast<MemSDNode>(Op);
6860     unsigned Opc;
6861     switch (IntrID) {
6862     case Intrinsic::amdgcn_atomic_inc:
6863       Opc = AMDGPUISD::ATOMIC_INC;
6864       break;
6865     case Intrinsic::amdgcn_atomic_dec:
6866       Opc = AMDGPUISD::ATOMIC_DEC;
6867       break;
6868     case Intrinsic::amdgcn_ds_fmin:
6869       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6870       break;
6871     case Intrinsic::amdgcn_ds_fmax:
6872       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6873       break;
6874     default:
6875       llvm_unreachable("Unknown intrinsic!");
6876     }
6877     SDValue Ops[] = {
6878       M->getOperand(0), // Chain
6879       M->getOperand(2), // Ptr
6880       M->getOperand(3)  // Value
6881     };
6882 
6883     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6884                                    M->getMemoryVT(), M->getMemOperand());
6885   }
6886   case Intrinsic::amdgcn_buffer_load:
6887   case Intrinsic::amdgcn_buffer_load_format: {
6888     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6889     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6890     unsigned IdxEn = 1;
6891     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6892       IdxEn = Idx->getZExtValue() != 0;
6893     SDValue Ops[] = {
6894       Op.getOperand(0), // Chain
6895       Op.getOperand(2), // rsrc
6896       Op.getOperand(3), // vindex
6897       SDValue(),        // voffset -- will be set by setBufferOffsets
6898       SDValue(),        // soffset -- will be set by setBufferOffsets
6899       SDValue(),        // offset -- will be set by setBufferOffsets
6900       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6901       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6902     };
6903 
6904     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6905     // We don't know the offset if vindex is non-zero, so clear it.
6906     if (IdxEn)
6907       Offset = 0;
6908 
6909     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6910         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6911 
6912     EVT VT = Op.getValueType();
6913     EVT IntVT = VT.changeTypeToInteger();
6914     auto *M = cast<MemSDNode>(Op);
6915     M->getMemOperand()->setOffset(Offset);
6916     EVT LoadVT = Op.getValueType();
6917 
6918     if (LoadVT.getScalarType() == MVT::f16)
6919       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6920                                  M, DAG, Ops);
6921 
6922     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6923     if (LoadVT.getScalarType() == MVT::i8 ||
6924         LoadVT.getScalarType() == MVT::i16)
6925       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6926 
6927     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6928                                M->getMemOperand(), DAG);
6929   }
6930   case Intrinsic::amdgcn_raw_buffer_load:
6931   case Intrinsic::amdgcn_raw_buffer_load_format: {
6932     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6933 
6934     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6935     SDValue Ops[] = {
6936       Op.getOperand(0), // Chain
6937       Op.getOperand(2), // rsrc
6938       DAG.getConstant(0, DL, MVT::i32), // vindex
6939       Offsets.first,    // voffset
6940       Op.getOperand(4), // soffset
6941       Offsets.second,   // offset
6942       Op.getOperand(5), // cachepolicy, swizzled buffer
6943       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6944     };
6945 
6946     auto *M = cast<MemSDNode>(Op);
6947     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6948     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6949   }
6950   case Intrinsic::amdgcn_struct_buffer_load:
6951   case Intrinsic::amdgcn_struct_buffer_load_format: {
6952     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6953 
6954     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6955     SDValue Ops[] = {
6956       Op.getOperand(0), // Chain
6957       Op.getOperand(2), // rsrc
6958       Op.getOperand(3), // vindex
6959       Offsets.first,    // voffset
6960       Op.getOperand(5), // soffset
6961       Offsets.second,   // offset
6962       Op.getOperand(6), // cachepolicy, swizzled buffer
6963       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6964     };
6965 
6966     auto *M = cast<MemSDNode>(Op);
6967     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6968                                                         Ops[2]));
6969     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6970   }
6971   case Intrinsic::amdgcn_tbuffer_load: {
6972     MemSDNode *M = cast<MemSDNode>(Op);
6973     EVT LoadVT = Op.getValueType();
6974 
6975     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6976     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6977     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6978     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6979     unsigned IdxEn = 1;
6980     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6981       IdxEn = Idx->getZExtValue() != 0;
6982     SDValue Ops[] = {
6983       Op.getOperand(0),  // Chain
6984       Op.getOperand(2),  // rsrc
6985       Op.getOperand(3),  // vindex
6986       Op.getOperand(4),  // voffset
6987       Op.getOperand(5),  // soffset
6988       Op.getOperand(6),  // offset
6989       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6990       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6991       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6992     };
6993 
6994     if (LoadVT.getScalarType() == MVT::f16)
6995       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6996                                  M, DAG, Ops);
6997     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6998                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6999                                DAG);
7000   }
7001   case Intrinsic::amdgcn_raw_tbuffer_load: {
7002     MemSDNode *M = cast<MemSDNode>(Op);
7003     EVT LoadVT = Op.getValueType();
7004     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7005 
7006     SDValue Ops[] = {
7007       Op.getOperand(0),  // Chain
7008       Op.getOperand(2),  // rsrc
7009       DAG.getConstant(0, DL, MVT::i32), // vindex
7010       Offsets.first,     // voffset
7011       Op.getOperand(4),  // soffset
7012       Offsets.second,    // offset
7013       Op.getOperand(5),  // format
7014       Op.getOperand(6),  // cachepolicy, swizzled buffer
7015       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7016     };
7017 
7018     if (LoadVT.getScalarType() == MVT::f16)
7019       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7020                                  M, DAG, Ops);
7021     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7022                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7023                                DAG);
7024   }
7025   case Intrinsic::amdgcn_struct_tbuffer_load: {
7026     MemSDNode *M = cast<MemSDNode>(Op);
7027     EVT LoadVT = Op.getValueType();
7028     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7029 
7030     SDValue Ops[] = {
7031       Op.getOperand(0),  // Chain
7032       Op.getOperand(2),  // rsrc
7033       Op.getOperand(3),  // vindex
7034       Offsets.first,     // voffset
7035       Op.getOperand(5),  // soffset
7036       Offsets.second,    // offset
7037       Op.getOperand(6),  // format
7038       Op.getOperand(7),  // cachepolicy, swizzled buffer
7039       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7040     };
7041 
7042     if (LoadVT.getScalarType() == MVT::f16)
7043       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7044                                  M, DAG, Ops);
7045     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7046                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7047                                DAG);
7048   }
7049   case Intrinsic::amdgcn_buffer_atomic_swap:
7050   case Intrinsic::amdgcn_buffer_atomic_add:
7051   case Intrinsic::amdgcn_buffer_atomic_sub:
7052   case Intrinsic::amdgcn_buffer_atomic_csub:
7053   case Intrinsic::amdgcn_buffer_atomic_smin:
7054   case Intrinsic::amdgcn_buffer_atomic_umin:
7055   case Intrinsic::amdgcn_buffer_atomic_smax:
7056   case Intrinsic::amdgcn_buffer_atomic_umax:
7057   case Intrinsic::amdgcn_buffer_atomic_and:
7058   case Intrinsic::amdgcn_buffer_atomic_or:
7059   case Intrinsic::amdgcn_buffer_atomic_xor:
7060   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7061     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7062     unsigned IdxEn = 1;
7063     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7064       IdxEn = Idx->getZExtValue() != 0;
7065     SDValue Ops[] = {
7066       Op.getOperand(0), // Chain
7067       Op.getOperand(2), // vdata
7068       Op.getOperand(3), // rsrc
7069       Op.getOperand(4), // vindex
7070       SDValue(),        // voffset -- will be set by setBufferOffsets
7071       SDValue(),        // soffset -- will be set by setBufferOffsets
7072       SDValue(),        // offset -- will be set by setBufferOffsets
7073       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7074       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7075     };
7076     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7077     // We don't know the offset if vindex is non-zero, so clear it.
7078     if (IdxEn)
7079       Offset = 0;
7080     EVT VT = Op.getValueType();
7081 
7082     auto *M = cast<MemSDNode>(Op);
7083     M->getMemOperand()->setOffset(Offset);
7084     unsigned Opcode = 0;
7085 
7086     switch (IntrID) {
7087     case Intrinsic::amdgcn_buffer_atomic_swap:
7088       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7089       break;
7090     case Intrinsic::amdgcn_buffer_atomic_add:
7091       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7092       break;
7093     case Intrinsic::amdgcn_buffer_atomic_sub:
7094       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7095       break;
7096     case Intrinsic::amdgcn_buffer_atomic_csub:
7097       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7098       break;
7099     case Intrinsic::amdgcn_buffer_atomic_smin:
7100       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7101       break;
7102     case Intrinsic::amdgcn_buffer_atomic_umin:
7103       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7104       break;
7105     case Intrinsic::amdgcn_buffer_atomic_smax:
7106       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7107       break;
7108     case Intrinsic::amdgcn_buffer_atomic_umax:
7109       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7110       break;
7111     case Intrinsic::amdgcn_buffer_atomic_and:
7112       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7113       break;
7114     case Intrinsic::amdgcn_buffer_atomic_or:
7115       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7116       break;
7117     case Intrinsic::amdgcn_buffer_atomic_xor:
7118       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7119       break;
7120     case Intrinsic::amdgcn_buffer_atomic_fadd:
7121       if (!Op.getValue(0).use_empty()) {
7122         DiagnosticInfoUnsupported
7123           NoFpRet(DAG.getMachineFunction().getFunction(),
7124                   "return versions of fp atomics not supported",
7125                   DL.getDebugLoc(), DS_Error);
7126         DAG.getContext()->diagnose(NoFpRet);
7127         return SDValue();
7128       }
7129       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7130       break;
7131     default:
7132       llvm_unreachable("unhandled atomic opcode");
7133     }
7134 
7135     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7136                                    M->getMemOperand());
7137   }
7138   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7139     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7140   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7141     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7142   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7143     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7144   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7145     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7146   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7147     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7148   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7149     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7150   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7151     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7152   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7153     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7154   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7155     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7156   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7157     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7158   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7159     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7160   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7161     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7162   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7163     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7164   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7165     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7166   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7167     return lowerStructBufferAtomicIntrin(Op, DAG,
7168                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7169   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7170     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7171   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7172     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7173   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7174     return lowerStructBufferAtomicIntrin(Op, DAG,
7175                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7176   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7177     return lowerStructBufferAtomicIntrin(Op, DAG,
7178                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7179   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7180     return lowerStructBufferAtomicIntrin(Op, DAG,
7181                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7182   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7183     return lowerStructBufferAtomicIntrin(Op, DAG,
7184                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7185   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7186     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7187   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7188     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7189   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7190     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7191   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7192     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7193   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7194     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7195 
7196   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7197     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7198     unsigned IdxEn = 1;
7199     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7200       IdxEn = Idx->getZExtValue() != 0;
7201     SDValue Ops[] = {
7202       Op.getOperand(0), // Chain
7203       Op.getOperand(2), // src
7204       Op.getOperand(3), // cmp
7205       Op.getOperand(4), // rsrc
7206       Op.getOperand(5), // vindex
7207       SDValue(),        // voffset -- will be set by setBufferOffsets
7208       SDValue(),        // soffset -- will be set by setBufferOffsets
7209       SDValue(),        // offset -- will be set by setBufferOffsets
7210       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7211       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7212     };
7213     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7214     // We don't know the offset if vindex is non-zero, so clear it.
7215     if (IdxEn)
7216       Offset = 0;
7217     EVT VT = Op.getValueType();
7218     auto *M = cast<MemSDNode>(Op);
7219     M->getMemOperand()->setOffset(Offset);
7220 
7221     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7222                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7223   }
7224   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7225     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7226     SDValue Ops[] = {
7227       Op.getOperand(0), // Chain
7228       Op.getOperand(2), // src
7229       Op.getOperand(3), // cmp
7230       Op.getOperand(4), // rsrc
7231       DAG.getConstant(0, DL, MVT::i32), // vindex
7232       Offsets.first,    // voffset
7233       Op.getOperand(6), // soffset
7234       Offsets.second,   // offset
7235       Op.getOperand(7), // cachepolicy
7236       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7237     };
7238     EVT VT = Op.getValueType();
7239     auto *M = cast<MemSDNode>(Op);
7240     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7241 
7242     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7243                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7244   }
7245   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7246     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7247     SDValue Ops[] = {
7248       Op.getOperand(0), // Chain
7249       Op.getOperand(2), // src
7250       Op.getOperand(3), // cmp
7251       Op.getOperand(4), // rsrc
7252       Op.getOperand(5), // vindex
7253       Offsets.first,    // voffset
7254       Op.getOperand(7), // soffset
7255       Offsets.second,   // offset
7256       Op.getOperand(8), // cachepolicy
7257       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7258     };
7259     EVT VT = Op.getValueType();
7260     auto *M = cast<MemSDNode>(Op);
7261     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7262                                                         Ops[4]));
7263 
7264     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7265                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7266   }
7267   case Intrinsic::amdgcn_global_atomic_fadd: {
7268     if (!Op.getValue(0).use_empty()) {
7269       DiagnosticInfoUnsupported
7270         NoFpRet(DAG.getMachineFunction().getFunction(),
7271                 "return versions of fp atomics not supported",
7272                 DL.getDebugLoc(), DS_Error);
7273       DAG.getContext()->diagnose(NoFpRet);
7274       return SDValue();
7275     }
7276     MemSDNode *M = cast<MemSDNode>(Op);
7277     SDValue Ops[] = {
7278       M->getOperand(0), // Chain
7279       M->getOperand(2), // Ptr
7280       M->getOperand(3)  // Value
7281     };
7282 
7283     EVT VT = Op.getOperand(3).getValueType();
7284     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7285                          DAG.getVTList(VT, MVT::Other), Ops,
7286                          M->getMemOperand());
7287   }
7288   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7289     SDLoc DL(Op);
7290     MemSDNode *M = cast<MemSDNode>(Op);
7291     SDValue NodePtr = M->getOperand(2);
7292     SDValue RayExtent = M->getOperand(3);
7293     SDValue RayOrigin = M->getOperand(4);
7294     SDValue RayDir = M->getOperand(5);
7295     SDValue RayInvDir = M->getOperand(6);
7296     SDValue TDescr = M->getOperand(7);
7297 
7298     assert(NodePtr.getValueType() == MVT::i32 ||
7299            NodePtr.getValueType() == MVT::i64);
7300     assert(RayDir.getValueType() == MVT::v4f16 ||
7301            RayDir.getValueType() == MVT::v4f32);
7302 
7303     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7304     bool Is64 = NodePtr.getValueType() == MVT::i64;
7305     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7306                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7307                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7308                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7309 
7310     SmallVector<SDValue, 16> Ops;
7311 
7312     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7313       SmallVector<SDValue, 3> Lanes;
7314       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7315       if (Lanes[0].getValueSizeInBits() == 32) {
7316         for (unsigned I = 0; I < 3; ++I)
7317           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7318       } else {
7319         if (IsAligned) {
7320           Ops.push_back(
7321             DAG.getBitcast(MVT::i32,
7322                            DAG.getBuildVector(MVT::v2f16, DL,
7323                                               { Lanes[0], Lanes[1] })));
7324           Ops.push_back(Lanes[2]);
7325         } else {
7326           SDValue Elt0 = Ops.pop_back_val();
7327           Ops.push_back(
7328             DAG.getBitcast(MVT::i32,
7329                            DAG.getBuildVector(MVT::v2f16, DL,
7330                                               { Elt0, Lanes[0] })));
7331           Ops.push_back(
7332             DAG.getBitcast(MVT::i32,
7333                            DAG.getBuildVector(MVT::v2f16, DL,
7334                                               { Lanes[1], Lanes[2] })));
7335         }
7336       }
7337     };
7338 
7339     if (Is64)
7340       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7341     else
7342       Ops.push_back(NodePtr);
7343 
7344     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7345     packLanes(RayOrigin, true);
7346     packLanes(RayDir, true);
7347     packLanes(RayInvDir, false);
7348     Ops.push_back(TDescr);
7349     if (IsA16)
7350       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7351     Ops.push_back(M->getChain());
7352 
7353     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7354     MachineMemOperand *MemRef = M->getMemOperand();
7355     DAG.setNodeMemRefs(NewNode, {MemRef});
7356     return SDValue(NewNode, 0);
7357   }
7358   default:
7359     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7360             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7361       return lowerImage(Op, ImageDimIntr, DAG, true);
7362 
7363     return SDValue();
7364   }
7365 }
7366 
7367 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7368 // dwordx4 if on SI.
7369 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7370                                               SDVTList VTList,
7371                                               ArrayRef<SDValue> Ops, EVT MemVT,
7372                                               MachineMemOperand *MMO,
7373                                               SelectionDAG &DAG) const {
7374   EVT VT = VTList.VTs[0];
7375   EVT WidenedVT = VT;
7376   EVT WidenedMemVT = MemVT;
7377   if (!Subtarget->hasDwordx3LoadStores() &&
7378       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7379     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7380                                  WidenedVT.getVectorElementType(), 4);
7381     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7382                                     WidenedMemVT.getVectorElementType(), 4);
7383     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7384   }
7385 
7386   assert(VTList.NumVTs == 2);
7387   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7388 
7389   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7390                                        WidenedMemVT, MMO);
7391   if (WidenedVT != VT) {
7392     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7393                                DAG.getVectorIdxConstant(0, DL));
7394     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7395   }
7396   return NewOp;
7397 }
7398 
7399 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7400                                          bool ImageStore) const {
7401   EVT StoreVT = VData.getValueType();
7402 
7403   // No change for f16 and legal vector D16 types.
7404   if (!StoreVT.isVector())
7405     return VData;
7406 
7407   SDLoc DL(VData);
7408   unsigned NumElements = StoreVT.getVectorNumElements();
7409 
7410   if (Subtarget->hasUnpackedD16VMem()) {
7411     // We need to unpack the packed data to store.
7412     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7413     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7414 
7415     EVT EquivStoreVT =
7416         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7417     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7418     return DAG.UnrollVectorOp(ZExt.getNode());
7419   }
7420 
7421   // The sq block of gfx8.1 does not estimate register use correctly for d16
7422   // image store instructions. The data operand is computed as if it were not a
7423   // d16 image instruction.
7424   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7425     // Bitcast to i16
7426     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7427     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7428 
7429     // Decompose into scalars
7430     SmallVector<SDValue, 4> Elts;
7431     DAG.ExtractVectorElements(IntVData, Elts);
7432 
7433     // Group pairs of i16 into v2i16 and bitcast to i32
7434     SmallVector<SDValue, 4> PackedElts;
7435     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7436       SDValue Pair =
7437           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7438       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7439       PackedElts.push_back(IntPair);
7440     }
7441     if ((NumElements % 2) == 1) {
7442       // Handle v3i16
7443       unsigned I = Elts.size() / 2;
7444       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7445                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7446       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7447       PackedElts.push_back(IntPair);
7448     }
7449 
7450     // Pad using UNDEF
7451     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7452 
7453     // Build final vector
7454     EVT VecVT =
7455         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7456     return DAG.getBuildVector(VecVT, DL, PackedElts);
7457   }
7458 
7459   if (NumElements == 3) {
7460     EVT IntStoreVT =
7461         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7462     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7463 
7464     EVT WidenedStoreVT = EVT::getVectorVT(
7465         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7466     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7467                                          WidenedStoreVT.getStoreSizeInBits());
7468     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7469     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7470   }
7471 
7472   assert(isTypeLegal(StoreVT));
7473   return VData;
7474 }
7475 
7476 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7477                                               SelectionDAG &DAG) const {
7478   SDLoc DL(Op);
7479   SDValue Chain = Op.getOperand(0);
7480   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7481   MachineFunction &MF = DAG.getMachineFunction();
7482 
7483   switch (IntrinsicID) {
7484   case Intrinsic::amdgcn_exp_compr: {
7485     SDValue Src0 = Op.getOperand(4);
7486     SDValue Src1 = Op.getOperand(5);
7487     // Hack around illegal type on SI by directly selecting it.
7488     if (isTypeLegal(Src0.getValueType()))
7489       return SDValue();
7490 
7491     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7492     SDValue Undef = DAG.getUNDEF(MVT::f32);
7493     const SDValue Ops[] = {
7494       Op.getOperand(2), // tgt
7495       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7496       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7497       Undef, // src2
7498       Undef, // src3
7499       Op.getOperand(7), // vm
7500       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7501       Op.getOperand(3), // en
7502       Op.getOperand(0) // Chain
7503     };
7504 
7505     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7506     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7507   }
7508   case Intrinsic::amdgcn_s_barrier: {
7509     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7510       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7511       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7512       if (WGSize <= ST.getWavefrontSize())
7513         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7514                                           Op.getOperand(0)), 0);
7515     }
7516     return SDValue();
7517   };
7518   case Intrinsic::amdgcn_tbuffer_store: {
7519     SDValue VData = Op.getOperand(2);
7520     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7521     if (IsD16)
7522       VData = handleD16VData(VData, DAG);
7523     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7524     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7525     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7526     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7527     unsigned IdxEn = 1;
7528     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7529       IdxEn = Idx->getZExtValue() != 0;
7530     SDValue Ops[] = {
7531       Chain,
7532       VData,             // vdata
7533       Op.getOperand(3),  // rsrc
7534       Op.getOperand(4),  // vindex
7535       Op.getOperand(5),  // voffset
7536       Op.getOperand(6),  // soffset
7537       Op.getOperand(7),  // offset
7538       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7539       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7540       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7541     };
7542     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7543                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7544     MemSDNode *M = cast<MemSDNode>(Op);
7545     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7546                                    M->getMemoryVT(), M->getMemOperand());
7547   }
7548 
7549   case Intrinsic::amdgcn_struct_tbuffer_store: {
7550     SDValue VData = Op.getOperand(2);
7551     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7552     if (IsD16)
7553       VData = handleD16VData(VData, DAG);
7554     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7555     SDValue Ops[] = {
7556       Chain,
7557       VData,             // vdata
7558       Op.getOperand(3),  // rsrc
7559       Op.getOperand(4),  // vindex
7560       Offsets.first,     // voffset
7561       Op.getOperand(6),  // soffset
7562       Offsets.second,    // offset
7563       Op.getOperand(7),  // format
7564       Op.getOperand(8),  // cachepolicy, swizzled buffer
7565       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7566     };
7567     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7568                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7569     MemSDNode *M = cast<MemSDNode>(Op);
7570     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7571                                    M->getMemoryVT(), M->getMemOperand());
7572   }
7573 
7574   case Intrinsic::amdgcn_raw_tbuffer_store: {
7575     SDValue VData = Op.getOperand(2);
7576     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7577     if (IsD16)
7578       VData = handleD16VData(VData, DAG);
7579     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7580     SDValue Ops[] = {
7581       Chain,
7582       VData,             // vdata
7583       Op.getOperand(3),  // rsrc
7584       DAG.getConstant(0, DL, MVT::i32), // vindex
7585       Offsets.first,     // voffset
7586       Op.getOperand(5),  // soffset
7587       Offsets.second,    // offset
7588       Op.getOperand(6),  // format
7589       Op.getOperand(7),  // cachepolicy, swizzled buffer
7590       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7591     };
7592     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7593                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7594     MemSDNode *M = cast<MemSDNode>(Op);
7595     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7596                                    M->getMemoryVT(), M->getMemOperand());
7597   }
7598 
7599   case Intrinsic::amdgcn_buffer_store:
7600   case Intrinsic::amdgcn_buffer_store_format: {
7601     SDValue VData = Op.getOperand(2);
7602     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7603     if (IsD16)
7604       VData = handleD16VData(VData, DAG);
7605     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7606     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7607     unsigned IdxEn = 1;
7608     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7609       IdxEn = Idx->getZExtValue() != 0;
7610     SDValue Ops[] = {
7611       Chain,
7612       VData,
7613       Op.getOperand(3), // rsrc
7614       Op.getOperand(4), // vindex
7615       SDValue(), // voffset -- will be set by setBufferOffsets
7616       SDValue(), // soffset -- will be set by setBufferOffsets
7617       SDValue(), // offset -- will be set by setBufferOffsets
7618       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7619       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7620     };
7621     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7622     // We don't know the offset if vindex is non-zero, so clear it.
7623     if (IdxEn)
7624       Offset = 0;
7625     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7626                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7627     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7628     MemSDNode *M = cast<MemSDNode>(Op);
7629     M->getMemOperand()->setOffset(Offset);
7630 
7631     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7632     EVT VDataType = VData.getValueType().getScalarType();
7633     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7634       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7635 
7636     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7637                                    M->getMemoryVT(), M->getMemOperand());
7638   }
7639 
7640   case Intrinsic::amdgcn_raw_buffer_store:
7641   case Intrinsic::amdgcn_raw_buffer_store_format: {
7642     const bool IsFormat =
7643         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7644 
7645     SDValue VData = Op.getOperand(2);
7646     EVT VDataVT = VData.getValueType();
7647     EVT EltType = VDataVT.getScalarType();
7648     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7649     if (IsD16) {
7650       VData = handleD16VData(VData, DAG);
7651       VDataVT = VData.getValueType();
7652     }
7653 
7654     if (!isTypeLegal(VDataVT)) {
7655       VData =
7656           DAG.getNode(ISD::BITCAST, DL,
7657                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7658     }
7659 
7660     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7661     SDValue Ops[] = {
7662       Chain,
7663       VData,
7664       Op.getOperand(3), // rsrc
7665       DAG.getConstant(0, DL, MVT::i32), // vindex
7666       Offsets.first,    // voffset
7667       Op.getOperand(5), // soffset
7668       Offsets.second,   // offset
7669       Op.getOperand(6), // cachepolicy, swizzled buffer
7670       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7671     };
7672     unsigned Opc =
7673         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7674     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7675     MemSDNode *M = cast<MemSDNode>(Op);
7676     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7677 
7678     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7679     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7680       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7681 
7682     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7683                                    M->getMemoryVT(), M->getMemOperand());
7684   }
7685 
7686   case Intrinsic::amdgcn_struct_buffer_store:
7687   case Intrinsic::amdgcn_struct_buffer_store_format: {
7688     const bool IsFormat =
7689         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7690 
7691     SDValue VData = Op.getOperand(2);
7692     EVT VDataVT = VData.getValueType();
7693     EVT EltType = VDataVT.getScalarType();
7694     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7695 
7696     if (IsD16) {
7697       VData = handleD16VData(VData, DAG);
7698       VDataVT = VData.getValueType();
7699     }
7700 
7701     if (!isTypeLegal(VDataVT)) {
7702       VData =
7703           DAG.getNode(ISD::BITCAST, DL,
7704                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7705     }
7706 
7707     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7708     SDValue Ops[] = {
7709       Chain,
7710       VData,
7711       Op.getOperand(3), // rsrc
7712       Op.getOperand(4), // vindex
7713       Offsets.first,    // voffset
7714       Op.getOperand(6), // soffset
7715       Offsets.second,   // offset
7716       Op.getOperand(7), // cachepolicy, swizzled buffer
7717       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7718     };
7719     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_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(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7724                                                         Ops[3]));
7725 
7726     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7727     EVT VDataType = VData.getValueType().getScalarType();
7728     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7729       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7730 
7731     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7732                                    M->getMemoryVT(), M->getMemOperand());
7733   }
7734   case Intrinsic::amdgcn_end_cf:
7735     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7736                                       Op->getOperand(2), Chain), 0);
7737 
7738   default: {
7739     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7740             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7741       return lowerImage(Op, ImageDimIntr, DAG, true);
7742 
7743     return Op;
7744   }
7745   }
7746 }
7747 
7748 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7749 // offset (the offset that is included in bounds checking and swizzling, to be
7750 // split between the instruction's voffset and immoffset fields) and soffset
7751 // (the offset that is excluded from bounds checking and swizzling, to go in
7752 // the instruction's soffset field).  This function takes the first kind of
7753 // offset and figures out how to split it between voffset and immoffset.
7754 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7755     SDValue Offset, SelectionDAG &DAG) const {
7756   SDLoc DL(Offset);
7757   const unsigned MaxImm = 4095;
7758   SDValue N0 = Offset;
7759   ConstantSDNode *C1 = nullptr;
7760 
7761   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7762     N0 = SDValue();
7763   else if (DAG.isBaseWithConstantOffset(N0)) {
7764     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7765     N0 = N0.getOperand(0);
7766   }
7767 
7768   if (C1) {
7769     unsigned ImmOffset = C1->getZExtValue();
7770     // If the immediate value is too big for the immoffset field, put the value
7771     // and -4096 into the immoffset field so that the value that is copied/added
7772     // for the voffset field is a multiple of 4096, and it stands more chance
7773     // of being CSEd with the copy/add for another similar load/store.
7774     // However, do not do that rounding down to a multiple of 4096 if that is a
7775     // negative number, as it appears to be illegal to have a negative offset
7776     // in the vgpr, even if adding the immediate offset makes it positive.
7777     unsigned Overflow = ImmOffset & ~MaxImm;
7778     ImmOffset -= Overflow;
7779     if ((int32_t)Overflow < 0) {
7780       Overflow += ImmOffset;
7781       ImmOffset = 0;
7782     }
7783     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7784     if (Overflow) {
7785       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7786       if (!N0)
7787         N0 = OverflowVal;
7788       else {
7789         SDValue Ops[] = { N0, OverflowVal };
7790         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7791       }
7792     }
7793   }
7794   if (!N0)
7795     N0 = DAG.getConstant(0, DL, MVT::i32);
7796   if (!C1)
7797     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7798   return {N0, SDValue(C1, 0)};
7799 }
7800 
7801 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7802 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7803 // pointed to by Offsets.
7804 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7805                                             SelectionDAG &DAG, SDValue *Offsets,
7806                                             Align Alignment) const {
7807   SDLoc DL(CombinedOffset);
7808   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7809     uint32_t Imm = C->getZExtValue();
7810     uint32_t SOffset, ImmOffset;
7811     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7812                                  Alignment)) {
7813       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7814       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7815       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7816       return SOffset + ImmOffset;
7817     }
7818   }
7819   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7820     SDValue N0 = CombinedOffset.getOperand(0);
7821     SDValue N1 = CombinedOffset.getOperand(1);
7822     uint32_t SOffset, ImmOffset;
7823     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7824     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7825                                                 Subtarget, Alignment)) {
7826       Offsets[0] = N0;
7827       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7828       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7829       return 0;
7830     }
7831   }
7832   Offsets[0] = CombinedOffset;
7833   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7834   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7835   return 0;
7836 }
7837 
7838 // Handle 8 bit and 16 bit buffer loads
7839 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7840                                                      EVT LoadVT, SDLoc DL,
7841                                                      ArrayRef<SDValue> Ops,
7842                                                      MemSDNode *M) const {
7843   EVT IntVT = LoadVT.changeTypeToInteger();
7844   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7845          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7846 
7847   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7848   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7849                                                Ops, IntVT,
7850                                                M->getMemOperand());
7851   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7852   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7853 
7854   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7855 }
7856 
7857 // Handle 8 bit and 16 bit buffer stores
7858 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7859                                                       EVT VDataType, SDLoc DL,
7860                                                       SDValue Ops[],
7861                                                       MemSDNode *M) const {
7862   if (VDataType == MVT::f16)
7863     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7864 
7865   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7866   Ops[1] = BufferStoreExt;
7867   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7868                                  AMDGPUISD::BUFFER_STORE_SHORT;
7869   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7870   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7871                                      M->getMemOperand());
7872 }
7873 
7874 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7875                                  ISD::LoadExtType ExtType, SDValue Op,
7876                                  const SDLoc &SL, EVT VT) {
7877   if (VT.bitsLT(Op.getValueType()))
7878     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7879 
7880   switch (ExtType) {
7881   case ISD::SEXTLOAD:
7882     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7883   case ISD::ZEXTLOAD:
7884     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7885   case ISD::EXTLOAD:
7886     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7887   case ISD::NON_EXTLOAD:
7888     return Op;
7889   }
7890 
7891   llvm_unreachable("invalid ext type");
7892 }
7893 
7894 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7895   SelectionDAG &DAG = DCI.DAG;
7896   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7897     return SDValue();
7898 
7899   // FIXME: Constant loads should all be marked invariant.
7900   unsigned AS = Ld->getAddressSpace();
7901   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7902       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7903       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7904     return SDValue();
7905 
7906   // Don't do this early, since it may interfere with adjacent load merging for
7907   // illegal types. We can avoid losing alignment information for exotic types
7908   // pre-legalize.
7909   EVT MemVT = Ld->getMemoryVT();
7910   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7911       MemVT.getSizeInBits() >= 32)
7912     return SDValue();
7913 
7914   SDLoc SL(Ld);
7915 
7916   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7917          "unexpected vector extload");
7918 
7919   // TODO: Drop only high part of range.
7920   SDValue Ptr = Ld->getBasePtr();
7921   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7922                                 MVT::i32, SL, Ld->getChain(), Ptr,
7923                                 Ld->getOffset(),
7924                                 Ld->getPointerInfo(), MVT::i32,
7925                                 Ld->getAlignment(),
7926                                 Ld->getMemOperand()->getFlags(),
7927                                 Ld->getAAInfo(),
7928                                 nullptr); // Drop ranges
7929 
7930   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7931   if (MemVT.isFloatingPoint()) {
7932     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7933            "unexpected fp extload");
7934     TruncVT = MemVT.changeTypeToInteger();
7935   }
7936 
7937   SDValue Cvt = NewLoad;
7938   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7939     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7940                       DAG.getValueType(TruncVT));
7941   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7942              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7943     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7944   } else {
7945     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7946   }
7947 
7948   EVT VT = Ld->getValueType(0);
7949   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7950 
7951   DCI.AddToWorklist(Cvt.getNode());
7952 
7953   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7954   // the appropriate extension from the 32-bit load.
7955   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7956   DCI.AddToWorklist(Cvt.getNode());
7957 
7958   // Handle conversion back to floating point if necessary.
7959   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7960 
7961   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7962 }
7963 
7964 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7965   SDLoc DL(Op);
7966   LoadSDNode *Load = cast<LoadSDNode>(Op);
7967   ISD::LoadExtType ExtType = Load->getExtensionType();
7968   EVT MemVT = Load->getMemoryVT();
7969 
7970   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7971     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7972       return SDValue();
7973 
7974     // FIXME: Copied from PPC
7975     // First, load into 32 bits, then truncate to 1 bit.
7976 
7977     SDValue Chain = Load->getChain();
7978     SDValue BasePtr = Load->getBasePtr();
7979     MachineMemOperand *MMO = Load->getMemOperand();
7980 
7981     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7982 
7983     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7984                                    BasePtr, RealMemVT, MMO);
7985 
7986     if (!MemVT.isVector()) {
7987       SDValue Ops[] = {
7988         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7989         NewLD.getValue(1)
7990       };
7991 
7992       return DAG.getMergeValues(Ops, DL);
7993     }
7994 
7995     SmallVector<SDValue, 3> Elts;
7996     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7997       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7998                                 DAG.getConstant(I, DL, MVT::i32));
7999 
8000       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8001     }
8002 
8003     SDValue Ops[] = {
8004       DAG.getBuildVector(MemVT, DL, Elts),
8005       NewLD.getValue(1)
8006     };
8007 
8008     return DAG.getMergeValues(Ops, DL);
8009   }
8010 
8011   if (!MemVT.isVector())
8012     return SDValue();
8013 
8014   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8015          "Custom lowering for non-i32 vectors hasn't been implemented.");
8016 
8017   unsigned Alignment = Load->getAlignment();
8018   unsigned AS = Load->getAddressSpace();
8019   if (Subtarget->hasLDSMisalignedBug() &&
8020       AS == AMDGPUAS::FLAT_ADDRESS &&
8021       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8022     return SplitVectorLoad(Op, DAG);
8023   }
8024 
8025   MachineFunction &MF = DAG.getMachineFunction();
8026   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8027   // If there is a possibilty that flat instruction access scratch memory
8028   // then we need to use the same legalization rules we use for private.
8029   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8030       !Subtarget->hasMultiDwordFlatScratchAddressing())
8031     AS = MFI->hasFlatScratchInit() ?
8032          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8033 
8034   unsigned NumElements = MemVT.getVectorNumElements();
8035 
8036   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8037       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8038     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8039       if (MemVT.isPow2VectorType())
8040         return SDValue();
8041       return WidenOrSplitVectorLoad(Op, DAG);
8042     }
8043     // Non-uniform loads will be selected to MUBUF instructions, so they
8044     // have the same legalization requirements as global and private
8045     // loads.
8046     //
8047   }
8048 
8049   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8050       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8051       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8052     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8053         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8054         Alignment >= 4 && NumElements < 32) {
8055       if (MemVT.isPow2VectorType())
8056         return SDValue();
8057       return WidenOrSplitVectorLoad(Op, DAG);
8058     }
8059     // Non-uniform loads will be selected to MUBUF instructions, so they
8060     // have the same legalization requirements as global and private
8061     // loads.
8062     //
8063   }
8064   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8065       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8066       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8067       AS == AMDGPUAS::FLAT_ADDRESS) {
8068     if (NumElements > 4)
8069       return SplitVectorLoad(Op, DAG);
8070     // v3 loads not supported on SI.
8071     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8072       return WidenOrSplitVectorLoad(Op, DAG);
8073 
8074     // v3 and v4 loads are supported for private and global memory.
8075     return SDValue();
8076   }
8077   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8078     // Depending on the setting of the private_element_size field in the
8079     // resource descriptor, we can only make private accesses up to a certain
8080     // size.
8081     switch (Subtarget->getMaxPrivateElementSize()) {
8082     case 4: {
8083       SDValue Ops[2];
8084       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8085       return DAG.getMergeValues(Ops, DL);
8086     }
8087     case 8:
8088       if (NumElements > 2)
8089         return SplitVectorLoad(Op, DAG);
8090       return SDValue();
8091     case 16:
8092       // Same as global/flat
8093       if (NumElements > 4)
8094         return SplitVectorLoad(Op, DAG);
8095       // v3 loads not supported on SI.
8096       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8097         return WidenOrSplitVectorLoad(Op, DAG);
8098 
8099       return SDValue();
8100     default:
8101       llvm_unreachable("unsupported private_element_size");
8102     }
8103   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8104     // Use ds_read_b128 or ds_read_b96 when possible.
8105     if (Subtarget->hasDS96AndDS128() &&
8106         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8107          MemVT.getStoreSize() == 12) &&
8108         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8109                                            Load->getAlign()))
8110       return SDValue();
8111 
8112     if (NumElements > 2)
8113       return SplitVectorLoad(Op, DAG);
8114 
8115     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8116     // address is negative, then the instruction is incorrectly treated as
8117     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8118     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8119     // load later in the SILoadStoreOptimizer.
8120     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8121         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8122         Load->getAlignment() < 8) {
8123       return SplitVectorLoad(Op, DAG);
8124     }
8125   }
8126 
8127   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8128                                       MemVT, *Load->getMemOperand())) {
8129     SDValue Ops[2];
8130     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8131     return DAG.getMergeValues(Ops, DL);
8132   }
8133 
8134   return SDValue();
8135 }
8136 
8137 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8138   EVT VT = Op.getValueType();
8139   assert(VT.getSizeInBits() == 64);
8140 
8141   SDLoc DL(Op);
8142   SDValue Cond = Op.getOperand(0);
8143 
8144   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8145   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8146 
8147   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8148   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8149 
8150   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8151   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8152 
8153   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8154 
8155   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8156   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8157 
8158   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8159 
8160   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8161   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8162 }
8163 
8164 // Catch division cases where we can use shortcuts with rcp and rsq
8165 // instructions.
8166 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8167                                               SelectionDAG &DAG) const {
8168   SDLoc SL(Op);
8169   SDValue LHS = Op.getOperand(0);
8170   SDValue RHS = Op.getOperand(1);
8171   EVT VT = Op.getValueType();
8172   const SDNodeFlags Flags = Op->getFlags();
8173 
8174   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8175 
8176   // Without !fpmath accuracy information, we can't do more because we don't
8177   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8178   if (!AllowInaccurateRcp)
8179     return SDValue();
8180 
8181   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8182     if (CLHS->isExactlyValue(1.0)) {
8183       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8184       // the CI documentation has a worst case error of 1 ulp.
8185       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8186       // use it as long as we aren't trying to use denormals.
8187       //
8188       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8189 
8190       // 1.0 / sqrt(x) -> rsq(x)
8191 
8192       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8193       // error seems really high at 2^29 ULP.
8194       if (RHS.getOpcode() == ISD::FSQRT)
8195         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8196 
8197       // 1.0 / x -> rcp(x)
8198       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8199     }
8200 
8201     // Same as for 1.0, but expand the sign out of the constant.
8202     if (CLHS->isExactlyValue(-1.0)) {
8203       // -1.0 / x -> rcp (fneg x)
8204       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8205       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8206     }
8207   }
8208 
8209   // Turn into multiply by the reciprocal.
8210   // x / y -> x * (1.0 / y)
8211   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8212   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8213 }
8214 
8215 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8216                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8217                           SDNodeFlags Flags) {
8218   if (GlueChain->getNumValues() <= 1) {
8219     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8220   }
8221 
8222   assert(GlueChain->getNumValues() == 3);
8223 
8224   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8225   switch (Opcode) {
8226   default: llvm_unreachable("no chain equivalent for opcode");
8227   case ISD::FMUL:
8228     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8229     break;
8230   }
8231 
8232   return DAG.getNode(Opcode, SL, VTList,
8233                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8234                      Flags);
8235 }
8236 
8237 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8238                            EVT VT, SDValue A, SDValue B, SDValue C,
8239                            SDValue GlueChain, SDNodeFlags Flags) {
8240   if (GlueChain->getNumValues() <= 1) {
8241     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8242   }
8243 
8244   assert(GlueChain->getNumValues() == 3);
8245 
8246   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8247   switch (Opcode) {
8248   default: llvm_unreachable("no chain equivalent for opcode");
8249   case ISD::FMA:
8250     Opcode = AMDGPUISD::FMA_W_CHAIN;
8251     break;
8252   }
8253 
8254   return DAG.getNode(Opcode, SL, VTList,
8255                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8256                      Flags);
8257 }
8258 
8259 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8260   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8261     return FastLowered;
8262 
8263   SDLoc SL(Op);
8264   SDValue Src0 = Op.getOperand(0);
8265   SDValue Src1 = Op.getOperand(1);
8266 
8267   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8268   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8269 
8270   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8271   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8272 
8273   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8274   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8275 
8276   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8277 }
8278 
8279 // Faster 2.5 ULP division that does not support denormals.
8280 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8281   SDLoc SL(Op);
8282   SDValue LHS = Op.getOperand(1);
8283   SDValue RHS = Op.getOperand(2);
8284 
8285   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8286 
8287   const APFloat K0Val(BitsToFloat(0x6f800000));
8288   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8289 
8290   const APFloat K1Val(BitsToFloat(0x2f800000));
8291   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8292 
8293   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8294 
8295   EVT SetCCVT =
8296     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8297 
8298   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8299 
8300   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8301 
8302   // TODO: Should this propagate fast-math-flags?
8303   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8304 
8305   // rcp does not support denormals.
8306   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8307 
8308   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8309 
8310   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8311 }
8312 
8313 // Returns immediate value for setting the F32 denorm mode when using the
8314 // S_DENORM_MODE instruction.
8315 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8316                                           const SDLoc &SL, const GCNSubtarget *ST) {
8317   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8318   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8319                                 ? FP_DENORM_FLUSH_NONE
8320                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8321 
8322   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8323   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8324 }
8325 
8326 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8327   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8328     return FastLowered;
8329 
8330   // The selection matcher assumes anything with a chain selecting to a
8331   // mayRaiseFPException machine instruction. Since we're introducing a chain
8332   // here, we need to explicitly report nofpexcept for the regular fdiv
8333   // lowering.
8334   SDNodeFlags Flags = Op->getFlags();
8335   Flags.setNoFPExcept(true);
8336 
8337   SDLoc SL(Op);
8338   SDValue LHS = Op.getOperand(0);
8339   SDValue RHS = Op.getOperand(1);
8340 
8341   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8342 
8343   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8344 
8345   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8346                                           {RHS, RHS, LHS}, Flags);
8347   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8348                                         {LHS, RHS, LHS}, Flags);
8349 
8350   // Denominator is scaled to not be denormal, so using rcp is ok.
8351   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8352                                   DenominatorScaled, Flags);
8353   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8354                                      DenominatorScaled, Flags);
8355 
8356   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8357                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8358                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8359   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8360 
8361   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8362 
8363   if (!HasFP32Denormals) {
8364     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8365     // lowering. The chain dependence is insufficient, and we need glue. We do
8366     // not need the glue variants in a strictfp function.
8367 
8368     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8369 
8370     SDNode *EnableDenorm;
8371     if (Subtarget->hasDenormModeInst()) {
8372       const SDValue EnableDenormValue =
8373           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8374 
8375       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8376                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8377     } else {
8378       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8379                                                         SL, MVT::i32);
8380       EnableDenorm =
8381           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8382                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8383     }
8384 
8385     SDValue Ops[3] = {
8386       NegDivScale0,
8387       SDValue(EnableDenorm, 0),
8388       SDValue(EnableDenorm, 1)
8389     };
8390 
8391     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8392   }
8393 
8394   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8395                              ApproxRcp, One, NegDivScale0, Flags);
8396 
8397   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8398                              ApproxRcp, Fma0, Flags);
8399 
8400   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8401                            Fma1, Fma1, Flags);
8402 
8403   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8404                              NumeratorScaled, Mul, Flags);
8405 
8406   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8407                              Fma2, Fma1, Mul, Fma2, Flags);
8408 
8409   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8410                              NumeratorScaled, Fma3, Flags);
8411 
8412   if (!HasFP32Denormals) {
8413     SDNode *DisableDenorm;
8414     if (Subtarget->hasDenormModeInst()) {
8415       const SDValue DisableDenormValue =
8416           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8417 
8418       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8419                                   Fma4.getValue(1), DisableDenormValue,
8420                                   Fma4.getValue(2)).getNode();
8421     } else {
8422       const SDValue DisableDenormValue =
8423           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8424 
8425       DisableDenorm = DAG.getMachineNode(
8426           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8427           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8428     }
8429 
8430     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8431                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8432     DAG.setRoot(OutputChain);
8433   }
8434 
8435   SDValue Scale = NumeratorScaled.getValue(1);
8436   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8437                              {Fma4, Fma1, Fma3, Scale}, Flags);
8438 
8439   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8440 }
8441 
8442 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8443   if (DAG.getTarget().Options.UnsafeFPMath)
8444     return lowerFastUnsafeFDIV(Op, DAG);
8445 
8446   SDLoc SL(Op);
8447   SDValue X = Op.getOperand(0);
8448   SDValue Y = Op.getOperand(1);
8449 
8450   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8451 
8452   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8453 
8454   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8455 
8456   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8457 
8458   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8459 
8460   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8461 
8462   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8463 
8464   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8465 
8466   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8467 
8468   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8469   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8470 
8471   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8472                              NegDivScale0, Mul, DivScale1);
8473 
8474   SDValue Scale;
8475 
8476   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8477     // Workaround a hardware bug on SI where the condition output from div_scale
8478     // is not usable.
8479 
8480     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8481 
8482     // Figure out if the scale to use for div_fmas.
8483     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8484     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8485     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8486     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8487 
8488     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8489     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8490 
8491     SDValue Scale0Hi
8492       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8493     SDValue Scale1Hi
8494       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8495 
8496     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8497     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8498     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8499   } else {
8500     Scale = DivScale1.getValue(1);
8501   }
8502 
8503   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8504                              Fma4, Fma3, Mul, Scale);
8505 
8506   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8507 }
8508 
8509 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8510   EVT VT = Op.getValueType();
8511 
8512   if (VT == MVT::f32)
8513     return LowerFDIV32(Op, DAG);
8514 
8515   if (VT == MVT::f64)
8516     return LowerFDIV64(Op, DAG);
8517 
8518   if (VT == MVT::f16)
8519     return LowerFDIV16(Op, DAG);
8520 
8521   llvm_unreachable("Unexpected type for fdiv");
8522 }
8523 
8524 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8525   SDLoc DL(Op);
8526   StoreSDNode *Store = cast<StoreSDNode>(Op);
8527   EVT VT = Store->getMemoryVT();
8528 
8529   if (VT == MVT::i1) {
8530     return DAG.getTruncStore(Store->getChain(), DL,
8531        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8532        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8533   }
8534 
8535   assert(VT.isVector() &&
8536          Store->getValue().getValueType().getScalarType() == MVT::i32);
8537 
8538   unsigned AS = Store->getAddressSpace();
8539   if (Subtarget->hasLDSMisalignedBug() &&
8540       AS == AMDGPUAS::FLAT_ADDRESS &&
8541       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8542     return SplitVectorStore(Op, DAG);
8543   }
8544 
8545   MachineFunction &MF = DAG.getMachineFunction();
8546   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8547   // If there is a possibilty that flat instruction access scratch memory
8548   // then we need to use the same legalization rules we use for private.
8549   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8550       !Subtarget->hasMultiDwordFlatScratchAddressing())
8551     AS = MFI->hasFlatScratchInit() ?
8552          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8553 
8554   unsigned NumElements = VT.getVectorNumElements();
8555   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8556       AS == AMDGPUAS::FLAT_ADDRESS) {
8557     if (NumElements > 4)
8558       return SplitVectorStore(Op, DAG);
8559     // v3 stores not supported on SI.
8560     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8561       return SplitVectorStore(Op, DAG);
8562 
8563     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8564                                         VT, *Store->getMemOperand()))
8565       return expandUnalignedStore(Store, DAG);
8566 
8567     return SDValue();
8568   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8569     switch (Subtarget->getMaxPrivateElementSize()) {
8570     case 4:
8571       return scalarizeVectorStore(Store, DAG);
8572     case 8:
8573       if (NumElements > 2)
8574         return SplitVectorStore(Op, DAG);
8575       return SDValue();
8576     case 16:
8577       if (NumElements > 4 ||
8578           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8579         return SplitVectorStore(Op, DAG);
8580       return SDValue();
8581     default:
8582       llvm_unreachable("unsupported private_element_size");
8583     }
8584   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8585     // Use ds_write_b128 or ds_write_b96 when possible.
8586     if (Subtarget->hasDS96AndDS128() &&
8587         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8588          (VT.getStoreSize() == 12)) &&
8589         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8590                                            Store->getAlign()))
8591       return SDValue();
8592 
8593     if (NumElements > 2)
8594       return SplitVectorStore(Op, DAG);
8595 
8596     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8597     // address is negative, then the instruction is incorrectly treated as
8598     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8599     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8600     // store later in the SILoadStoreOptimizer.
8601     if (!Subtarget->hasUsableDSOffset() &&
8602         NumElements == 2 && VT.getStoreSize() == 8 &&
8603         Store->getAlignment() < 8) {
8604       return SplitVectorStore(Op, DAG);
8605     }
8606 
8607     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8608                                         VT, *Store->getMemOperand())) {
8609       if (VT.isVector())
8610         return SplitVectorStore(Op, DAG);
8611       return expandUnalignedStore(Store, DAG);
8612     }
8613 
8614     return SDValue();
8615   } else {
8616     llvm_unreachable("unhandled address space");
8617   }
8618 }
8619 
8620 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8621   SDLoc DL(Op);
8622   EVT VT = Op.getValueType();
8623   SDValue Arg = Op.getOperand(0);
8624   SDValue TrigVal;
8625 
8626   // Propagate fast-math flags so that the multiply we introduce can be folded
8627   // if Arg is already the result of a multiply by constant.
8628   auto Flags = Op->getFlags();
8629 
8630   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8631 
8632   if (Subtarget->hasTrigReducedRange()) {
8633     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8634     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8635   } else {
8636     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8637   }
8638 
8639   switch (Op.getOpcode()) {
8640   case ISD::FCOS:
8641     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8642   case ISD::FSIN:
8643     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8644   default:
8645     llvm_unreachable("Wrong trig opcode");
8646   }
8647 }
8648 
8649 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8650   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8651   assert(AtomicNode->isCompareAndSwap());
8652   unsigned AS = AtomicNode->getAddressSpace();
8653 
8654   // No custom lowering required for local address space
8655   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8656     return Op;
8657 
8658   // Non-local address space requires custom lowering for atomic compare
8659   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8660   SDLoc DL(Op);
8661   SDValue ChainIn = Op.getOperand(0);
8662   SDValue Addr = Op.getOperand(1);
8663   SDValue Old = Op.getOperand(2);
8664   SDValue New = Op.getOperand(3);
8665   EVT VT = Op.getValueType();
8666   MVT SimpleVT = VT.getSimpleVT();
8667   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8668 
8669   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8670   SDValue Ops[] = { ChainIn, Addr, NewOld };
8671 
8672   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8673                                  Ops, VT, AtomicNode->getMemOperand());
8674 }
8675 
8676 //===----------------------------------------------------------------------===//
8677 // Custom DAG optimizations
8678 //===----------------------------------------------------------------------===//
8679 
8680 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8681                                                      DAGCombinerInfo &DCI) const {
8682   EVT VT = N->getValueType(0);
8683   EVT ScalarVT = VT.getScalarType();
8684   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8685     return SDValue();
8686 
8687   SelectionDAG &DAG = DCI.DAG;
8688   SDLoc DL(N);
8689 
8690   SDValue Src = N->getOperand(0);
8691   EVT SrcVT = Src.getValueType();
8692 
8693   // TODO: We could try to match extracting the higher bytes, which would be
8694   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8695   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8696   // about in practice.
8697   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8698     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8699       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8700       DCI.AddToWorklist(Cvt.getNode());
8701 
8702       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8703       if (ScalarVT != MVT::f32) {
8704         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8705                           DAG.getTargetConstant(0, DL, MVT::i32));
8706       }
8707       return Cvt;
8708     }
8709   }
8710 
8711   return SDValue();
8712 }
8713 
8714 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8715 
8716 // This is a variant of
8717 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8718 //
8719 // The normal DAG combiner will do this, but only if the add has one use since
8720 // that would increase the number of instructions.
8721 //
8722 // This prevents us from seeing a constant offset that can be folded into a
8723 // memory instruction's addressing mode. If we know the resulting add offset of
8724 // a pointer can be folded into an addressing offset, we can replace the pointer
8725 // operand with the add of new constant offset. This eliminates one of the uses,
8726 // and may allow the remaining use to also be simplified.
8727 //
8728 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8729                                                unsigned AddrSpace,
8730                                                EVT MemVT,
8731                                                DAGCombinerInfo &DCI) const {
8732   SDValue N0 = N->getOperand(0);
8733   SDValue N1 = N->getOperand(1);
8734 
8735   // We only do this to handle cases where it's profitable when there are
8736   // multiple uses of the add, so defer to the standard combine.
8737   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8738       N0->hasOneUse())
8739     return SDValue();
8740 
8741   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8742   if (!CN1)
8743     return SDValue();
8744 
8745   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8746   if (!CAdd)
8747     return SDValue();
8748 
8749   // If the resulting offset is too large, we can't fold it into the addressing
8750   // mode offset.
8751   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8752   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8753 
8754   AddrMode AM;
8755   AM.HasBaseReg = true;
8756   AM.BaseOffs = Offset.getSExtValue();
8757   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8758     return SDValue();
8759 
8760   SelectionDAG &DAG = DCI.DAG;
8761   SDLoc SL(N);
8762   EVT VT = N->getValueType(0);
8763 
8764   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8765   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8766 
8767   SDNodeFlags Flags;
8768   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8769                           (N0.getOpcode() == ISD::OR ||
8770                            N0->getFlags().hasNoUnsignedWrap()));
8771 
8772   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8773 }
8774 
8775 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8776 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8777 /// specific intrinsic, but they all place the pointer operand first.
8778 static unsigned getBasePtrIndex(const MemSDNode *N) {
8779   switch (N->getOpcode()) {
8780   case ISD::STORE:
8781   case ISD::INTRINSIC_W_CHAIN:
8782   case ISD::INTRINSIC_VOID:
8783     return 2;
8784   default:
8785     return 1;
8786   }
8787 }
8788 
8789 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8790                                                   DAGCombinerInfo &DCI) const {
8791   SelectionDAG &DAG = DCI.DAG;
8792   SDLoc SL(N);
8793 
8794   unsigned PtrIdx = getBasePtrIndex(N);
8795   SDValue Ptr = N->getOperand(PtrIdx);
8796 
8797   // TODO: We could also do this for multiplies.
8798   if (Ptr.getOpcode() == ISD::SHL) {
8799     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8800                                           N->getMemoryVT(), DCI);
8801     if (NewPtr) {
8802       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8803 
8804       NewOps[PtrIdx] = NewPtr;
8805       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8806     }
8807   }
8808 
8809   return SDValue();
8810 }
8811 
8812 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8813   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8814          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8815          (Opc == ISD::XOR && Val == 0);
8816 }
8817 
8818 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8819 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8820 // integer combine opportunities since most 64-bit operations are decomposed
8821 // this way.  TODO: We won't want this for SALU especially if it is an inline
8822 // immediate.
8823 SDValue SITargetLowering::splitBinaryBitConstantOp(
8824   DAGCombinerInfo &DCI,
8825   const SDLoc &SL,
8826   unsigned Opc, SDValue LHS,
8827   const ConstantSDNode *CRHS) const {
8828   uint64_t Val = CRHS->getZExtValue();
8829   uint32_t ValLo = Lo_32(Val);
8830   uint32_t ValHi = Hi_32(Val);
8831   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8832 
8833     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8834          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8835         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8836     // If we need to materialize a 64-bit immediate, it will be split up later
8837     // anyway. Avoid creating the harder to understand 64-bit immediate
8838     // materialization.
8839     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8840   }
8841 
8842   return SDValue();
8843 }
8844 
8845 // Returns true if argument is a boolean value which is not serialized into
8846 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8847 static bool isBoolSGPR(SDValue V) {
8848   if (V.getValueType() != MVT::i1)
8849     return false;
8850   switch (V.getOpcode()) {
8851   default: break;
8852   case ISD::SETCC:
8853   case ISD::AND:
8854   case ISD::OR:
8855   case ISD::XOR:
8856   case AMDGPUISD::FP_CLASS:
8857     return true;
8858   }
8859   return false;
8860 }
8861 
8862 // If a constant has all zeroes or all ones within each byte return it.
8863 // Otherwise return 0.
8864 static uint32_t getConstantPermuteMask(uint32_t C) {
8865   // 0xff for any zero byte in the mask
8866   uint32_t ZeroByteMask = 0;
8867   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8868   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8869   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8870   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8871   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8872   if ((NonZeroByteMask & C) != NonZeroByteMask)
8873     return 0; // Partial bytes selected.
8874   return C;
8875 }
8876 
8877 // Check if a node selects whole bytes from its operand 0 starting at a byte
8878 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8879 // or -1 if not succeeded.
8880 // Note byte select encoding:
8881 // value 0-3 selects corresponding source byte;
8882 // value 0xc selects zero;
8883 // value 0xff selects 0xff.
8884 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8885   assert(V.getValueSizeInBits() == 32);
8886 
8887   if (V.getNumOperands() != 2)
8888     return ~0;
8889 
8890   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8891   if (!N1)
8892     return ~0;
8893 
8894   uint32_t C = N1->getZExtValue();
8895 
8896   switch (V.getOpcode()) {
8897   default:
8898     break;
8899   case ISD::AND:
8900     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8901       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8902     }
8903     break;
8904 
8905   case ISD::OR:
8906     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8907       return (0x03020100 & ~ConstMask) | ConstMask;
8908     }
8909     break;
8910 
8911   case ISD::SHL:
8912     if (C % 8)
8913       return ~0;
8914 
8915     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8916 
8917   case ISD::SRL:
8918     if (C % 8)
8919       return ~0;
8920 
8921     return uint32_t(0x0c0c0c0c03020100ull >> C);
8922   }
8923 
8924   return ~0;
8925 }
8926 
8927 SDValue SITargetLowering::performAndCombine(SDNode *N,
8928                                             DAGCombinerInfo &DCI) const {
8929   if (DCI.isBeforeLegalize())
8930     return SDValue();
8931 
8932   SelectionDAG &DAG = DCI.DAG;
8933   EVT VT = N->getValueType(0);
8934   SDValue LHS = N->getOperand(0);
8935   SDValue RHS = N->getOperand(1);
8936 
8937 
8938   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8939   if (VT == MVT::i64 && CRHS) {
8940     if (SDValue Split
8941         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8942       return Split;
8943   }
8944 
8945   if (CRHS && VT == MVT::i32) {
8946     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8947     // nb = number of trailing zeroes in mask
8948     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8949     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8950     uint64_t Mask = CRHS->getZExtValue();
8951     unsigned Bits = countPopulation(Mask);
8952     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8953         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8954       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8955         unsigned Shift = CShift->getZExtValue();
8956         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8957         unsigned Offset = NB + Shift;
8958         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8959           SDLoc SL(N);
8960           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8961                                     LHS->getOperand(0),
8962                                     DAG.getConstant(Offset, SL, MVT::i32),
8963                                     DAG.getConstant(Bits, SL, MVT::i32));
8964           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8965           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8966                                     DAG.getValueType(NarrowVT));
8967           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8968                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8969           return Shl;
8970         }
8971       }
8972     }
8973 
8974     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8975     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8976         isa<ConstantSDNode>(LHS.getOperand(2))) {
8977       uint32_t Sel = getConstantPermuteMask(Mask);
8978       if (!Sel)
8979         return SDValue();
8980 
8981       // Select 0xc for all zero bytes
8982       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8983       SDLoc DL(N);
8984       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8985                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8986     }
8987   }
8988 
8989   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8990   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8991   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8992     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8993     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8994 
8995     SDValue X = LHS.getOperand(0);
8996     SDValue Y = RHS.getOperand(0);
8997     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8998       return SDValue();
8999 
9000     if (LCC == ISD::SETO) {
9001       if (X != LHS.getOperand(1))
9002         return SDValue();
9003 
9004       if (RCC == ISD::SETUNE) {
9005         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9006         if (!C1 || !C1->isInfinity() || C1->isNegative())
9007           return SDValue();
9008 
9009         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9010                               SIInstrFlags::N_SUBNORMAL |
9011                               SIInstrFlags::N_ZERO |
9012                               SIInstrFlags::P_ZERO |
9013                               SIInstrFlags::P_SUBNORMAL |
9014                               SIInstrFlags::P_NORMAL;
9015 
9016         static_assert(((~(SIInstrFlags::S_NAN |
9017                           SIInstrFlags::Q_NAN |
9018                           SIInstrFlags::N_INFINITY |
9019                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9020                       "mask not equal");
9021 
9022         SDLoc DL(N);
9023         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9024                            X, DAG.getConstant(Mask, DL, MVT::i32));
9025       }
9026     }
9027   }
9028 
9029   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9030     std::swap(LHS, RHS);
9031 
9032   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9033       RHS.hasOneUse()) {
9034     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9035     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9036     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9037     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9038     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9039         (RHS.getOperand(0) == LHS.getOperand(0) &&
9040          LHS.getOperand(0) == LHS.getOperand(1))) {
9041       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9042       unsigned NewMask = LCC == ISD::SETO ?
9043         Mask->getZExtValue() & ~OrdMask :
9044         Mask->getZExtValue() & OrdMask;
9045 
9046       SDLoc DL(N);
9047       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9048                          DAG.getConstant(NewMask, DL, MVT::i32));
9049     }
9050   }
9051 
9052   if (VT == MVT::i32 &&
9053       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9054     // and x, (sext cc from i1) => select cc, x, 0
9055     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9056       std::swap(LHS, RHS);
9057     if (isBoolSGPR(RHS.getOperand(0)))
9058       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9059                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9060   }
9061 
9062   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9063   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9064   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9065       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9066     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9067     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9068     if (LHSMask != ~0u && RHSMask != ~0u) {
9069       // Canonicalize the expression in an attempt to have fewer unique masks
9070       // and therefore fewer registers used to hold the masks.
9071       if (LHSMask > RHSMask) {
9072         std::swap(LHSMask, RHSMask);
9073         std::swap(LHS, RHS);
9074       }
9075 
9076       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9077       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9078       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9079       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9080 
9081       // Check of we need to combine values from two sources within a byte.
9082       if (!(LHSUsedLanes & RHSUsedLanes) &&
9083           // If we select high and lower word keep it for SDWA.
9084           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9085           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9086         // Each byte in each mask is either selector mask 0-3, or has higher
9087         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9088         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9089         // mask which is not 0xff wins. By anding both masks we have a correct
9090         // result except that 0x0c shall be corrected to give 0x0c only.
9091         uint32_t Mask = LHSMask & RHSMask;
9092         for (unsigned I = 0; I < 32; I += 8) {
9093           uint32_t ByteSel = 0xff << I;
9094           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9095             Mask &= (0x0c << I) & 0xffffffff;
9096         }
9097 
9098         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9099         // or 0x0c.
9100         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9101         SDLoc DL(N);
9102 
9103         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9104                            LHS.getOperand(0), RHS.getOperand(0),
9105                            DAG.getConstant(Sel, DL, MVT::i32));
9106       }
9107     }
9108   }
9109 
9110   return SDValue();
9111 }
9112 
9113 SDValue SITargetLowering::performOrCombine(SDNode *N,
9114                                            DAGCombinerInfo &DCI) const {
9115   SelectionDAG &DAG = DCI.DAG;
9116   SDValue LHS = N->getOperand(0);
9117   SDValue RHS = N->getOperand(1);
9118 
9119   EVT VT = N->getValueType(0);
9120   if (VT == MVT::i1) {
9121     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9122     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9123         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9124       SDValue Src = LHS.getOperand(0);
9125       if (Src != RHS.getOperand(0))
9126         return SDValue();
9127 
9128       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9129       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9130       if (!CLHS || !CRHS)
9131         return SDValue();
9132 
9133       // Only 10 bits are used.
9134       static const uint32_t MaxMask = 0x3ff;
9135 
9136       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9137       SDLoc DL(N);
9138       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9139                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9140     }
9141 
9142     return SDValue();
9143   }
9144 
9145   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9146   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9147       LHS.getOpcode() == AMDGPUISD::PERM &&
9148       isa<ConstantSDNode>(LHS.getOperand(2))) {
9149     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9150     if (!Sel)
9151       return SDValue();
9152 
9153     Sel |= LHS.getConstantOperandVal(2);
9154     SDLoc DL(N);
9155     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9156                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9157   }
9158 
9159   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9160   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9161   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9162       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9163     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9164     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9165     if (LHSMask != ~0u && RHSMask != ~0u) {
9166       // Canonicalize the expression in an attempt to have fewer unique masks
9167       // and therefore fewer registers used to hold the masks.
9168       if (LHSMask > RHSMask) {
9169         std::swap(LHSMask, RHSMask);
9170         std::swap(LHS, RHS);
9171       }
9172 
9173       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9174       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9175       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9176       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9177 
9178       // Check of we need to combine values from two sources within a byte.
9179       if (!(LHSUsedLanes & RHSUsedLanes) &&
9180           // If we select high and lower word keep it for SDWA.
9181           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9182           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9183         // Kill zero bytes selected by other mask. Zero value is 0xc.
9184         LHSMask &= ~RHSUsedLanes;
9185         RHSMask &= ~LHSUsedLanes;
9186         // Add 4 to each active LHS lane
9187         LHSMask |= LHSUsedLanes & 0x04040404;
9188         // Combine masks
9189         uint32_t Sel = LHSMask | RHSMask;
9190         SDLoc DL(N);
9191 
9192         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9193                            LHS.getOperand(0), RHS.getOperand(0),
9194                            DAG.getConstant(Sel, DL, MVT::i32));
9195       }
9196     }
9197   }
9198 
9199   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9200     return SDValue();
9201 
9202   // TODO: This could be a generic combine with a predicate for extracting the
9203   // high half of an integer being free.
9204 
9205   // (or i64:x, (zero_extend i32:y)) ->
9206   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9207   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9208       RHS.getOpcode() != ISD::ZERO_EXTEND)
9209     std::swap(LHS, RHS);
9210 
9211   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9212     SDValue ExtSrc = RHS.getOperand(0);
9213     EVT SrcVT = ExtSrc.getValueType();
9214     if (SrcVT == MVT::i32) {
9215       SDLoc SL(N);
9216       SDValue LowLHS, HiBits;
9217       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9218       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9219 
9220       DCI.AddToWorklist(LowOr.getNode());
9221       DCI.AddToWorklist(HiBits.getNode());
9222 
9223       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9224                                 LowOr, HiBits);
9225       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9226     }
9227   }
9228 
9229   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9230   if (CRHS) {
9231     if (SDValue Split
9232           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9233       return Split;
9234   }
9235 
9236   return SDValue();
9237 }
9238 
9239 SDValue SITargetLowering::performXorCombine(SDNode *N,
9240                                             DAGCombinerInfo &DCI) const {
9241   EVT VT = N->getValueType(0);
9242   if (VT != MVT::i64)
9243     return SDValue();
9244 
9245   SDValue LHS = N->getOperand(0);
9246   SDValue RHS = N->getOperand(1);
9247 
9248   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9249   if (CRHS) {
9250     if (SDValue Split
9251           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9252       return Split;
9253   }
9254 
9255   return SDValue();
9256 }
9257 
9258 // Instructions that will be lowered with a final instruction that zeros the
9259 // high result bits.
9260 // XXX - probably only need to list legal operations.
9261 static bool fp16SrcZerosHighBits(unsigned Opc) {
9262   switch (Opc) {
9263   case ISD::FADD:
9264   case ISD::FSUB:
9265   case ISD::FMUL:
9266   case ISD::FDIV:
9267   case ISD::FREM:
9268   case ISD::FMA:
9269   case ISD::FMAD:
9270   case ISD::FCANONICALIZE:
9271   case ISD::FP_ROUND:
9272   case ISD::UINT_TO_FP:
9273   case ISD::SINT_TO_FP:
9274   case ISD::FABS:
9275     // Fabs is lowered to a bit operation, but it's an and which will clear the
9276     // high bits anyway.
9277   case ISD::FSQRT:
9278   case ISD::FSIN:
9279   case ISD::FCOS:
9280   case ISD::FPOWI:
9281   case ISD::FPOW:
9282   case ISD::FLOG:
9283   case ISD::FLOG2:
9284   case ISD::FLOG10:
9285   case ISD::FEXP:
9286   case ISD::FEXP2:
9287   case ISD::FCEIL:
9288   case ISD::FTRUNC:
9289   case ISD::FRINT:
9290   case ISD::FNEARBYINT:
9291   case ISD::FROUND:
9292   case ISD::FFLOOR:
9293   case ISD::FMINNUM:
9294   case ISD::FMAXNUM:
9295   case AMDGPUISD::FRACT:
9296   case AMDGPUISD::CLAMP:
9297   case AMDGPUISD::COS_HW:
9298   case AMDGPUISD::SIN_HW:
9299   case AMDGPUISD::FMIN3:
9300   case AMDGPUISD::FMAX3:
9301   case AMDGPUISD::FMED3:
9302   case AMDGPUISD::FMAD_FTZ:
9303   case AMDGPUISD::RCP:
9304   case AMDGPUISD::RSQ:
9305   case AMDGPUISD::RCP_IFLAG:
9306   case AMDGPUISD::LDEXP:
9307     return true;
9308   default:
9309     // fcopysign, select and others may be lowered to 32-bit bit operations
9310     // which don't zero the high bits.
9311     return false;
9312   }
9313 }
9314 
9315 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9316                                                    DAGCombinerInfo &DCI) const {
9317   if (!Subtarget->has16BitInsts() ||
9318       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9319     return SDValue();
9320 
9321   EVT VT = N->getValueType(0);
9322   if (VT != MVT::i32)
9323     return SDValue();
9324 
9325   SDValue Src = N->getOperand(0);
9326   if (Src.getValueType() != MVT::i16)
9327     return SDValue();
9328 
9329   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9330   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9331   if (Src.getOpcode() == ISD::BITCAST) {
9332     SDValue BCSrc = Src.getOperand(0);
9333     if (BCSrc.getValueType() == MVT::f16 &&
9334         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9335       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9336   }
9337 
9338   return SDValue();
9339 }
9340 
9341 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9342                                                         DAGCombinerInfo &DCI)
9343                                                         const {
9344   SDValue Src = N->getOperand(0);
9345   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9346 
9347   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9348       VTSign->getVT() == MVT::i8) ||
9349       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9350       VTSign->getVT() == MVT::i16)) &&
9351       Src.hasOneUse()) {
9352     auto *M = cast<MemSDNode>(Src);
9353     SDValue Ops[] = {
9354       Src.getOperand(0), // Chain
9355       Src.getOperand(1), // rsrc
9356       Src.getOperand(2), // vindex
9357       Src.getOperand(3), // voffset
9358       Src.getOperand(4), // soffset
9359       Src.getOperand(5), // offset
9360       Src.getOperand(6),
9361       Src.getOperand(7)
9362     };
9363     // replace with BUFFER_LOAD_BYTE/SHORT
9364     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9365                                          Src.getOperand(0).getValueType());
9366     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9367                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9368     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9369                                                           ResList,
9370                                                           Ops, M->getMemoryVT(),
9371                                                           M->getMemOperand());
9372     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9373                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9374   }
9375   return SDValue();
9376 }
9377 
9378 SDValue SITargetLowering::performClassCombine(SDNode *N,
9379                                               DAGCombinerInfo &DCI) const {
9380   SelectionDAG &DAG = DCI.DAG;
9381   SDValue Mask = N->getOperand(1);
9382 
9383   // fp_class x, 0 -> false
9384   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9385     if (CMask->isNullValue())
9386       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9387   }
9388 
9389   if (N->getOperand(0).isUndef())
9390     return DAG.getUNDEF(MVT::i1);
9391 
9392   return SDValue();
9393 }
9394 
9395 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9396                                             DAGCombinerInfo &DCI) const {
9397   EVT VT = N->getValueType(0);
9398   SDValue N0 = N->getOperand(0);
9399 
9400   if (N0.isUndef())
9401     return N0;
9402 
9403   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9404                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9405     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9406                            N->getFlags());
9407   }
9408 
9409   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9410     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9411                            N0.getOperand(0), N->getFlags());
9412   }
9413 
9414   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9415 }
9416 
9417 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9418                                        unsigned MaxDepth) const {
9419   unsigned Opcode = Op.getOpcode();
9420   if (Opcode == ISD::FCANONICALIZE)
9421     return true;
9422 
9423   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9424     auto F = CFP->getValueAPF();
9425     if (F.isNaN() && F.isSignaling())
9426       return false;
9427     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9428   }
9429 
9430   // If source is a result of another standard FP operation it is already in
9431   // canonical form.
9432   if (MaxDepth == 0)
9433     return false;
9434 
9435   switch (Opcode) {
9436   // These will flush denorms if required.
9437   case ISD::FADD:
9438   case ISD::FSUB:
9439   case ISD::FMUL:
9440   case ISD::FCEIL:
9441   case ISD::FFLOOR:
9442   case ISD::FMA:
9443   case ISD::FMAD:
9444   case ISD::FSQRT:
9445   case ISD::FDIV:
9446   case ISD::FREM:
9447   case ISD::FP_ROUND:
9448   case ISD::FP_EXTEND:
9449   case AMDGPUISD::FMUL_LEGACY:
9450   case AMDGPUISD::FMAD_FTZ:
9451   case AMDGPUISD::RCP:
9452   case AMDGPUISD::RSQ:
9453   case AMDGPUISD::RSQ_CLAMP:
9454   case AMDGPUISD::RCP_LEGACY:
9455   case AMDGPUISD::RCP_IFLAG:
9456   case AMDGPUISD::DIV_SCALE:
9457   case AMDGPUISD::DIV_FMAS:
9458   case AMDGPUISD::DIV_FIXUP:
9459   case AMDGPUISD::FRACT:
9460   case AMDGPUISD::LDEXP:
9461   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9462   case AMDGPUISD::CVT_F32_UBYTE0:
9463   case AMDGPUISD::CVT_F32_UBYTE1:
9464   case AMDGPUISD::CVT_F32_UBYTE2:
9465   case AMDGPUISD::CVT_F32_UBYTE3:
9466     return true;
9467 
9468   // It can/will be lowered or combined as a bit operation.
9469   // Need to check their input recursively to handle.
9470   case ISD::FNEG:
9471   case ISD::FABS:
9472   case ISD::FCOPYSIGN:
9473     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9474 
9475   case ISD::FSIN:
9476   case ISD::FCOS:
9477   case ISD::FSINCOS:
9478     return Op.getValueType().getScalarType() != MVT::f16;
9479 
9480   case ISD::FMINNUM:
9481   case ISD::FMAXNUM:
9482   case ISD::FMINNUM_IEEE:
9483   case ISD::FMAXNUM_IEEE:
9484   case AMDGPUISD::CLAMP:
9485   case AMDGPUISD::FMED3:
9486   case AMDGPUISD::FMAX3:
9487   case AMDGPUISD::FMIN3: {
9488     // FIXME: Shouldn't treat the generic operations different based these.
9489     // However, we aren't really required to flush the result from
9490     // minnum/maxnum..
9491 
9492     // snans will be quieted, so we only need to worry about denormals.
9493     if (Subtarget->supportsMinMaxDenormModes() ||
9494         denormalsEnabledForType(DAG, Op.getValueType()))
9495       return true;
9496 
9497     // Flushing may be required.
9498     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9499     // targets need to check their input recursively.
9500 
9501     // FIXME: Does this apply with clamp? It's implemented with max.
9502     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9503       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9504         return false;
9505     }
9506 
9507     return true;
9508   }
9509   case ISD::SELECT: {
9510     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9511            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9512   }
9513   case ISD::BUILD_VECTOR: {
9514     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9515       SDValue SrcOp = Op.getOperand(i);
9516       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9517         return false;
9518     }
9519 
9520     return true;
9521   }
9522   case ISD::EXTRACT_VECTOR_ELT:
9523   case ISD::EXTRACT_SUBVECTOR: {
9524     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9525   }
9526   case ISD::INSERT_VECTOR_ELT: {
9527     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9528            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9529   }
9530   case ISD::UNDEF:
9531     // Could be anything.
9532     return false;
9533 
9534   case ISD::BITCAST: {
9535     // Hack round the mess we make when legalizing extract_vector_elt
9536     SDValue Src = Op.getOperand(0);
9537     if (Src.getValueType() == MVT::i16 &&
9538         Src.getOpcode() == ISD::TRUNCATE) {
9539       SDValue TruncSrc = Src.getOperand(0);
9540       if (TruncSrc.getValueType() == MVT::i32 &&
9541           TruncSrc.getOpcode() == ISD::BITCAST &&
9542           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9543         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9544       }
9545     }
9546 
9547     return false;
9548   }
9549   case ISD::INTRINSIC_WO_CHAIN: {
9550     unsigned IntrinsicID
9551       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9552     // TODO: Handle more intrinsics
9553     switch (IntrinsicID) {
9554     case Intrinsic::amdgcn_cvt_pkrtz:
9555     case Intrinsic::amdgcn_cubeid:
9556     case Intrinsic::amdgcn_frexp_mant:
9557     case Intrinsic::amdgcn_fdot2:
9558     case Intrinsic::amdgcn_rcp:
9559     case Intrinsic::amdgcn_rsq:
9560     case Intrinsic::amdgcn_rsq_clamp:
9561     case Intrinsic::amdgcn_rcp_legacy:
9562     case Intrinsic::amdgcn_rsq_legacy:
9563     case Intrinsic::amdgcn_trig_preop:
9564       return true;
9565     default:
9566       break;
9567     }
9568 
9569     LLVM_FALLTHROUGH;
9570   }
9571   default:
9572     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9573            DAG.isKnownNeverSNaN(Op);
9574   }
9575 
9576   llvm_unreachable("invalid operation");
9577 }
9578 
9579 // Constant fold canonicalize.
9580 SDValue SITargetLowering::getCanonicalConstantFP(
9581   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9582   // Flush denormals to 0 if not enabled.
9583   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9584     return DAG.getConstantFP(0.0, SL, VT);
9585 
9586   if (C.isNaN()) {
9587     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9588     if (C.isSignaling()) {
9589       // Quiet a signaling NaN.
9590       // FIXME: Is this supposed to preserve payload bits?
9591       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9592     }
9593 
9594     // Make sure it is the canonical NaN bitpattern.
9595     //
9596     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9597     // immediate?
9598     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9599       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9600   }
9601 
9602   // Already canonical.
9603   return DAG.getConstantFP(C, SL, VT);
9604 }
9605 
9606 static bool vectorEltWillFoldAway(SDValue Op) {
9607   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9608 }
9609 
9610 SDValue SITargetLowering::performFCanonicalizeCombine(
9611   SDNode *N,
9612   DAGCombinerInfo &DCI) const {
9613   SelectionDAG &DAG = DCI.DAG;
9614   SDValue N0 = N->getOperand(0);
9615   EVT VT = N->getValueType(0);
9616 
9617   // fcanonicalize undef -> qnan
9618   if (N0.isUndef()) {
9619     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9620     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9621   }
9622 
9623   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9624     EVT VT = N->getValueType(0);
9625     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9626   }
9627 
9628   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9629   //                                                   (fcanonicalize k)
9630   //
9631   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9632 
9633   // TODO: This could be better with wider vectors that will be split to v2f16,
9634   // and to consider uses since there aren't that many packed operations.
9635   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9636       isTypeLegal(MVT::v2f16)) {
9637     SDLoc SL(N);
9638     SDValue NewElts[2];
9639     SDValue Lo = N0.getOperand(0);
9640     SDValue Hi = N0.getOperand(1);
9641     EVT EltVT = Lo.getValueType();
9642 
9643     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9644       for (unsigned I = 0; I != 2; ++I) {
9645         SDValue Op = N0.getOperand(I);
9646         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9647           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9648                                               CFP->getValueAPF());
9649         } else if (Op.isUndef()) {
9650           // Handled below based on what the other operand is.
9651           NewElts[I] = Op;
9652         } else {
9653           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9654         }
9655       }
9656 
9657       // If one half is undef, and one is constant, perfer a splat vector rather
9658       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9659       // cheaper to use and may be free with a packed operation.
9660       if (NewElts[0].isUndef()) {
9661         if (isa<ConstantFPSDNode>(NewElts[1]))
9662           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9663             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9664       }
9665 
9666       if (NewElts[1].isUndef()) {
9667         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9668           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9669       }
9670 
9671       return DAG.getBuildVector(VT, SL, NewElts);
9672     }
9673   }
9674 
9675   unsigned SrcOpc = N0.getOpcode();
9676 
9677   // If it's free to do so, push canonicalizes further up the source, which may
9678   // find a canonical source.
9679   //
9680   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9681   // sNaNs.
9682   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9683     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9684     if (CRHS && N0.hasOneUse()) {
9685       SDLoc SL(N);
9686       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9687                                    N0.getOperand(0));
9688       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9689       DCI.AddToWorklist(Canon0.getNode());
9690 
9691       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9692     }
9693   }
9694 
9695   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9696 }
9697 
9698 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9699   switch (Opc) {
9700   case ISD::FMAXNUM:
9701   case ISD::FMAXNUM_IEEE:
9702     return AMDGPUISD::FMAX3;
9703   case ISD::SMAX:
9704     return AMDGPUISD::SMAX3;
9705   case ISD::UMAX:
9706     return AMDGPUISD::UMAX3;
9707   case ISD::FMINNUM:
9708   case ISD::FMINNUM_IEEE:
9709     return AMDGPUISD::FMIN3;
9710   case ISD::SMIN:
9711     return AMDGPUISD::SMIN3;
9712   case ISD::UMIN:
9713     return AMDGPUISD::UMIN3;
9714   default:
9715     llvm_unreachable("Not a min/max opcode");
9716   }
9717 }
9718 
9719 SDValue SITargetLowering::performIntMed3ImmCombine(
9720   SelectionDAG &DAG, const SDLoc &SL,
9721   SDValue Op0, SDValue Op1, bool Signed) const {
9722   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9723   if (!K1)
9724     return SDValue();
9725 
9726   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9727   if (!K0)
9728     return SDValue();
9729 
9730   if (Signed) {
9731     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9732       return SDValue();
9733   } else {
9734     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9735       return SDValue();
9736   }
9737 
9738   EVT VT = K0->getValueType(0);
9739   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9740   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9741     return DAG.getNode(Med3Opc, SL, VT,
9742                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9743   }
9744 
9745   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9746   MVT NVT = MVT::i32;
9747   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9748 
9749   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9750   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9751   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9752 
9753   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9754   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9755 }
9756 
9757 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9758   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9759     return C;
9760 
9761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9762     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9763       return C;
9764   }
9765 
9766   return nullptr;
9767 }
9768 
9769 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9770                                                   const SDLoc &SL,
9771                                                   SDValue Op0,
9772                                                   SDValue Op1) const {
9773   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9774   if (!K1)
9775     return SDValue();
9776 
9777   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9778   if (!K0)
9779     return SDValue();
9780 
9781   // Ordered >= (although NaN inputs should have folded away by now).
9782   if (K0->getValueAPF() > K1->getValueAPF())
9783     return SDValue();
9784 
9785   const MachineFunction &MF = DAG.getMachineFunction();
9786   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9787 
9788   // TODO: Check IEEE bit enabled?
9789   EVT VT = Op0.getValueType();
9790   if (Info->getMode().DX10Clamp) {
9791     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9792     // hardware fmed3 behavior converting to a min.
9793     // FIXME: Should this be allowing -0.0?
9794     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9795       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9796   }
9797 
9798   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9799   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9800     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9801     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9802     // then give the other result, which is different from med3 with a NaN
9803     // input.
9804     SDValue Var = Op0.getOperand(0);
9805     if (!DAG.isKnownNeverSNaN(Var))
9806       return SDValue();
9807 
9808     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9809 
9810     if ((!K0->hasOneUse() ||
9811          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9812         (!K1->hasOneUse() ||
9813          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9814       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9815                          Var, SDValue(K0, 0), SDValue(K1, 0));
9816     }
9817   }
9818 
9819   return SDValue();
9820 }
9821 
9822 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9823                                                DAGCombinerInfo &DCI) const {
9824   SelectionDAG &DAG = DCI.DAG;
9825 
9826   EVT VT = N->getValueType(0);
9827   unsigned Opc = N->getOpcode();
9828   SDValue Op0 = N->getOperand(0);
9829   SDValue Op1 = N->getOperand(1);
9830 
9831   // Only do this if the inner op has one use since this will just increases
9832   // register pressure for no benefit.
9833 
9834   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9835       !VT.isVector() &&
9836       (VT == MVT::i32 || VT == MVT::f32 ||
9837        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9838     // max(max(a, b), c) -> max3(a, b, c)
9839     // min(min(a, b), c) -> min3(a, b, c)
9840     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9841       SDLoc DL(N);
9842       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9843                          DL,
9844                          N->getValueType(0),
9845                          Op0.getOperand(0),
9846                          Op0.getOperand(1),
9847                          Op1);
9848     }
9849 
9850     // Try commuted.
9851     // max(a, max(b, c)) -> max3(a, b, c)
9852     // min(a, min(b, c)) -> min3(a, b, c)
9853     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9854       SDLoc DL(N);
9855       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9856                          DL,
9857                          N->getValueType(0),
9858                          Op0,
9859                          Op1.getOperand(0),
9860                          Op1.getOperand(1));
9861     }
9862   }
9863 
9864   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9865   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9866     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9867       return Med3;
9868   }
9869 
9870   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9871     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9872       return Med3;
9873   }
9874 
9875   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9876   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9877        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9878        (Opc == AMDGPUISD::FMIN_LEGACY &&
9879         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9880       (VT == MVT::f32 || VT == MVT::f64 ||
9881        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9882        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9883       Op0.hasOneUse()) {
9884     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9885       return Res;
9886   }
9887 
9888   return SDValue();
9889 }
9890 
9891 static bool isClampZeroToOne(SDValue A, SDValue B) {
9892   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9893     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9894       // FIXME: Should this be allowing -0.0?
9895       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9896              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9897     }
9898   }
9899 
9900   return false;
9901 }
9902 
9903 // FIXME: Should only worry about snans for version with chain.
9904 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9905                                               DAGCombinerInfo &DCI) const {
9906   EVT VT = N->getValueType(0);
9907   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9908   // NaNs. With a NaN input, the order of the operands may change the result.
9909 
9910   SelectionDAG &DAG = DCI.DAG;
9911   SDLoc SL(N);
9912 
9913   SDValue Src0 = N->getOperand(0);
9914   SDValue Src1 = N->getOperand(1);
9915   SDValue Src2 = N->getOperand(2);
9916 
9917   if (isClampZeroToOne(Src0, Src1)) {
9918     // const_a, const_b, x -> clamp is safe in all cases including signaling
9919     // nans.
9920     // FIXME: Should this be allowing -0.0?
9921     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9922   }
9923 
9924   const MachineFunction &MF = DAG.getMachineFunction();
9925   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9926 
9927   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9928   // handling no dx10-clamp?
9929   if (Info->getMode().DX10Clamp) {
9930     // If NaNs is clamped to 0, we are free to reorder the inputs.
9931 
9932     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9933       std::swap(Src0, Src1);
9934 
9935     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9936       std::swap(Src1, Src2);
9937 
9938     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9939       std::swap(Src0, Src1);
9940 
9941     if (isClampZeroToOne(Src1, Src2))
9942       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9943   }
9944 
9945   return SDValue();
9946 }
9947 
9948 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9949                                                  DAGCombinerInfo &DCI) const {
9950   SDValue Src0 = N->getOperand(0);
9951   SDValue Src1 = N->getOperand(1);
9952   if (Src0.isUndef() && Src1.isUndef())
9953     return DCI.DAG.getUNDEF(N->getValueType(0));
9954   return SDValue();
9955 }
9956 
9957 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9958 // expanded into a set of cmp/select instructions.
9959 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9960                                                 unsigned NumElem,
9961                                                 bool IsDivergentIdx) {
9962   if (UseDivergentRegisterIndexing)
9963     return false;
9964 
9965   unsigned VecSize = EltSize * NumElem;
9966 
9967   // Sub-dword vectors of size 2 dword or less have better implementation.
9968   if (VecSize <= 64 && EltSize < 32)
9969     return false;
9970 
9971   // Always expand the rest of sub-dword instructions, otherwise it will be
9972   // lowered via memory.
9973   if (EltSize < 32)
9974     return true;
9975 
9976   // Always do this if var-idx is divergent, otherwise it will become a loop.
9977   if (IsDivergentIdx)
9978     return true;
9979 
9980   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9981   unsigned NumInsts = NumElem /* Number of compares */ +
9982                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9983   return NumInsts <= 16;
9984 }
9985 
9986 static bool shouldExpandVectorDynExt(SDNode *N) {
9987   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9988   if (isa<ConstantSDNode>(Idx))
9989     return false;
9990 
9991   SDValue Vec = N->getOperand(0);
9992   EVT VecVT = Vec.getValueType();
9993   EVT EltVT = VecVT.getVectorElementType();
9994   unsigned EltSize = EltVT.getSizeInBits();
9995   unsigned NumElem = VecVT.getVectorNumElements();
9996 
9997   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9998                                                     Idx->isDivergent());
9999 }
10000 
10001 SDValue SITargetLowering::performExtractVectorEltCombine(
10002   SDNode *N, DAGCombinerInfo &DCI) const {
10003   SDValue Vec = N->getOperand(0);
10004   SelectionDAG &DAG = DCI.DAG;
10005 
10006   EVT VecVT = Vec.getValueType();
10007   EVT EltVT = VecVT.getVectorElementType();
10008 
10009   if ((Vec.getOpcode() == ISD::FNEG ||
10010        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10011     SDLoc SL(N);
10012     EVT EltVT = N->getValueType(0);
10013     SDValue Idx = N->getOperand(1);
10014     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10015                               Vec.getOperand(0), Idx);
10016     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10017   }
10018 
10019   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10020   //    =>
10021   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10022   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10023   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10024   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10025     SDLoc SL(N);
10026     EVT EltVT = N->getValueType(0);
10027     SDValue Idx = N->getOperand(1);
10028     unsigned Opc = Vec.getOpcode();
10029 
10030     switch(Opc) {
10031     default:
10032       break;
10033       // TODO: Support other binary operations.
10034     case ISD::FADD:
10035     case ISD::FSUB:
10036     case ISD::FMUL:
10037     case ISD::ADD:
10038     case ISD::UMIN:
10039     case ISD::UMAX:
10040     case ISD::SMIN:
10041     case ISD::SMAX:
10042     case ISD::FMAXNUM:
10043     case ISD::FMINNUM:
10044     case ISD::FMAXNUM_IEEE:
10045     case ISD::FMINNUM_IEEE: {
10046       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10047                                  Vec.getOperand(0), Idx);
10048       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10049                                  Vec.getOperand(1), Idx);
10050 
10051       DCI.AddToWorklist(Elt0.getNode());
10052       DCI.AddToWorklist(Elt1.getNode());
10053       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10054     }
10055     }
10056   }
10057 
10058   unsigned VecSize = VecVT.getSizeInBits();
10059   unsigned EltSize = EltVT.getSizeInBits();
10060 
10061   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10062   if (::shouldExpandVectorDynExt(N)) {
10063     SDLoc SL(N);
10064     SDValue Idx = N->getOperand(1);
10065     SDValue V;
10066     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10067       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10068       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10069       if (I == 0)
10070         V = Elt;
10071       else
10072         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10073     }
10074     return V;
10075   }
10076 
10077   if (!DCI.isBeforeLegalize())
10078     return SDValue();
10079 
10080   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10081   // elements. This exposes more load reduction opportunities by replacing
10082   // multiple small extract_vector_elements with a single 32-bit extract.
10083   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10084   if (isa<MemSDNode>(Vec) &&
10085       EltSize <= 16 &&
10086       EltVT.isByteSized() &&
10087       VecSize > 32 &&
10088       VecSize % 32 == 0 &&
10089       Idx) {
10090     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10091 
10092     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10093     unsigned EltIdx = BitIndex / 32;
10094     unsigned LeftoverBitIdx = BitIndex % 32;
10095     SDLoc SL(N);
10096 
10097     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10098     DCI.AddToWorklist(Cast.getNode());
10099 
10100     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10101                               DAG.getConstant(EltIdx, SL, MVT::i32));
10102     DCI.AddToWorklist(Elt.getNode());
10103     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10104                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10105     DCI.AddToWorklist(Srl.getNode());
10106 
10107     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10108     DCI.AddToWorklist(Trunc.getNode());
10109     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10110   }
10111 
10112   return SDValue();
10113 }
10114 
10115 SDValue
10116 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10117                                                 DAGCombinerInfo &DCI) const {
10118   SDValue Vec = N->getOperand(0);
10119   SDValue Idx = N->getOperand(2);
10120   EVT VecVT = Vec.getValueType();
10121   EVT EltVT = VecVT.getVectorElementType();
10122 
10123   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10124   // => BUILD_VECTOR n x select (e, const-idx)
10125   if (!::shouldExpandVectorDynExt(N))
10126     return SDValue();
10127 
10128   SelectionDAG &DAG = DCI.DAG;
10129   SDLoc SL(N);
10130   SDValue Ins = N->getOperand(1);
10131   EVT IdxVT = Idx.getValueType();
10132 
10133   SmallVector<SDValue, 16> Ops;
10134   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10135     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10136     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10137     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10138     Ops.push_back(V);
10139   }
10140 
10141   return DAG.getBuildVector(VecVT, SL, Ops);
10142 }
10143 
10144 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10145                                           const SDNode *N0,
10146                                           const SDNode *N1) const {
10147   EVT VT = N0->getValueType(0);
10148 
10149   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10150   // support denormals ever.
10151   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10152        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10153         getSubtarget()->hasMadF16())) &&
10154        isOperationLegal(ISD::FMAD, VT))
10155     return ISD::FMAD;
10156 
10157   const TargetOptions &Options = DAG.getTarget().Options;
10158   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10159        (N0->getFlags().hasAllowContract() &&
10160         N1->getFlags().hasAllowContract())) &&
10161       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10162     return ISD::FMA;
10163   }
10164 
10165   return 0;
10166 }
10167 
10168 // For a reassociatable opcode perform:
10169 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10170 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10171                                                SelectionDAG &DAG) const {
10172   EVT VT = N->getValueType(0);
10173   if (VT != MVT::i32 && VT != MVT::i64)
10174     return SDValue();
10175 
10176   unsigned Opc = N->getOpcode();
10177   SDValue Op0 = N->getOperand(0);
10178   SDValue Op1 = N->getOperand(1);
10179 
10180   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10181     return SDValue();
10182 
10183   if (Op0->isDivergent())
10184     std::swap(Op0, Op1);
10185 
10186   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10187     return SDValue();
10188 
10189   SDValue Op2 = Op1.getOperand(1);
10190   Op1 = Op1.getOperand(0);
10191   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10192     return SDValue();
10193 
10194   if (Op1->isDivergent())
10195     std::swap(Op1, Op2);
10196 
10197   // If either operand is constant this will conflict with
10198   // DAGCombiner::ReassociateOps().
10199   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10200       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10201     return SDValue();
10202 
10203   SDLoc SL(N);
10204   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10205   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10206 }
10207 
10208 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10209                            EVT VT,
10210                            SDValue N0, SDValue N1, SDValue N2,
10211                            bool Signed) {
10212   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10213   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10214   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10215   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10216 }
10217 
10218 SDValue SITargetLowering::performAddCombine(SDNode *N,
10219                                             DAGCombinerInfo &DCI) const {
10220   SelectionDAG &DAG = DCI.DAG;
10221   EVT VT = N->getValueType(0);
10222   SDLoc SL(N);
10223   SDValue LHS = N->getOperand(0);
10224   SDValue RHS = N->getOperand(1);
10225 
10226   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10227       && Subtarget->hasMad64_32() &&
10228       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10229       VT.getScalarSizeInBits() <= 64) {
10230     if (LHS.getOpcode() != ISD::MUL)
10231       std::swap(LHS, RHS);
10232 
10233     SDValue MulLHS = LHS.getOperand(0);
10234     SDValue MulRHS = LHS.getOperand(1);
10235     SDValue AddRHS = RHS;
10236 
10237     // TODO: Maybe restrict if SGPR inputs.
10238     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10239         numBitsUnsigned(MulRHS, DAG) <= 32) {
10240       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10241       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10242       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10243       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10244     }
10245 
10246     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10247       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10248       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10249       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10250       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10251     }
10252 
10253     return SDValue();
10254   }
10255 
10256   if (SDValue V = reassociateScalarOps(N, DAG)) {
10257     return V;
10258   }
10259 
10260   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10261     return SDValue();
10262 
10263   // add x, zext (setcc) => addcarry x, 0, setcc
10264   // add x, sext (setcc) => subcarry x, 0, setcc
10265   unsigned Opc = LHS.getOpcode();
10266   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10267       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10268     std::swap(RHS, LHS);
10269 
10270   Opc = RHS.getOpcode();
10271   switch (Opc) {
10272   default: break;
10273   case ISD::ZERO_EXTEND:
10274   case ISD::SIGN_EXTEND:
10275   case ISD::ANY_EXTEND: {
10276     auto Cond = RHS.getOperand(0);
10277     // If this won't be a real VOPC output, we would still need to insert an
10278     // extra instruction anyway.
10279     if (!isBoolSGPR(Cond))
10280       break;
10281     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10282     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10283     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10284     return DAG.getNode(Opc, SL, VTList, Args);
10285   }
10286   case ISD::ADDCARRY: {
10287     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10288     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10289     if (!C || C->getZExtValue() != 0) break;
10290     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10291     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10292   }
10293   }
10294   return SDValue();
10295 }
10296 
10297 SDValue SITargetLowering::performSubCombine(SDNode *N,
10298                                             DAGCombinerInfo &DCI) const {
10299   SelectionDAG &DAG = DCI.DAG;
10300   EVT VT = N->getValueType(0);
10301 
10302   if (VT != MVT::i32)
10303     return SDValue();
10304 
10305   SDLoc SL(N);
10306   SDValue LHS = N->getOperand(0);
10307   SDValue RHS = N->getOperand(1);
10308 
10309   // sub x, zext (setcc) => subcarry x, 0, setcc
10310   // sub x, sext (setcc) => addcarry x, 0, setcc
10311   unsigned Opc = RHS.getOpcode();
10312   switch (Opc) {
10313   default: break;
10314   case ISD::ZERO_EXTEND:
10315   case ISD::SIGN_EXTEND:
10316   case ISD::ANY_EXTEND: {
10317     auto Cond = RHS.getOperand(0);
10318     // If this won't be a real VOPC output, we would still need to insert an
10319     // extra instruction anyway.
10320     if (!isBoolSGPR(Cond))
10321       break;
10322     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10323     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10324     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10325     return DAG.getNode(Opc, SL, VTList, Args);
10326   }
10327   }
10328 
10329   if (LHS.getOpcode() == ISD::SUBCARRY) {
10330     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10331     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10332     if (!C || !C->isNullValue())
10333       return SDValue();
10334     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10335     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10336   }
10337   return SDValue();
10338 }
10339 
10340 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10341   DAGCombinerInfo &DCI) const {
10342 
10343   if (N->getValueType(0) != MVT::i32)
10344     return SDValue();
10345 
10346   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10347   if (!C || C->getZExtValue() != 0)
10348     return SDValue();
10349 
10350   SelectionDAG &DAG = DCI.DAG;
10351   SDValue LHS = N->getOperand(0);
10352 
10353   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10354   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10355   unsigned LHSOpc = LHS.getOpcode();
10356   unsigned Opc = N->getOpcode();
10357   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10358       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10359     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10360     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10361   }
10362   return SDValue();
10363 }
10364 
10365 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10366                                              DAGCombinerInfo &DCI) const {
10367   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10368     return SDValue();
10369 
10370   SelectionDAG &DAG = DCI.DAG;
10371   EVT VT = N->getValueType(0);
10372 
10373   SDLoc SL(N);
10374   SDValue LHS = N->getOperand(0);
10375   SDValue RHS = N->getOperand(1);
10376 
10377   // These should really be instruction patterns, but writing patterns with
10378   // source modiifiers is a pain.
10379 
10380   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10381   if (LHS.getOpcode() == ISD::FADD) {
10382     SDValue A = LHS.getOperand(0);
10383     if (A == LHS.getOperand(1)) {
10384       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10385       if (FusedOp != 0) {
10386         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10387         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10388       }
10389     }
10390   }
10391 
10392   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10393   if (RHS.getOpcode() == ISD::FADD) {
10394     SDValue A = RHS.getOperand(0);
10395     if (A == RHS.getOperand(1)) {
10396       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10397       if (FusedOp != 0) {
10398         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10399         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10400       }
10401     }
10402   }
10403 
10404   return SDValue();
10405 }
10406 
10407 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10408                                              DAGCombinerInfo &DCI) const {
10409   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10410     return SDValue();
10411 
10412   SelectionDAG &DAG = DCI.DAG;
10413   SDLoc SL(N);
10414   EVT VT = N->getValueType(0);
10415   assert(!VT.isVector());
10416 
10417   // Try to get the fneg to fold into the source modifier. This undoes generic
10418   // DAG combines and folds them into the mad.
10419   //
10420   // Only do this if we are not trying to support denormals. v_mad_f32 does
10421   // not support denormals ever.
10422   SDValue LHS = N->getOperand(0);
10423   SDValue RHS = N->getOperand(1);
10424   if (LHS.getOpcode() == ISD::FADD) {
10425     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10426     SDValue A = LHS.getOperand(0);
10427     if (A == LHS.getOperand(1)) {
10428       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10429       if (FusedOp != 0){
10430         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10431         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10432 
10433         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10434       }
10435     }
10436   }
10437 
10438   if (RHS.getOpcode() == ISD::FADD) {
10439     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10440 
10441     SDValue A = RHS.getOperand(0);
10442     if (A == RHS.getOperand(1)) {
10443       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10444       if (FusedOp != 0){
10445         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10446         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10447       }
10448     }
10449   }
10450 
10451   return SDValue();
10452 }
10453 
10454 SDValue SITargetLowering::performFMACombine(SDNode *N,
10455                                             DAGCombinerInfo &DCI) const {
10456   SelectionDAG &DAG = DCI.DAG;
10457   EVT VT = N->getValueType(0);
10458   SDLoc SL(N);
10459 
10460   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10461     return SDValue();
10462 
10463   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10464   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10465   SDValue Op1 = N->getOperand(0);
10466   SDValue Op2 = N->getOperand(1);
10467   SDValue FMA = N->getOperand(2);
10468 
10469   if (FMA.getOpcode() != ISD::FMA ||
10470       Op1.getOpcode() != ISD::FP_EXTEND ||
10471       Op2.getOpcode() != ISD::FP_EXTEND)
10472     return SDValue();
10473 
10474   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10475   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10476   // is sufficient to allow generaing fdot2.
10477   const TargetOptions &Options = DAG.getTarget().Options;
10478   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10479       (N->getFlags().hasAllowContract() &&
10480        FMA->getFlags().hasAllowContract())) {
10481     Op1 = Op1.getOperand(0);
10482     Op2 = Op2.getOperand(0);
10483     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10484         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10485       return SDValue();
10486 
10487     SDValue Vec1 = Op1.getOperand(0);
10488     SDValue Idx1 = Op1.getOperand(1);
10489     SDValue Vec2 = Op2.getOperand(0);
10490 
10491     SDValue FMAOp1 = FMA.getOperand(0);
10492     SDValue FMAOp2 = FMA.getOperand(1);
10493     SDValue FMAAcc = FMA.getOperand(2);
10494 
10495     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10496         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10497       return SDValue();
10498 
10499     FMAOp1 = FMAOp1.getOperand(0);
10500     FMAOp2 = FMAOp2.getOperand(0);
10501     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10502         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10503       return SDValue();
10504 
10505     SDValue Vec3 = FMAOp1.getOperand(0);
10506     SDValue Vec4 = FMAOp2.getOperand(0);
10507     SDValue Idx2 = FMAOp1.getOperand(1);
10508 
10509     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10510         // Idx1 and Idx2 cannot be the same.
10511         Idx1 == Idx2)
10512       return SDValue();
10513 
10514     if (Vec1 == Vec2 || Vec3 == Vec4)
10515       return SDValue();
10516 
10517     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10518       return SDValue();
10519 
10520     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10521         (Vec1 == Vec4 && Vec2 == Vec3)) {
10522       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10523                          DAG.getTargetConstant(0, SL, MVT::i1));
10524     }
10525   }
10526   return SDValue();
10527 }
10528 
10529 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10530                                               DAGCombinerInfo &DCI) const {
10531   SelectionDAG &DAG = DCI.DAG;
10532   SDLoc SL(N);
10533 
10534   SDValue LHS = N->getOperand(0);
10535   SDValue RHS = N->getOperand(1);
10536   EVT VT = LHS.getValueType();
10537   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10538 
10539   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10540   if (!CRHS) {
10541     CRHS = dyn_cast<ConstantSDNode>(LHS);
10542     if (CRHS) {
10543       std::swap(LHS, RHS);
10544       CC = getSetCCSwappedOperands(CC);
10545     }
10546   }
10547 
10548   if (CRHS) {
10549     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10550         isBoolSGPR(LHS.getOperand(0))) {
10551       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10552       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10553       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10554       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10555       if ((CRHS->isAllOnesValue() &&
10556            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10557           (CRHS->isNullValue() &&
10558            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10559         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10560                            DAG.getConstant(-1, SL, MVT::i1));
10561       if ((CRHS->isAllOnesValue() &&
10562            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10563           (CRHS->isNullValue() &&
10564            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10565         return LHS.getOperand(0);
10566     }
10567 
10568     uint64_t CRHSVal = CRHS->getZExtValue();
10569     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10570         LHS.getOpcode() == ISD::SELECT &&
10571         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10572         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10573         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10574         isBoolSGPR(LHS.getOperand(0))) {
10575       // Given CT != FT:
10576       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10577       // setcc (select cc, CT, CF), CF, ne => cc
10578       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10579       // setcc (select cc, CT, CF), CT, eq => cc
10580       uint64_t CT = LHS.getConstantOperandVal(1);
10581       uint64_t CF = LHS.getConstantOperandVal(2);
10582 
10583       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10584           (CT == CRHSVal && CC == ISD::SETNE))
10585         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10586                            DAG.getConstant(-1, SL, MVT::i1));
10587       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10588           (CT == CRHSVal && CC == ISD::SETEQ))
10589         return LHS.getOperand(0);
10590     }
10591   }
10592 
10593   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10594                                            VT != MVT::f16))
10595     return SDValue();
10596 
10597   // Match isinf/isfinite pattern
10598   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10599   // (fcmp one (fabs x), inf) -> (fp_class x,
10600   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10601   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10602     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10603     if (!CRHS)
10604       return SDValue();
10605 
10606     const APFloat &APF = CRHS->getValueAPF();
10607     if (APF.isInfinity() && !APF.isNegative()) {
10608       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10609                                  SIInstrFlags::N_INFINITY;
10610       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10611                                     SIInstrFlags::P_ZERO |
10612                                     SIInstrFlags::N_NORMAL |
10613                                     SIInstrFlags::P_NORMAL |
10614                                     SIInstrFlags::N_SUBNORMAL |
10615                                     SIInstrFlags::P_SUBNORMAL;
10616       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10617       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10618                          DAG.getConstant(Mask, SL, MVT::i32));
10619     }
10620   }
10621 
10622   return SDValue();
10623 }
10624 
10625 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10626                                                      DAGCombinerInfo &DCI) const {
10627   SelectionDAG &DAG = DCI.DAG;
10628   SDLoc SL(N);
10629   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10630 
10631   SDValue Src = N->getOperand(0);
10632   SDValue Shift = N->getOperand(0);
10633 
10634   // TODO: Extend type shouldn't matter (assuming legal types).
10635   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10636     Shift = Shift.getOperand(0);
10637 
10638   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10639     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10640     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10641     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10642     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10643     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10644     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10645       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10646                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10647 
10648       unsigned ShiftOffset = 8 * Offset;
10649       if (Shift.getOpcode() == ISD::SHL)
10650         ShiftOffset -= C->getZExtValue();
10651       else
10652         ShiftOffset += C->getZExtValue();
10653 
10654       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10655         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10656                            MVT::f32, Shift);
10657       }
10658     }
10659   }
10660 
10661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10662   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10663   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10664     // We simplified Src. If this node is not dead, visit it again so it is
10665     // folded properly.
10666     if (N->getOpcode() != ISD::DELETED_NODE)
10667       DCI.AddToWorklist(N);
10668     return SDValue(N, 0);
10669   }
10670 
10671   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10672   if (SDValue DemandedSrc =
10673           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10674     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10675 
10676   return SDValue();
10677 }
10678 
10679 SDValue SITargetLowering::performClampCombine(SDNode *N,
10680                                               DAGCombinerInfo &DCI) const {
10681   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10682   if (!CSrc)
10683     return SDValue();
10684 
10685   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10686   const APFloat &F = CSrc->getValueAPF();
10687   APFloat Zero = APFloat::getZero(F.getSemantics());
10688   if (F < Zero ||
10689       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10690     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10691   }
10692 
10693   APFloat One(F.getSemantics(), "1.0");
10694   if (F > One)
10695     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10696 
10697   return SDValue(CSrc, 0);
10698 }
10699 
10700 
10701 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10702                                             DAGCombinerInfo &DCI) const {
10703   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10704     return SDValue();
10705   switch (N->getOpcode()) {
10706   case ISD::ADD:
10707     return performAddCombine(N, DCI);
10708   case ISD::SUB:
10709     return performSubCombine(N, DCI);
10710   case ISD::ADDCARRY:
10711   case ISD::SUBCARRY:
10712     return performAddCarrySubCarryCombine(N, DCI);
10713   case ISD::FADD:
10714     return performFAddCombine(N, DCI);
10715   case ISD::FSUB:
10716     return performFSubCombine(N, DCI);
10717   case ISD::SETCC:
10718     return performSetCCCombine(N, DCI);
10719   case ISD::FMAXNUM:
10720   case ISD::FMINNUM:
10721   case ISD::FMAXNUM_IEEE:
10722   case ISD::FMINNUM_IEEE:
10723   case ISD::SMAX:
10724   case ISD::SMIN:
10725   case ISD::UMAX:
10726   case ISD::UMIN:
10727   case AMDGPUISD::FMIN_LEGACY:
10728   case AMDGPUISD::FMAX_LEGACY:
10729     return performMinMaxCombine(N, DCI);
10730   case ISD::FMA:
10731     return performFMACombine(N, DCI);
10732   case ISD::AND:
10733     return performAndCombine(N, DCI);
10734   case ISD::OR:
10735     return performOrCombine(N, DCI);
10736   case ISD::XOR:
10737     return performXorCombine(N, DCI);
10738   case ISD::ZERO_EXTEND:
10739     return performZeroExtendCombine(N, DCI);
10740   case ISD::SIGN_EXTEND_INREG:
10741     return performSignExtendInRegCombine(N , DCI);
10742   case AMDGPUISD::FP_CLASS:
10743     return performClassCombine(N, DCI);
10744   case ISD::FCANONICALIZE:
10745     return performFCanonicalizeCombine(N, DCI);
10746   case AMDGPUISD::RCP:
10747     return performRcpCombine(N, DCI);
10748   case AMDGPUISD::FRACT:
10749   case AMDGPUISD::RSQ:
10750   case AMDGPUISD::RCP_LEGACY:
10751   case AMDGPUISD::RCP_IFLAG:
10752   case AMDGPUISD::RSQ_CLAMP:
10753   case AMDGPUISD::LDEXP: {
10754     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10755     SDValue Src = N->getOperand(0);
10756     if (Src.isUndef())
10757       return Src;
10758     break;
10759   }
10760   case ISD::SINT_TO_FP:
10761   case ISD::UINT_TO_FP:
10762     return performUCharToFloatCombine(N, DCI);
10763   case AMDGPUISD::CVT_F32_UBYTE0:
10764   case AMDGPUISD::CVT_F32_UBYTE1:
10765   case AMDGPUISD::CVT_F32_UBYTE2:
10766   case AMDGPUISD::CVT_F32_UBYTE3:
10767     return performCvtF32UByteNCombine(N, DCI);
10768   case AMDGPUISD::FMED3:
10769     return performFMed3Combine(N, DCI);
10770   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10771     return performCvtPkRTZCombine(N, DCI);
10772   case AMDGPUISD::CLAMP:
10773     return performClampCombine(N, DCI);
10774   case ISD::SCALAR_TO_VECTOR: {
10775     SelectionDAG &DAG = DCI.DAG;
10776     EVT VT = N->getValueType(0);
10777 
10778     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10779     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10780       SDLoc SL(N);
10781       SDValue Src = N->getOperand(0);
10782       EVT EltVT = Src.getValueType();
10783       if (EltVT == MVT::f16)
10784         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10785 
10786       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10787       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10788     }
10789 
10790     break;
10791   }
10792   case ISD::EXTRACT_VECTOR_ELT:
10793     return performExtractVectorEltCombine(N, DCI);
10794   case ISD::INSERT_VECTOR_ELT:
10795     return performInsertVectorEltCombine(N, DCI);
10796   case ISD::LOAD: {
10797     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10798       return Widended;
10799     LLVM_FALLTHROUGH;
10800   }
10801   default: {
10802     if (!DCI.isBeforeLegalize()) {
10803       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10804         return performMemSDNodeCombine(MemNode, DCI);
10805     }
10806 
10807     break;
10808   }
10809   }
10810 
10811   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10812 }
10813 
10814 /// Helper function for adjustWritemask
10815 static unsigned SubIdx2Lane(unsigned Idx) {
10816   switch (Idx) {
10817   default: return ~0u;
10818   case AMDGPU::sub0: return 0;
10819   case AMDGPU::sub1: return 1;
10820   case AMDGPU::sub2: return 2;
10821   case AMDGPU::sub3: return 3;
10822   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10823   }
10824 }
10825 
10826 /// Adjust the writemask of MIMG instructions
10827 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10828                                           SelectionDAG &DAG) const {
10829   unsigned Opcode = Node->getMachineOpcode();
10830 
10831   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10832   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10833   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10834     return Node; // not implemented for D16
10835 
10836   SDNode *Users[5] = { nullptr };
10837   unsigned Lane = 0;
10838   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10839   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10840   unsigned NewDmask = 0;
10841   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10842   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10843   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10844                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10845   unsigned TFCLane = 0;
10846   bool HasChain = Node->getNumValues() > 1;
10847 
10848   if (OldDmask == 0) {
10849     // These are folded out, but on the chance it happens don't assert.
10850     return Node;
10851   }
10852 
10853   unsigned OldBitsSet = countPopulation(OldDmask);
10854   // Work out which is the TFE/LWE lane if that is enabled.
10855   if (UsesTFC) {
10856     TFCLane = OldBitsSet;
10857   }
10858 
10859   // Try to figure out the used register components
10860   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10861        I != E; ++I) {
10862 
10863     // Don't look at users of the chain.
10864     if (I.getUse().getResNo() != 0)
10865       continue;
10866 
10867     // Abort if we can't understand the usage
10868     if (!I->isMachineOpcode() ||
10869         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10870       return Node;
10871 
10872     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10873     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10874     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10875     // set, etc.
10876     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10877     if (Lane == ~0u)
10878       return Node;
10879 
10880     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10881     if (UsesTFC && Lane == TFCLane) {
10882       Users[Lane] = *I;
10883     } else {
10884       // Set which texture component corresponds to the lane.
10885       unsigned Comp;
10886       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10887         Comp = countTrailingZeros(Dmask);
10888         Dmask &= ~(1 << Comp);
10889       }
10890 
10891       // Abort if we have more than one user per component.
10892       if (Users[Lane])
10893         return Node;
10894 
10895       Users[Lane] = *I;
10896       NewDmask |= 1 << Comp;
10897     }
10898   }
10899 
10900   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10901   bool NoChannels = !NewDmask;
10902   if (NoChannels) {
10903     if (!UsesTFC) {
10904       // No uses of the result and not using TFC. Then do nothing.
10905       return Node;
10906     }
10907     // If the original dmask has one channel - then nothing to do
10908     if (OldBitsSet == 1)
10909       return Node;
10910     // Use an arbitrary dmask - required for the instruction to work
10911     NewDmask = 1;
10912   }
10913   // Abort if there's no change
10914   if (NewDmask == OldDmask)
10915     return Node;
10916 
10917   unsigned BitsSet = countPopulation(NewDmask);
10918 
10919   // Check for TFE or LWE - increase the number of channels by one to account
10920   // for the extra return value
10921   // This will need adjustment for D16 if this is also included in
10922   // adjustWriteMask (this function) but at present D16 are excluded.
10923   unsigned NewChannels = BitsSet + UsesTFC;
10924 
10925   int NewOpcode =
10926       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10927   assert(NewOpcode != -1 &&
10928          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10929          "failed to find equivalent MIMG op");
10930 
10931   // Adjust the writemask in the node
10932   SmallVector<SDValue, 12> Ops;
10933   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10934   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10935   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10936 
10937   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10938 
10939   MVT ResultVT = NewChannels == 1 ?
10940     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10941                            NewChannels == 5 ? 8 : NewChannels);
10942   SDVTList NewVTList = HasChain ?
10943     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10944 
10945 
10946   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10947                                               NewVTList, Ops);
10948 
10949   if (HasChain) {
10950     // Update chain.
10951     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10952     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10953   }
10954 
10955   if (NewChannels == 1) {
10956     assert(Node->hasNUsesOfValue(1, 0));
10957     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10958                                       SDLoc(Node), Users[Lane]->getValueType(0),
10959                                       SDValue(NewNode, 0));
10960     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10961     return nullptr;
10962   }
10963 
10964   // Update the users of the node with the new indices
10965   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10966     SDNode *User = Users[i];
10967     if (!User) {
10968       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10969       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10970       if (i || !NoChannels)
10971         continue;
10972     } else {
10973       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10974       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10975     }
10976 
10977     switch (Idx) {
10978     default: break;
10979     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10980     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10981     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10982     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10983     }
10984   }
10985 
10986   DAG.RemoveDeadNode(Node);
10987   return nullptr;
10988 }
10989 
10990 static bool isFrameIndexOp(SDValue Op) {
10991   if (Op.getOpcode() == ISD::AssertZext)
10992     Op = Op.getOperand(0);
10993 
10994   return isa<FrameIndexSDNode>(Op);
10995 }
10996 
10997 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10998 /// with frame index operands.
10999 /// LLVM assumes that inputs are to these instructions are registers.
11000 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11001                                                         SelectionDAG &DAG) const {
11002   if (Node->getOpcode() == ISD::CopyToReg) {
11003     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11004     SDValue SrcVal = Node->getOperand(2);
11005 
11006     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11007     // to try understanding copies to physical registers.
11008     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11009       SDLoc SL(Node);
11010       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11011       SDValue VReg = DAG.getRegister(
11012         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11013 
11014       SDNode *Glued = Node->getGluedNode();
11015       SDValue ToVReg
11016         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11017                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11018       SDValue ToResultReg
11019         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11020                            VReg, ToVReg.getValue(1));
11021       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11022       DAG.RemoveDeadNode(Node);
11023       return ToResultReg.getNode();
11024     }
11025   }
11026 
11027   SmallVector<SDValue, 8> Ops;
11028   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11029     if (!isFrameIndexOp(Node->getOperand(i))) {
11030       Ops.push_back(Node->getOperand(i));
11031       continue;
11032     }
11033 
11034     SDLoc DL(Node);
11035     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11036                                      Node->getOperand(i).getValueType(),
11037                                      Node->getOperand(i)), 0));
11038   }
11039 
11040   return DAG.UpdateNodeOperands(Node, Ops);
11041 }
11042 
11043 /// Fold the instructions after selecting them.
11044 /// Returns null if users were already updated.
11045 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11046                                           SelectionDAG &DAG) const {
11047   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11048   unsigned Opcode = Node->getMachineOpcode();
11049 
11050   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11051       !TII->isGather4(Opcode) &&
11052       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11053     return adjustWritemask(Node, DAG);
11054   }
11055 
11056   if (Opcode == AMDGPU::INSERT_SUBREG ||
11057       Opcode == AMDGPU::REG_SEQUENCE) {
11058     legalizeTargetIndependentNode(Node, DAG);
11059     return Node;
11060   }
11061 
11062   switch (Opcode) {
11063   case AMDGPU::V_DIV_SCALE_F32_e64:
11064   case AMDGPU::V_DIV_SCALE_F64_e64: {
11065     // Satisfy the operand register constraint when one of the inputs is
11066     // undefined. Ordinarily each undef value will have its own implicit_def of
11067     // a vreg, so force these to use a single register.
11068     SDValue Src0 = Node->getOperand(1);
11069     SDValue Src1 = Node->getOperand(3);
11070     SDValue Src2 = Node->getOperand(5);
11071 
11072     if ((Src0.isMachineOpcode() &&
11073          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11074         (Src0 == Src1 || Src0 == Src2))
11075       break;
11076 
11077     MVT VT = Src0.getValueType().getSimpleVT();
11078     const TargetRegisterClass *RC =
11079         getRegClassFor(VT, Src0.getNode()->isDivergent());
11080 
11081     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11082     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11083 
11084     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11085                                       UndefReg, Src0, SDValue());
11086 
11087     // src0 must be the same register as src1 or src2, even if the value is
11088     // undefined, so make sure we don't violate this constraint.
11089     if (Src0.isMachineOpcode() &&
11090         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11091       if (Src1.isMachineOpcode() &&
11092           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11093         Src0 = Src1;
11094       else if (Src2.isMachineOpcode() &&
11095                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11096         Src0 = Src2;
11097       else {
11098         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11099         Src0 = UndefReg;
11100         Src1 = UndefReg;
11101       }
11102     } else
11103       break;
11104 
11105     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11106     Ops[1] = Src0;
11107     Ops[3] = Src1;
11108     Ops[5] = Src2;
11109     Ops.push_back(ImpDef.getValue(1));
11110     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11111   }
11112   default:
11113     break;
11114   }
11115 
11116   return Node;
11117 }
11118 
11119 /// Assign the register class depending on the number of
11120 /// bits set in the writemask
11121 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11122                                                      SDNode *Node) const {
11123   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11124 
11125   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11126 
11127   if (TII->isVOP3(MI.getOpcode())) {
11128     // Make sure constant bus requirements are respected.
11129     TII->legalizeOperandsVOP3(MRI, MI);
11130 
11131     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11132     // This saves a chain-copy of registers and better ballance register
11133     // use between vgpr and agpr as agpr tuples tend to be big.
11134     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11135       unsigned Opc = MI.getOpcode();
11136       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11137       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11138                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11139         if (I == -1)
11140           break;
11141         MachineOperand &Op = MI.getOperand(I);
11142         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11143              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11144             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11145           continue;
11146         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11147         if (!Src || !Src->isCopy() ||
11148             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11149           continue;
11150         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11151         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11152         // All uses of agpr64 and agpr32 can also accept vgpr except for
11153         // v_accvgpr_read, but we do not produce agpr reads during selection,
11154         // so no use checks are needed.
11155         MRI.setRegClass(Op.getReg(), NewRC);
11156       }
11157     }
11158 
11159     return;
11160   }
11161 
11162   // Replace unused atomics with the no return version.
11163   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11164   if (NoRetAtomicOp != -1) {
11165     if (!Node->hasAnyUseOfValue(0)) {
11166       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11167                                                AMDGPU::OpName::glc1);
11168       if (Glc1Idx != -1)
11169         MI.RemoveOperand(Glc1Idx);
11170       MI.RemoveOperand(0);
11171       MI.setDesc(TII->get(NoRetAtomicOp));
11172       return;
11173     }
11174 
11175     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11176     // instruction, because the return type of these instructions is a vec2 of
11177     // the memory type, so it can be tied to the input operand.
11178     // This means these instructions always have a use, so we need to add a
11179     // special case to check if the atomic has only one extract_subreg use,
11180     // which itself has no uses.
11181     if ((Node->hasNUsesOfValue(1, 0) &&
11182          Node->use_begin()->isMachineOpcode() &&
11183          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11184          !Node->use_begin()->hasAnyUseOfValue(0))) {
11185       Register Def = MI.getOperand(0).getReg();
11186 
11187       // Change this into a noret atomic.
11188       MI.setDesc(TII->get(NoRetAtomicOp));
11189       MI.RemoveOperand(0);
11190 
11191       // If we only remove the def operand from the atomic instruction, the
11192       // extract_subreg will be left with a use of a vreg without a def.
11193       // So we need to insert an implicit_def to avoid machine verifier
11194       // errors.
11195       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11196               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11197     }
11198     return;
11199   }
11200 }
11201 
11202 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11203                               uint64_t Val) {
11204   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11205   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11206 }
11207 
11208 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11209                                                 const SDLoc &DL,
11210                                                 SDValue Ptr) const {
11211   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11212 
11213   // Build the half of the subregister with the constants before building the
11214   // full 128-bit register. If we are building multiple resource descriptors,
11215   // this will allow CSEing of the 2-component register.
11216   const SDValue Ops0[] = {
11217     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11218     buildSMovImm32(DAG, DL, 0),
11219     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11220     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11221     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11222   };
11223 
11224   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11225                                                 MVT::v2i32, Ops0), 0);
11226 
11227   // Combine the constants and the pointer.
11228   const SDValue Ops1[] = {
11229     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11230     Ptr,
11231     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11232     SubRegHi,
11233     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11234   };
11235 
11236   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11237 }
11238 
11239 /// Return a resource descriptor with the 'Add TID' bit enabled
11240 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11241 ///        of the resource descriptor) to create an offset, which is added to
11242 ///        the resource pointer.
11243 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11244                                            SDValue Ptr, uint32_t RsrcDword1,
11245                                            uint64_t RsrcDword2And3) const {
11246   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11247   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11248   if (RsrcDword1) {
11249     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11250                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11251                     0);
11252   }
11253 
11254   SDValue DataLo = buildSMovImm32(DAG, DL,
11255                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11256   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11257 
11258   const SDValue Ops[] = {
11259     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11260     PtrLo,
11261     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11262     PtrHi,
11263     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11264     DataLo,
11265     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11266     DataHi,
11267     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11268   };
11269 
11270   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11271 }
11272 
11273 //===----------------------------------------------------------------------===//
11274 //                         SI Inline Assembly Support
11275 //===----------------------------------------------------------------------===//
11276 
11277 std::pair<unsigned, const TargetRegisterClass *>
11278 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11279                                                StringRef Constraint,
11280                                                MVT VT) const {
11281   const TargetRegisterClass *RC = nullptr;
11282   if (Constraint.size() == 1) {
11283     const unsigned BitWidth = VT.getSizeInBits();
11284     switch (Constraint[0]) {
11285     default:
11286       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11287     case 's':
11288     case 'r':
11289       switch (BitWidth) {
11290       case 16:
11291         RC = &AMDGPU::SReg_32RegClass;
11292         break;
11293       case 64:
11294         RC = &AMDGPU::SGPR_64RegClass;
11295         break;
11296       default:
11297         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11298         if (!RC)
11299           return std::make_pair(0U, nullptr);
11300         break;
11301       }
11302       break;
11303     case 'v':
11304       switch (BitWidth) {
11305       case 16:
11306         RC = &AMDGPU::VGPR_32RegClass;
11307         break;
11308       default:
11309         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11310         if (!RC)
11311           return std::make_pair(0U, nullptr);
11312         break;
11313       }
11314       break;
11315     case 'a':
11316       if (!Subtarget->hasMAIInsts())
11317         break;
11318       switch (BitWidth) {
11319       case 16:
11320         RC = &AMDGPU::AGPR_32RegClass;
11321         break;
11322       default:
11323         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11324         if (!RC)
11325           return std::make_pair(0U, nullptr);
11326         break;
11327       }
11328       break;
11329     }
11330     // We actually support i128, i16 and f16 as inline parameters
11331     // even if they are not reported as legal
11332     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11333                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11334       return std::make_pair(0U, RC);
11335   }
11336 
11337   if (Constraint.size() > 1) {
11338     if (Constraint[1] == 'v') {
11339       RC = &AMDGPU::VGPR_32RegClass;
11340     } else if (Constraint[1] == 's') {
11341       RC = &AMDGPU::SGPR_32RegClass;
11342     } else if (Constraint[1] == 'a') {
11343       RC = &AMDGPU::AGPR_32RegClass;
11344     }
11345 
11346     if (RC) {
11347       uint32_t Idx;
11348       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11349       if (!Failed && Idx < RC->getNumRegs())
11350         return std::make_pair(RC->getRegister(Idx), RC);
11351     }
11352   }
11353 
11354   // FIXME: Returns VS_32 for physical SGPR constraints
11355   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11356 }
11357 
11358 static bool isImmConstraint(StringRef Constraint) {
11359   if (Constraint.size() == 1) {
11360     switch (Constraint[0]) {
11361     default: break;
11362     case 'I':
11363     case 'J':
11364     case 'A':
11365     case 'B':
11366     case 'C':
11367       return true;
11368     }
11369   } else if (Constraint == "DA" ||
11370              Constraint == "DB") {
11371     return true;
11372   }
11373   return false;
11374 }
11375 
11376 SITargetLowering::ConstraintType
11377 SITargetLowering::getConstraintType(StringRef Constraint) const {
11378   if (Constraint.size() == 1) {
11379     switch (Constraint[0]) {
11380     default: break;
11381     case 's':
11382     case 'v':
11383     case 'a':
11384       return C_RegisterClass;
11385     }
11386   }
11387   if (isImmConstraint(Constraint)) {
11388     return C_Other;
11389   }
11390   return TargetLowering::getConstraintType(Constraint);
11391 }
11392 
11393 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11394   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11395     Val = Val & maskTrailingOnes<uint64_t>(Size);
11396   }
11397   return Val;
11398 }
11399 
11400 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11401                                                     std::string &Constraint,
11402                                                     std::vector<SDValue> &Ops,
11403                                                     SelectionDAG &DAG) const {
11404   if (isImmConstraint(Constraint)) {
11405     uint64_t Val;
11406     if (getAsmOperandConstVal(Op, Val) &&
11407         checkAsmConstraintVal(Op, Constraint, Val)) {
11408       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11409       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11410     }
11411   } else {
11412     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11413   }
11414 }
11415 
11416 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11417   unsigned Size = Op.getScalarValueSizeInBits();
11418   if (Size > 64)
11419     return false;
11420 
11421   if (Size == 16 && !Subtarget->has16BitInsts())
11422     return false;
11423 
11424   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11425     Val = C->getSExtValue();
11426     return true;
11427   }
11428   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11429     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11430     return true;
11431   }
11432   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11433     if (Size != 16 || Op.getNumOperands() != 2)
11434       return false;
11435     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11436       return false;
11437     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11438       Val = C->getSExtValue();
11439       return true;
11440     }
11441     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11442       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11443       return true;
11444     }
11445   }
11446 
11447   return false;
11448 }
11449 
11450 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11451                                              const std::string &Constraint,
11452                                              uint64_t Val) const {
11453   if (Constraint.size() == 1) {
11454     switch (Constraint[0]) {
11455     case 'I':
11456       return AMDGPU::isInlinableIntLiteral(Val);
11457     case 'J':
11458       return isInt<16>(Val);
11459     case 'A':
11460       return checkAsmConstraintValA(Op, Val);
11461     case 'B':
11462       return isInt<32>(Val);
11463     case 'C':
11464       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11465              AMDGPU::isInlinableIntLiteral(Val);
11466     default:
11467       break;
11468     }
11469   } else if (Constraint.size() == 2) {
11470     if (Constraint == "DA") {
11471       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11472       int64_t LoBits = static_cast<int32_t>(Val);
11473       return checkAsmConstraintValA(Op, HiBits, 32) &&
11474              checkAsmConstraintValA(Op, LoBits, 32);
11475     }
11476     if (Constraint == "DB") {
11477       return true;
11478     }
11479   }
11480   llvm_unreachable("Invalid asm constraint");
11481 }
11482 
11483 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11484                                               uint64_t Val,
11485                                               unsigned MaxSize) const {
11486   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11487   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11488   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11489       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11490       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11491     return true;
11492   }
11493   return false;
11494 }
11495 
11496 // Figure out which registers should be reserved for stack access. Only after
11497 // the function is legalized do we know all of the non-spill stack objects or if
11498 // calls are present.
11499 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11500   MachineRegisterInfo &MRI = MF.getRegInfo();
11501   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11502   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11503   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11504 
11505   if (Info->isEntryFunction()) {
11506     // Callable functions have fixed registers used for stack access.
11507     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11508   }
11509 
11510   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11511                              Info->getStackPtrOffsetReg()));
11512   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11513     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11514 
11515   // We need to worry about replacing the default register with itself in case
11516   // of MIR testcases missing the MFI.
11517   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11518     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11519 
11520   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11521     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11522 
11523   Info->limitOccupancy(MF);
11524 
11525   if (ST.isWave32() && !MF.empty()) {
11526     const SIInstrInfo *TII = ST.getInstrInfo();
11527     for (auto &MBB : MF) {
11528       for (auto &MI : MBB) {
11529         TII->fixImplicitOperands(MI);
11530       }
11531     }
11532   }
11533 
11534   TargetLoweringBase::finalizeLowering(MF);
11535 
11536   // Allocate a VGPR for future SGPR Spill if
11537   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11538   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11539   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11540       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11541     Info->reserveVGPRforSGPRSpills(MF);
11542 }
11543 
11544 void SITargetLowering::computeKnownBitsForFrameIndex(
11545   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11546   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11547 
11548   // Set the high bits to zero based on the maximum allowed scratch size per
11549   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11550   // calculation won't overflow, so assume the sign bit is never set.
11551   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11552 }
11553 
11554 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11555                                    KnownBits &Known, unsigned Dim) {
11556   unsigned MaxValue =
11557       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11558   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11559 }
11560 
11561 void SITargetLowering::computeKnownBitsForTargetInstr(
11562     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11563     const MachineRegisterInfo &MRI, unsigned Depth) const {
11564   const MachineInstr *MI = MRI.getVRegDef(R);
11565   switch (MI->getOpcode()) {
11566   case AMDGPU::G_INTRINSIC: {
11567     switch (MI->getIntrinsicID()) {
11568     case Intrinsic::amdgcn_workitem_id_x:
11569       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11570       break;
11571     case Intrinsic::amdgcn_workitem_id_y:
11572       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11573       break;
11574     case Intrinsic::amdgcn_workitem_id_z:
11575       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11576       break;
11577     case Intrinsic::amdgcn_mbcnt_lo:
11578     case Intrinsic::amdgcn_mbcnt_hi: {
11579       // These return at most the wavefront size - 1.
11580       unsigned Size = MRI.getType(R).getSizeInBits();
11581       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11582       break;
11583     }
11584     case Intrinsic::amdgcn_groupstaticsize: {
11585       // We can report everything over the maximum size as 0. We can't report
11586       // based on the actual size because we don't know if it's accurate or not
11587       // at any given point.
11588       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11589       break;
11590     }
11591     }
11592     break;
11593   }
11594   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11595     Known.Zero.setHighBits(24);
11596     break;
11597   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11598     Known.Zero.setHighBits(16);
11599     break;
11600   }
11601 }
11602 
11603 Align SITargetLowering::computeKnownAlignForTargetInstr(
11604   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11605   unsigned Depth) const {
11606   const MachineInstr *MI = MRI.getVRegDef(R);
11607   switch (MI->getOpcode()) {
11608   case AMDGPU::G_INTRINSIC:
11609   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11610     // FIXME: Can this move to generic code? What about the case where the call
11611     // site specifies a lower alignment?
11612     Intrinsic::ID IID = MI->getIntrinsicID();
11613     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11614     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11615     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11616       return *RetAlign;
11617     return Align(1);
11618   }
11619   default:
11620     return Align(1);
11621   }
11622 }
11623 
11624 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11625   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11626   const Align CacheLineAlign = Align(64);
11627 
11628   // Pre-GFX10 target did not benefit from loop alignment
11629   if (!ML || DisableLoopAlignment ||
11630       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11631       getSubtarget()->hasInstFwdPrefetchBug())
11632     return PrefAlign;
11633 
11634   // On GFX10 I$ is 4 x 64 bytes cache lines.
11635   // By default prefetcher keeps one cache line behind and reads two ahead.
11636   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11637   // behind and one ahead.
11638   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11639   // If loop fits 64 bytes it always spans no more than two cache lines and
11640   // does not need an alignment.
11641   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11642   // Else if loop is less or equal 192 bytes we need two lines behind.
11643 
11644   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11645   const MachineBasicBlock *Header = ML->getHeader();
11646   if (Header->getAlignment() != PrefAlign)
11647     return Header->getAlignment(); // Already processed.
11648 
11649   unsigned LoopSize = 0;
11650   for (const MachineBasicBlock *MBB : ML->blocks()) {
11651     // If inner loop block is aligned assume in average half of the alignment
11652     // size to be added as nops.
11653     if (MBB != Header)
11654       LoopSize += MBB->getAlignment().value() / 2;
11655 
11656     for (const MachineInstr &MI : *MBB) {
11657       LoopSize += TII->getInstSizeInBytes(MI);
11658       if (LoopSize > 192)
11659         return PrefAlign;
11660     }
11661   }
11662 
11663   if (LoopSize <= 64)
11664     return PrefAlign;
11665 
11666   if (LoopSize <= 128)
11667     return CacheLineAlign;
11668 
11669   // If any of parent loops is surrounded by prefetch instructions do not
11670   // insert new for inner loop, which would reset parent's settings.
11671   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11672     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11673       auto I = Exit->getFirstNonDebugInstr();
11674       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11675         return CacheLineAlign;
11676     }
11677   }
11678 
11679   MachineBasicBlock *Pre = ML->getLoopPreheader();
11680   MachineBasicBlock *Exit = ML->getExitBlock();
11681 
11682   if (Pre && Exit) {
11683     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11684             TII->get(AMDGPU::S_INST_PREFETCH))
11685       .addImm(1); // prefetch 2 lines behind PC
11686 
11687     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11688             TII->get(AMDGPU::S_INST_PREFETCH))
11689       .addImm(2); // prefetch 1 line behind PC
11690   }
11691 
11692   return CacheLineAlign;
11693 }
11694 
11695 LLVM_ATTRIBUTE_UNUSED
11696 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11697   assert(N->getOpcode() == ISD::CopyFromReg);
11698   do {
11699     // Follow the chain until we find an INLINEASM node.
11700     N = N->getOperand(0).getNode();
11701     if (N->getOpcode() == ISD::INLINEASM ||
11702         N->getOpcode() == ISD::INLINEASM_BR)
11703       return true;
11704   } while (N->getOpcode() == ISD::CopyFromReg);
11705   return false;
11706 }
11707 
11708 bool SITargetLowering::isSDNodeSourceOfDivergence(
11709     const SDNode *N, FunctionLoweringInfo *FLI,
11710     LegacyDivergenceAnalysis *KDA) const {
11711   switch (N->getOpcode()) {
11712   case ISD::CopyFromReg: {
11713     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11714     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11715     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11716     Register Reg = R->getReg();
11717 
11718     // FIXME: Why does this need to consider isLiveIn?
11719     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11720       return !TRI->isSGPRReg(MRI, Reg);
11721 
11722     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11723       return KDA->isDivergent(V);
11724 
11725     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11726     return !TRI->isSGPRReg(MRI, Reg);
11727   }
11728   case ISD::LOAD: {
11729     const LoadSDNode *L = cast<LoadSDNode>(N);
11730     unsigned AS = L->getAddressSpace();
11731     // A flat load may access private memory.
11732     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11733   }
11734   case ISD::CALLSEQ_END:
11735     return true;
11736   case ISD::INTRINSIC_WO_CHAIN:
11737     return AMDGPU::isIntrinsicSourceOfDivergence(
11738         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11739   case ISD::INTRINSIC_W_CHAIN:
11740     return AMDGPU::isIntrinsicSourceOfDivergence(
11741         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11742   }
11743   return false;
11744 }
11745 
11746 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11747                                                EVT VT) const {
11748   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11749   case MVT::f32:
11750     return hasFP32Denormals(DAG.getMachineFunction());
11751   case MVT::f64:
11752   case MVT::f16:
11753     return hasFP64FP16Denormals(DAG.getMachineFunction());
11754   default:
11755     return false;
11756   }
11757 }
11758 
11759 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11760                                                     const SelectionDAG &DAG,
11761                                                     bool SNaN,
11762                                                     unsigned Depth) const {
11763   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11764     const MachineFunction &MF = DAG.getMachineFunction();
11765     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11766 
11767     if (Info->getMode().DX10Clamp)
11768       return true; // Clamped to 0.
11769     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11770   }
11771 
11772   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11773                                                             SNaN, Depth);
11774 }
11775 
11776 // Global FP atomic instructions have a hardcoded FP mode and do not support
11777 // FP32 denormals, and only support v2f16 denormals.
11778 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11779   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11780   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11781   if (&Flt == &APFloat::IEEEsingle())
11782     return DenormMode == DenormalMode::getPreserveSign();
11783   return DenormMode == DenormalMode::getIEEE();
11784 }
11785 
11786 TargetLowering::AtomicExpansionKind
11787 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11788   switch (RMW->getOperation()) {
11789   case AtomicRMWInst::FAdd: {
11790     Type *Ty = RMW->getType();
11791 
11792     // We don't have a way to support 16-bit atomics now, so just leave them
11793     // as-is.
11794     if (Ty->isHalfTy())
11795       return AtomicExpansionKind::None;
11796 
11797     if (!Ty->isFloatTy())
11798       return AtomicExpansionKind::CmpXChg;
11799 
11800     // TODO: Do have these for flat. Older targets also had them for buffers.
11801     unsigned AS = RMW->getPointerAddressSpace();
11802 
11803     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11804       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11805         return AtomicExpansionKind::CmpXChg;
11806 
11807       return RMW->use_empty() ? AtomicExpansionKind::None :
11808                                 AtomicExpansionKind::CmpXChg;
11809     }
11810 
11811     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11812     // to round-to-nearest-even.
11813     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11814       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11815   }
11816   default:
11817     break;
11818   }
11819 
11820   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11821 }
11822 
11823 const TargetRegisterClass *
11824 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11825   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11826   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11827   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11828     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11829                                                : &AMDGPU::SReg_32RegClass;
11830   if (!TRI->isSGPRClass(RC) && !isDivergent)
11831     return TRI->getEquivalentSGPRClass(RC);
11832   else if (TRI->isSGPRClass(RC) && isDivergent)
11833     return TRI->getEquivalentVGPRClass(RC);
11834 
11835   return RC;
11836 }
11837 
11838 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11839 // uniform values (as produced by the mask results of control flow intrinsics)
11840 // used outside of divergent blocks. The phi users need to also be treated as
11841 // always uniform.
11842 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11843                       unsigned WaveSize) {
11844   // FIXME: We asssume we never cast the mask results of a control flow
11845   // intrinsic.
11846   // Early exit if the type won't be consistent as a compile time hack.
11847   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11848   if (!IT || IT->getBitWidth() != WaveSize)
11849     return false;
11850 
11851   if (!isa<Instruction>(V))
11852     return false;
11853   if (!Visited.insert(V).second)
11854     return false;
11855   bool Result = false;
11856   for (auto U : V->users()) {
11857     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11858       if (V == U->getOperand(1)) {
11859         switch (Intrinsic->getIntrinsicID()) {
11860         default:
11861           Result = false;
11862           break;
11863         case Intrinsic::amdgcn_if_break:
11864         case Intrinsic::amdgcn_if:
11865         case Intrinsic::amdgcn_else:
11866           Result = true;
11867           break;
11868         }
11869       }
11870       if (V == U->getOperand(0)) {
11871         switch (Intrinsic->getIntrinsicID()) {
11872         default:
11873           Result = false;
11874           break;
11875         case Intrinsic::amdgcn_end_cf:
11876         case Intrinsic::amdgcn_loop:
11877           Result = true;
11878           break;
11879         }
11880       }
11881     } else {
11882       Result = hasCFUser(U, Visited, WaveSize);
11883     }
11884     if (Result)
11885       break;
11886   }
11887   return Result;
11888 }
11889 
11890 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11891                                                const Value *V) const {
11892   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11893     if (CI->isInlineAsm()) {
11894       // FIXME: This cannot give a correct answer. This should only trigger in
11895       // the case where inline asm returns mixed SGPR and VGPR results, used
11896       // outside the defining block. We don't have a specific result to
11897       // consider, so this assumes if any value is SGPR, the overall register
11898       // also needs to be SGPR.
11899       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11900       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11901           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11902       for (auto &TC : TargetConstraints) {
11903         if (TC.Type == InlineAsm::isOutput) {
11904           ComputeConstraintToUse(TC, SDValue());
11905           unsigned AssignedReg;
11906           const TargetRegisterClass *RC;
11907           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11908               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11909           if (RC) {
11910             MachineRegisterInfo &MRI = MF.getRegInfo();
11911             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11912               return true;
11913             else if (SIRI->isSGPRClass(RC))
11914               return true;
11915           }
11916         }
11917       }
11918     }
11919   }
11920   SmallPtrSet<const Value *, 16> Visited;
11921   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11922 }
11923 
11924 std::pair<int, MVT>
11925 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11926                                           Type *Ty) const {
11927   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11928   auto Size = DL.getTypeSizeInBits(Ty);
11929   // Maximum load or store can handle 8 dwords for scalar and 4 for
11930   // vector ALU. Let's assume anything above 8 dwords is expensive
11931   // even if legal.
11932   if (Size <= 256)
11933     return Cost;
11934 
11935   Cost.first = (Size + 255) / 256;
11936   return Cost;
11937 }
11938