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 =
1012           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1013       Info.align.reset();
1014     } else {
1015       Info.ptrVal =
1016           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1017     }
1018 
1019     Info.flags = MachineMemOperand::MODereferenceable;
1020     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1021       unsigned DMaskLanes = 4;
1022 
1023       if (RsrcIntr->IsImage) {
1024         const AMDGPU::ImageDimIntrinsicInfo *Intr
1025           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1026         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1027           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1028 
1029         if (!BaseOpcode->Gather4) {
1030           // If this isn't a gather, we may have excess loaded elements in the
1031           // IR type. Check the dmask for the real number of elements loaded.
1032           unsigned DMask
1033             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1034           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1035         }
1036 
1037         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1038       } else
1039         Info.memVT = EVT::getEVT(CI.getType());
1040 
1041       // FIXME: What does alignment mean for an image?
1042       Info.opc = ISD::INTRINSIC_W_CHAIN;
1043       Info.flags |= MachineMemOperand::MOLoad;
1044     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1045       Info.opc = ISD::INTRINSIC_VOID;
1046 
1047       Type *DataTy = CI.getArgOperand(0)->getType();
1048       if (RsrcIntr->IsImage) {
1049         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1050         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1051         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1052       } else
1053         Info.memVT = EVT::getEVT(DataTy);
1054 
1055       Info.flags |= MachineMemOperand::MOStore;
1056     } else {
1057       // Atomic
1058       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1059                                             ISD::INTRINSIC_W_CHAIN;
1060       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1061       Info.flags = MachineMemOperand::MOLoad |
1062                    MachineMemOperand::MOStore |
1063                    MachineMemOperand::MODereferenceable;
1064 
1065       // XXX - Should this be volatile without known ordering?
1066       Info.flags |= MachineMemOperand::MOVolatile;
1067     }
1068     return true;
1069   }
1070 
1071   switch (IntrID) {
1072   case Intrinsic::amdgcn_atomic_inc:
1073   case Intrinsic::amdgcn_atomic_dec:
1074   case Intrinsic::amdgcn_ds_ordered_add:
1075   case Intrinsic::amdgcn_ds_ordered_swap:
1076   case Intrinsic::amdgcn_ds_fadd:
1077   case Intrinsic::amdgcn_ds_fmin:
1078   case Intrinsic::amdgcn_ds_fmax: {
1079     Info.opc = ISD::INTRINSIC_W_CHAIN;
1080     Info.memVT = MVT::getVT(CI.getType());
1081     Info.ptrVal = CI.getOperand(0);
1082     Info.align.reset();
1083     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1084 
1085     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1086     if (!Vol->isZero())
1087       Info.flags |= MachineMemOperand::MOVolatile;
1088 
1089     return true;
1090   }
1091   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1092     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1093 
1094     Info.opc = ISD::INTRINSIC_W_CHAIN;
1095     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1096     Info.ptrVal =
1097         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1098     Info.align.reset();
1099     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1100 
1101     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1102     if (!Vol || !Vol->isZero())
1103       Info.flags |= MachineMemOperand::MOVolatile;
1104 
1105     return true;
1106   }
1107   case Intrinsic::amdgcn_ds_append:
1108   case Intrinsic::amdgcn_ds_consume: {
1109     Info.opc = ISD::INTRINSIC_W_CHAIN;
1110     Info.memVT = MVT::getVT(CI.getType());
1111     Info.ptrVal = CI.getOperand(0);
1112     Info.align.reset();
1113     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1114 
1115     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1116     if (!Vol->isZero())
1117       Info.flags |= MachineMemOperand::MOVolatile;
1118 
1119     return true;
1120   }
1121   case Intrinsic::amdgcn_global_atomic_csub: {
1122     Info.opc = ISD::INTRINSIC_W_CHAIN;
1123     Info.memVT = MVT::getVT(CI.getType());
1124     Info.ptrVal = CI.getOperand(0);
1125     Info.align.reset();
1126     Info.flags = MachineMemOperand::MOLoad |
1127                  MachineMemOperand::MOStore |
1128                  MachineMemOperand::MOVolatile;
1129     return true;
1130   }
1131   case Intrinsic::amdgcn_global_atomic_fadd: {
1132     Info.opc = ISD::INTRINSIC_W_CHAIN;
1133     Info.memVT = MVT::getVT(CI.getType());
1134     Info.ptrVal = CI.getOperand(0);
1135     Info.align.reset();
1136     Info.flags = MachineMemOperand::MOLoad |
1137                  MachineMemOperand::MOStore |
1138                  MachineMemOperand::MODereferenceable |
1139                  MachineMemOperand::MOVolatile;
1140     return true;
1141   }
1142   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1143     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1144     Info.opc = ISD::INTRINSIC_W_CHAIN;
1145     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1146     Info.ptrVal =
1147         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1148     Info.align.reset();
1149     Info.flags = MachineMemOperand::MOLoad |
1150                  MachineMemOperand::MODereferenceable;
1151     return true;
1152   }
1153   case Intrinsic::amdgcn_ds_gws_init:
1154   case Intrinsic::amdgcn_ds_gws_barrier:
1155   case Intrinsic::amdgcn_ds_gws_sema_v:
1156   case Intrinsic::amdgcn_ds_gws_sema_br:
1157   case Intrinsic::amdgcn_ds_gws_sema_p:
1158   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1159     Info.opc = ISD::INTRINSIC_VOID;
1160 
1161     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1162     Info.ptrVal =
1163         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1164 
1165     // This is an abstract access, but we need to specify a type and size.
1166     Info.memVT = MVT::i32;
1167     Info.size = 4;
1168     Info.align = Align(4);
1169 
1170     Info.flags = MachineMemOperand::MOStore;
1171     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1172       Info.flags = MachineMemOperand::MOLoad;
1173     return true;
1174   }
1175   default:
1176     return false;
1177   }
1178 }
1179 
1180 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1181                                             SmallVectorImpl<Value*> &Ops,
1182                                             Type *&AccessTy) const {
1183   switch (II->getIntrinsicID()) {
1184   case Intrinsic::amdgcn_atomic_inc:
1185   case Intrinsic::amdgcn_atomic_dec:
1186   case Intrinsic::amdgcn_ds_ordered_add:
1187   case Intrinsic::amdgcn_ds_ordered_swap:
1188   case Intrinsic::amdgcn_ds_append:
1189   case Intrinsic::amdgcn_ds_consume:
1190   case Intrinsic::amdgcn_ds_fadd:
1191   case Intrinsic::amdgcn_ds_fmin:
1192   case Intrinsic::amdgcn_ds_fmax:
1193   case Intrinsic::amdgcn_global_atomic_fadd:
1194   case Intrinsic::amdgcn_global_atomic_csub: {
1195     Value *Ptr = II->getArgOperand(0);
1196     AccessTy = II->getType();
1197     Ops.push_back(Ptr);
1198     return true;
1199   }
1200   default:
1201     return false;
1202   }
1203 }
1204 
1205 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1206   if (!Subtarget->hasFlatInstOffsets()) {
1207     // Flat instructions do not have offsets, and only have the register
1208     // address.
1209     return AM.BaseOffs == 0 && AM.Scale == 0;
1210   }
1211 
1212   return AM.Scale == 0 &&
1213          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1214                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1215                                   /*Signed=*/false));
1216 }
1217 
1218 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1219   if (Subtarget->hasFlatGlobalInsts())
1220     return AM.Scale == 0 &&
1221            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1222                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1223                                     /*Signed=*/true));
1224 
1225   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1226       // Assume the we will use FLAT for all global memory accesses
1227       // on VI.
1228       // FIXME: This assumption is currently wrong.  On VI we still use
1229       // MUBUF instructions for the r + i addressing mode.  As currently
1230       // implemented, the MUBUF instructions only work on buffer < 4GB.
1231       // It may be possible to support > 4GB buffers with MUBUF instructions,
1232       // by setting the stride value in the resource descriptor which would
1233       // increase the size limit to (stride * 4GB).  However, this is risky,
1234       // because it has never been validated.
1235     return isLegalFlatAddressingMode(AM);
1236   }
1237 
1238   return isLegalMUBUFAddressingMode(AM);
1239 }
1240 
1241 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1242   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1243   // additionally can do r + r + i with addr64. 32-bit has more addressing
1244   // mode options. Depending on the resource constant, it can also do
1245   // (i64 r0) + (i32 r1) * (i14 i).
1246   //
1247   // Private arrays end up using a scratch buffer most of the time, so also
1248   // assume those use MUBUF instructions. Scratch loads / stores are currently
1249   // implemented as mubuf instructions with offen bit set, so slightly
1250   // different than the normal addr64.
1251   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1252     return false;
1253 
1254   // FIXME: Since we can split immediate into soffset and immediate offset,
1255   // would it make sense to allow any immediate?
1256 
1257   switch (AM.Scale) {
1258   case 0: // r + i or just i, depending on HasBaseReg.
1259     return true;
1260   case 1:
1261     return true; // We have r + r or r + i.
1262   case 2:
1263     if (AM.HasBaseReg) {
1264       // Reject 2 * r + r.
1265       return false;
1266     }
1267 
1268     // Allow 2 * r as r + r
1269     // Or  2 * r + i is allowed as r + r + i.
1270     return true;
1271   default: // Don't allow n * r
1272     return false;
1273   }
1274 }
1275 
1276 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1277                                              const AddrMode &AM, Type *Ty,
1278                                              unsigned AS, Instruction *I) const {
1279   // No global is ever allowed as a base.
1280   if (AM.BaseGV)
1281     return false;
1282 
1283   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1284     return isLegalGlobalAddressingMode(AM);
1285 
1286   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1287       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1288       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1289     // If the offset isn't a multiple of 4, it probably isn't going to be
1290     // correctly aligned.
1291     // FIXME: Can we get the real alignment here?
1292     if (AM.BaseOffs % 4 != 0)
1293       return isLegalMUBUFAddressingMode(AM);
1294 
1295     // There are no SMRD extloads, so if we have to do a small type access we
1296     // will use a MUBUF load.
1297     // FIXME?: We also need to do this if unaligned, but we don't know the
1298     // alignment here.
1299     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1300       return isLegalGlobalAddressingMode(AM);
1301 
1302     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1303       // SMRD instructions have an 8-bit, dword offset on SI.
1304       if (!isUInt<8>(AM.BaseOffs / 4))
1305         return false;
1306     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1307       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1308       // in 8-bits, it can use a smaller encoding.
1309       if (!isUInt<32>(AM.BaseOffs / 4))
1310         return false;
1311     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1312       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1313       if (!isUInt<20>(AM.BaseOffs))
1314         return false;
1315     } else
1316       llvm_unreachable("unhandled generation");
1317 
1318     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1319       return true;
1320 
1321     if (AM.Scale == 1 && AM.HasBaseReg)
1322       return true;
1323 
1324     return false;
1325 
1326   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1327     return isLegalMUBUFAddressingMode(AM);
1328   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1329              AS == AMDGPUAS::REGION_ADDRESS) {
1330     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1331     // field.
1332     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1333     // an 8-bit dword offset but we don't know the alignment here.
1334     if (!isUInt<16>(AM.BaseOffs))
1335       return false;
1336 
1337     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1338       return true;
1339 
1340     if (AM.Scale == 1 && AM.HasBaseReg)
1341       return true;
1342 
1343     return false;
1344   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1345              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1346     // For an unknown address space, this usually means that this is for some
1347     // reason being used for pure arithmetic, and not based on some addressing
1348     // computation. We don't have instructions that compute pointers with any
1349     // addressing modes, so treat them as having no offset like flat
1350     // instructions.
1351     return isLegalFlatAddressingMode(AM);
1352   }
1353 
1354   // Assume a user alias of global for unknown address spaces.
1355   return isLegalGlobalAddressingMode(AM);
1356 }
1357 
1358 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1359                                         const SelectionDAG &DAG) const {
1360   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1361     return (MemVT.getSizeInBits() <= 4 * 32);
1362   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1363     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1364     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1365   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1366     return (MemVT.getSizeInBits() <= 2 * 32);
1367   }
1368   return true;
1369 }
1370 
1371 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1372     unsigned Size, unsigned AddrSpace, Align Alignment,
1373     MachineMemOperand::Flags Flags, bool *IsFast) const {
1374   if (IsFast)
1375     *IsFast = false;
1376 
1377   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1378       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1379     // Check if alignment requirements for ds_read/write instructions are
1380     // disabled.
1381     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1382         !Subtarget->hasLDSMisalignedBug()) {
1383       if (IsFast)
1384         *IsFast = Alignment != Align(2);
1385       return true;
1386     }
1387 
1388     if (Size == 64) {
1389       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1390       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1391       // with adjacent offsets.
1392       bool AlignedBy4 = Alignment >= Align(4);
1393       if (IsFast)
1394         *IsFast = AlignedBy4;
1395 
1396       return AlignedBy4;
1397     }
1398     if (Size == 96) {
1399       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1400       bool Aligned = Alignment >= Align(16);
1401       if (IsFast)
1402         *IsFast = Aligned;
1403 
1404       return Aligned;
1405     }
1406     if (Size == 128) {
1407       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1408       // can do a 8 byte aligned, 16 byte access in a single operation using
1409       // ds_read2/write2_b64.
1410       bool Aligned = Alignment >= Align(8);
1411       if (IsFast)
1412         *IsFast = Aligned;
1413 
1414       return Aligned;
1415     }
1416   }
1417 
1418   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1419     bool AlignedBy4 = Alignment >= Align(4);
1420     if (IsFast)
1421       *IsFast = AlignedBy4;
1422 
1423     return AlignedBy4 ||
1424            Subtarget->enableFlatScratch() ||
1425            Subtarget->hasUnalignedScratchAccess();
1426   }
1427 
1428   // FIXME: We have to be conservative here and assume that flat operations
1429   // will access scratch.  If we had access to the IR function, then we
1430   // could determine if any private memory was used in the function.
1431   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1432       !Subtarget->hasUnalignedScratchAccess()) {
1433     bool AlignedBy4 = Alignment >= Align(4);
1434     if (IsFast)
1435       *IsFast = AlignedBy4;
1436 
1437     return AlignedBy4;
1438   }
1439 
1440   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1441       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1442         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1443     // If we have an uniform constant load, it still requires using a slow
1444     // buffer instruction if unaligned.
1445     if (IsFast) {
1446       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1447       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1448       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1449                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1450         Alignment >= Align(4) : Alignment != Align(2);
1451     }
1452 
1453     return true;
1454   }
1455 
1456   // Smaller than dword value must be aligned.
1457   if (Size < 32)
1458     return false;
1459 
1460   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1461   // byte-address are ignored, thus forcing Dword alignment.
1462   // This applies to private, global, and constant memory.
1463   if (IsFast)
1464     *IsFast = true;
1465 
1466   return Size >= 32 && Alignment >= Align(4);
1467 }
1468 
1469 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1470     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1471     bool *IsFast) const {
1472   if (IsFast)
1473     *IsFast = false;
1474 
1475   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1476   // which isn't a simple VT.
1477   // Until MVT is extended to handle this, simply check for the size and
1478   // rely on the condition below: allow accesses if the size is a multiple of 4.
1479   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1480                            VT.getStoreSize() > 16)) {
1481     return false;
1482   }
1483 
1484   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1485                                             Alignment, Flags, IsFast);
1486 }
1487 
1488 EVT SITargetLowering::getOptimalMemOpType(
1489     const MemOp &Op, const AttributeList &FuncAttributes) const {
1490   // FIXME: Should account for address space here.
1491 
1492   // The default fallback uses the private pointer size as a guess for a type to
1493   // use. Make sure we switch these to 64-bit accesses.
1494 
1495   if (Op.size() >= 16 &&
1496       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1497     return MVT::v4i32;
1498 
1499   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1500     return MVT::v2i32;
1501 
1502   // Use the default.
1503   return MVT::Other;
1504 }
1505 
1506 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1507   const MemSDNode *MemNode = cast<MemSDNode>(N);
1508   const Value *Ptr = MemNode->getMemOperand()->getValue();
1509   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1510   return I && I->getMetadata("amdgpu.noclobber");
1511 }
1512 
1513 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1514   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1515          AS == AMDGPUAS::PRIVATE_ADDRESS;
1516 }
1517 
1518 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1519                                            unsigned DestAS) const {
1520   // Flat -> private/local is a simple truncate.
1521   // Flat -> global is no-op
1522   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1523     return true;
1524 
1525   const GCNTargetMachine &TM =
1526       static_cast<const GCNTargetMachine &>(getTargetMachine());
1527   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1528 }
1529 
1530 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1531   const MemSDNode *MemNode = cast<MemSDNode>(N);
1532 
1533   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1534 }
1535 
1536 TargetLoweringBase::LegalizeTypeAction
1537 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1538   int NumElts = VT.getVectorNumElements();
1539   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1540     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1541   return TargetLoweringBase::getPreferredVectorAction(VT);
1542 }
1543 
1544 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1545                                                          Type *Ty) const {
1546   // FIXME: Could be smarter if called for vector constants.
1547   return true;
1548 }
1549 
1550 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1551   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1552     switch (Op) {
1553     case ISD::LOAD:
1554     case ISD::STORE:
1555 
1556     // These operations are done with 32-bit instructions anyway.
1557     case ISD::AND:
1558     case ISD::OR:
1559     case ISD::XOR:
1560     case ISD::SELECT:
1561       // TODO: Extensions?
1562       return true;
1563     default:
1564       return false;
1565     }
1566   }
1567 
1568   // SimplifySetCC uses this function to determine whether or not it should
1569   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1570   if (VT == MVT::i1 && Op == ISD::SETCC)
1571     return false;
1572 
1573   return TargetLowering::isTypeDesirableForOp(Op, VT);
1574 }
1575 
1576 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1577                                                    const SDLoc &SL,
1578                                                    SDValue Chain,
1579                                                    uint64_t Offset) const {
1580   const DataLayout &DL = DAG.getDataLayout();
1581   MachineFunction &MF = DAG.getMachineFunction();
1582   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1583 
1584   const ArgDescriptor *InputPtrReg;
1585   const TargetRegisterClass *RC;
1586   LLT ArgTy;
1587 
1588   std::tie(InputPtrReg, RC, ArgTy) =
1589       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1590 
1591   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1592   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1593   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1594     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1595 
1596   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1597 }
1598 
1599 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1600                                             const SDLoc &SL) const {
1601   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1602                                                FIRST_IMPLICIT);
1603   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1604 }
1605 
1606 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1607                                          const SDLoc &SL, SDValue Val,
1608                                          bool Signed,
1609                                          const ISD::InputArg *Arg) const {
1610   // First, if it is a widened vector, narrow it.
1611   if (VT.isVector() &&
1612       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1613     EVT NarrowedVT =
1614         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1615                          VT.getVectorNumElements());
1616     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1617                       DAG.getConstant(0, SL, MVT::i32));
1618   }
1619 
1620   // Then convert the vector elements or scalar value.
1621   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1622       VT.bitsLT(MemVT)) {
1623     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1624     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1625   }
1626 
1627   if (MemVT.isFloatingPoint())
1628     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1629   else if (Signed)
1630     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1631   else
1632     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1633 
1634   return Val;
1635 }
1636 
1637 SDValue SITargetLowering::lowerKernargMemParameter(
1638     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1639     uint64_t Offset, Align Alignment, bool Signed,
1640     const ISD::InputArg *Arg) const {
1641   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1642 
1643   // Try to avoid using an extload by loading earlier than the argument address,
1644   // and extracting the relevant bits. The load should hopefully be merged with
1645   // the previous argument.
1646   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1647     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1648     int64_t AlignDownOffset = alignDown(Offset, 4);
1649     int64_t OffsetDiff = Offset - AlignDownOffset;
1650 
1651     EVT IntVT = MemVT.changeTypeToInteger();
1652 
1653     // TODO: If we passed in the base kernel offset we could have a better
1654     // alignment than 4, but we don't really need it.
1655     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1656     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1657                                MachineMemOperand::MODereferenceable |
1658                                    MachineMemOperand::MOInvariant);
1659 
1660     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1661     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1662 
1663     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1664     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1665     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1666 
1667 
1668     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1669   }
1670 
1671   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1672   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1673                              MachineMemOperand::MODereferenceable |
1674                                  MachineMemOperand::MOInvariant);
1675 
1676   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1677   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1678 }
1679 
1680 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1681                                               const SDLoc &SL, SDValue Chain,
1682                                               const ISD::InputArg &Arg) const {
1683   MachineFunction &MF = DAG.getMachineFunction();
1684   MachineFrameInfo &MFI = MF.getFrameInfo();
1685 
1686   if (Arg.Flags.isByVal()) {
1687     unsigned Size = Arg.Flags.getByValSize();
1688     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1689     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1690   }
1691 
1692   unsigned ArgOffset = VA.getLocMemOffset();
1693   unsigned ArgSize = VA.getValVT().getStoreSize();
1694 
1695   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1696 
1697   // Create load nodes to retrieve arguments from the stack.
1698   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1699   SDValue ArgValue;
1700 
1701   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1702   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1703   MVT MemVT = VA.getValVT();
1704 
1705   switch (VA.getLocInfo()) {
1706   default:
1707     break;
1708   case CCValAssign::BCvt:
1709     MemVT = VA.getLocVT();
1710     break;
1711   case CCValAssign::SExt:
1712     ExtType = ISD::SEXTLOAD;
1713     break;
1714   case CCValAssign::ZExt:
1715     ExtType = ISD::ZEXTLOAD;
1716     break;
1717   case CCValAssign::AExt:
1718     ExtType = ISD::EXTLOAD;
1719     break;
1720   }
1721 
1722   ArgValue = DAG.getExtLoad(
1723     ExtType, SL, VA.getLocVT(), Chain, FIN,
1724     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1725     MemVT);
1726   return ArgValue;
1727 }
1728 
1729 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1730   const SIMachineFunctionInfo &MFI,
1731   EVT VT,
1732   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1733   const ArgDescriptor *Reg;
1734   const TargetRegisterClass *RC;
1735   LLT Ty;
1736 
1737   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1738   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1739 }
1740 
1741 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1742                                CallingConv::ID CallConv,
1743                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1744                                FunctionType *FType,
1745                                SIMachineFunctionInfo *Info) {
1746   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1747     const ISD::InputArg *Arg = &Ins[I];
1748 
1749     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1750            "vector type argument should have been split");
1751 
1752     // First check if it's a PS input addr.
1753     if (CallConv == CallingConv::AMDGPU_PS &&
1754         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1755       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1756 
1757       // Inconveniently only the first part of the split is marked as isSplit,
1758       // so skip to the end. We only want to increment PSInputNum once for the
1759       // entire split argument.
1760       if (Arg->Flags.isSplit()) {
1761         while (!Arg->Flags.isSplitEnd()) {
1762           assert((!Arg->VT.isVector() ||
1763                   Arg->VT.getScalarSizeInBits() == 16) &&
1764                  "unexpected vector split in ps argument type");
1765           if (!SkipArg)
1766             Splits.push_back(*Arg);
1767           Arg = &Ins[++I];
1768         }
1769       }
1770 
1771       if (SkipArg) {
1772         // We can safely skip PS inputs.
1773         Skipped.set(Arg->getOrigArgIndex());
1774         ++PSInputNum;
1775         continue;
1776       }
1777 
1778       Info->markPSInputAllocated(PSInputNum);
1779       if (Arg->Used)
1780         Info->markPSInputEnabled(PSInputNum);
1781 
1782       ++PSInputNum;
1783     }
1784 
1785     Splits.push_back(*Arg);
1786   }
1787 }
1788 
1789 // Allocate special inputs passed in VGPRs.
1790 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1791                                                       MachineFunction &MF,
1792                                                       const SIRegisterInfo &TRI,
1793                                                       SIMachineFunctionInfo &Info) const {
1794   const LLT S32 = LLT::scalar(32);
1795   MachineRegisterInfo &MRI = MF.getRegInfo();
1796 
1797   if (Info.hasWorkItemIDX()) {
1798     Register Reg = AMDGPU::VGPR0;
1799     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1800 
1801     CCInfo.AllocateReg(Reg);
1802     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1803   }
1804 
1805   if (Info.hasWorkItemIDY()) {
1806     Register Reg = AMDGPU::VGPR1;
1807     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1808 
1809     CCInfo.AllocateReg(Reg);
1810     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1811   }
1812 
1813   if (Info.hasWorkItemIDZ()) {
1814     Register Reg = AMDGPU::VGPR2;
1815     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1816 
1817     CCInfo.AllocateReg(Reg);
1818     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1819   }
1820 }
1821 
1822 // Try to allocate a VGPR at the end of the argument list, or if no argument
1823 // VGPRs are left allocating a stack slot.
1824 // If \p Mask is is given it indicates bitfield position in the register.
1825 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1826 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1827                                          ArgDescriptor Arg = ArgDescriptor()) {
1828   if (Arg.isSet())
1829     return ArgDescriptor::createArg(Arg, Mask);
1830 
1831   ArrayRef<MCPhysReg> ArgVGPRs
1832     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1833   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1834   if (RegIdx == ArgVGPRs.size()) {
1835     // Spill to stack required.
1836     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1837 
1838     return ArgDescriptor::createStack(Offset, Mask);
1839   }
1840 
1841   unsigned Reg = ArgVGPRs[RegIdx];
1842   Reg = CCInfo.AllocateReg(Reg);
1843   assert(Reg != AMDGPU::NoRegister);
1844 
1845   MachineFunction &MF = CCInfo.getMachineFunction();
1846   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1847   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1848   return ArgDescriptor::createRegister(Reg, Mask);
1849 }
1850 
1851 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1852                                              const TargetRegisterClass *RC,
1853                                              unsigned NumArgRegs) {
1854   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1855   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1856   if (RegIdx == ArgSGPRs.size())
1857     report_fatal_error("ran out of SGPRs for arguments");
1858 
1859   unsigned Reg = ArgSGPRs[RegIdx];
1860   Reg = CCInfo.AllocateReg(Reg);
1861   assert(Reg != AMDGPU::NoRegister);
1862 
1863   MachineFunction &MF = CCInfo.getMachineFunction();
1864   MF.addLiveIn(Reg, RC);
1865   return ArgDescriptor::createRegister(Reg);
1866 }
1867 
1868 // If this has a fixed position, we still should allocate the register in the
1869 // CCInfo state. Technically we could get away with this for values passed
1870 // outside of the normal argument range.
1871 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1872                                        const TargetRegisterClass *RC,
1873                                        MCRegister Reg) {
1874   Reg = CCInfo.AllocateReg(Reg);
1875   assert(Reg != AMDGPU::NoRegister);
1876   MachineFunction &MF = CCInfo.getMachineFunction();
1877   MF.addLiveIn(Reg, RC);
1878 }
1879 
1880 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1881   if (Arg) {
1882     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1883                                Arg.getRegister());
1884   } else
1885     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1886 }
1887 
1888 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1889   if (Arg) {
1890     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1891                                Arg.getRegister());
1892   } else
1893     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1894 }
1895 
1896 /// Allocate implicit function VGPR arguments at the end of allocated user
1897 /// arguments.
1898 void SITargetLowering::allocateSpecialInputVGPRs(
1899   CCState &CCInfo, MachineFunction &MF,
1900   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1901   const unsigned Mask = 0x3ff;
1902   ArgDescriptor Arg;
1903 
1904   if (Info.hasWorkItemIDX()) {
1905     Arg = allocateVGPR32Input(CCInfo, Mask);
1906     Info.setWorkItemIDX(Arg);
1907   }
1908 
1909   if (Info.hasWorkItemIDY()) {
1910     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1911     Info.setWorkItemIDY(Arg);
1912   }
1913 
1914   if (Info.hasWorkItemIDZ())
1915     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1916 }
1917 
1918 /// Allocate implicit function VGPR arguments in fixed registers.
1919 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1920   CCState &CCInfo, MachineFunction &MF,
1921   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1922   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1923   if (!Reg)
1924     report_fatal_error("failed to allocated VGPR for implicit arguments");
1925 
1926   const unsigned Mask = 0x3ff;
1927   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1928   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1929   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1930 }
1931 
1932 void SITargetLowering::allocateSpecialInputSGPRs(
1933   CCState &CCInfo,
1934   MachineFunction &MF,
1935   const SIRegisterInfo &TRI,
1936   SIMachineFunctionInfo &Info) const {
1937   auto &ArgInfo = Info.getArgInfo();
1938 
1939   // TODO: Unify handling with private memory pointers.
1940 
1941   if (Info.hasDispatchPtr())
1942     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1943 
1944   if (Info.hasQueuePtr())
1945     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1946 
1947   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1948   // constant offset from the kernarg segment.
1949   if (Info.hasImplicitArgPtr())
1950     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1951 
1952   if (Info.hasDispatchID())
1953     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
1954 
1955   // flat_scratch_init is not applicable for non-kernel functions.
1956 
1957   if (Info.hasWorkGroupIDX())
1958     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
1959 
1960   if (Info.hasWorkGroupIDY())
1961     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
1962 
1963   if (Info.hasWorkGroupIDZ())
1964     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
1965 }
1966 
1967 // Allocate special inputs passed in user SGPRs.
1968 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1969                                             MachineFunction &MF,
1970                                             const SIRegisterInfo &TRI,
1971                                             SIMachineFunctionInfo &Info) const {
1972   if (Info.hasImplicitBufferPtr()) {
1973     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1974     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1975     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1976   }
1977 
1978   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1979   if (Info.hasPrivateSegmentBuffer()) {
1980     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1981     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1982     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1983   }
1984 
1985   if (Info.hasDispatchPtr()) {
1986     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
1987     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1988     CCInfo.AllocateReg(DispatchPtrReg);
1989   }
1990 
1991   if (Info.hasQueuePtr()) {
1992     Register QueuePtrReg = Info.addQueuePtr(TRI);
1993     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1994     CCInfo.AllocateReg(QueuePtrReg);
1995   }
1996 
1997   if (Info.hasKernargSegmentPtr()) {
1998     MachineRegisterInfo &MRI = MF.getRegInfo();
1999     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2000     CCInfo.AllocateReg(InputPtrReg);
2001 
2002     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2003     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2004   }
2005 
2006   if (Info.hasDispatchID()) {
2007     Register DispatchIDReg = Info.addDispatchID(TRI);
2008     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2009     CCInfo.AllocateReg(DispatchIDReg);
2010   }
2011 
2012   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2013     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2014     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2015     CCInfo.AllocateReg(FlatScratchInitReg);
2016   }
2017 
2018   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2019   // these from the dispatch pointer.
2020 }
2021 
2022 // Allocate special input registers that are initialized per-wave.
2023 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2024                                            MachineFunction &MF,
2025                                            SIMachineFunctionInfo &Info,
2026                                            CallingConv::ID CallConv,
2027                                            bool IsShader) const {
2028   if (Info.hasWorkGroupIDX()) {
2029     Register Reg = Info.addWorkGroupIDX();
2030     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2031     CCInfo.AllocateReg(Reg);
2032   }
2033 
2034   if (Info.hasWorkGroupIDY()) {
2035     Register Reg = Info.addWorkGroupIDY();
2036     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2037     CCInfo.AllocateReg(Reg);
2038   }
2039 
2040   if (Info.hasWorkGroupIDZ()) {
2041     Register Reg = Info.addWorkGroupIDZ();
2042     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2043     CCInfo.AllocateReg(Reg);
2044   }
2045 
2046   if (Info.hasWorkGroupInfo()) {
2047     Register Reg = Info.addWorkGroupInfo();
2048     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2049     CCInfo.AllocateReg(Reg);
2050   }
2051 
2052   if (Info.hasPrivateSegmentWaveByteOffset()) {
2053     // Scratch wave offset passed in system SGPR.
2054     unsigned PrivateSegmentWaveByteOffsetReg;
2055 
2056     if (IsShader) {
2057       PrivateSegmentWaveByteOffsetReg =
2058         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2059 
2060       // This is true if the scratch wave byte offset doesn't have a fixed
2061       // location.
2062       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2063         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2064         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2065       }
2066     } else
2067       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2068 
2069     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2070     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2071   }
2072 }
2073 
2074 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2075                                      MachineFunction &MF,
2076                                      const SIRegisterInfo &TRI,
2077                                      SIMachineFunctionInfo &Info) {
2078   // Now that we've figured out where the scratch register inputs are, see if
2079   // should reserve the arguments and use them directly.
2080   MachineFrameInfo &MFI = MF.getFrameInfo();
2081   bool HasStackObjects = MFI.hasStackObjects();
2082   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2083 
2084   // Record that we know we have non-spill stack objects so we don't need to
2085   // check all stack objects later.
2086   if (HasStackObjects)
2087     Info.setHasNonSpillStackObjects(true);
2088 
2089   // Everything live out of a block is spilled with fast regalloc, so it's
2090   // almost certain that spilling will be required.
2091   if (TM.getOptLevel() == CodeGenOpt::None)
2092     HasStackObjects = true;
2093 
2094   // For now assume stack access is needed in any callee functions, so we need
2095   // the scratch registers to pass in.
2096   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2097 
2098   if (!ST.enableFlatScratch()) {
2099     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2100       // If we have stack objects, we unquestionably need the private buffer
2101       // resource. For the Code Object V2 ABI, this will be the first 4 user
2102       // SGPR inputs. We can reserve those and use them directly.
2103 
2104       Register PrivateSegmentBufferReg =
2105           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2106       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2107     } else {
2108       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2109       // We tentatively reserve the last registers (skipping the last registers
2110       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2111       // we'll replace these with the ones immediately after those which were
2112       // really allocated. In the prologue copies will be inserted from the
2113       // argument to these reserved registers.
2114 
2115       // Without HSA, relocations are used for the scratch pointer and the
2116       // buffer resource setup is always inserted in the prologue. Scratch wave
2117       // offset is still in an input SGPR.
2118       Info.setScratchRSrcReg(ReservedBufferReg);
2119     }
2120   }
2121 
2122   MachineRegisterInfo &MRI = MF.getRegInfo();
2123 
2124   // For entry functions we have to set up the stack pointer if we use it,
2125   // whereas non-entry functions get this "for free". This means there is no
2126   // intrinsic advantage to using S32 over S34 in cases where we do not have
2127   // calls but do need a frame pointer (i.e. if we are requested to have one
2128   // because frame pointer elimination is disabled). To keep things simple we
2129   // only ever use S32 as the call ABI stack pointer, and so using it does not
2130   // imply we need a separate frame pointer.
2131   //
2132   // Try to use s32 as the SP, but move it if it would interfere with input
2133   // arguments. This won't work with calls though.
2134   //
2135   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2136   // registers.
2137   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2138     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2139   } else {
2140     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2141 
2142     if (MFI.hasCalls())
2143       report_fatal_error("call in graphics shader with too many input SGPRs");
2144 
2145     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2146       if (!MRI.isLiveIn(Reg)) {
2147         Info.setStackPtrOffsetReg(Reg);
2148         break;
2149       }
2150     }
2151 
2152     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2153       report_fatal_error("failed to find register for SP");
2154   }
2155 
2156   // hasFP should be accurate for entry functions even before the frame is
2157   // finalized, because it does not rely on the known stack size, only
2158   // properties like whether variable sized objects are present.
2159   if (ST.getFrameLowering()->hasFP(MF)) {
2160     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2161   }
2162 }
2163 
2164 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2165   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2166   return !Info->isEntryFunction();
2167 }
2168 
2169 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2170 
2171 }
2172 
2173 void SITargetLowering::insertCopiesSplitCSR(
2174   MachineBasicBlock *Entry,
2175   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2176   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2177 
2178   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2179   if (!IStart)
2180     return;
2181 
2182   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2183   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2184   MachineBasicBlock::iterator MBBI = Entry->begin();
2185   for (const MCPhysReg *I = IStart; *I; ++I) {
2186     const TargetRegisterClass *RC = nullptr;
2187     if (AMDGPU::SReg_64RegClass.contains(*I))
2188       RC = &AMDGPU::SGPR_64RegClass;
2189     else if (AMDGPU::SReg_32RegClass.contains(*I))
2190       RC = &AMDGPU::SGPR_32RegClass;
2191     else
2192       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2193 
2194     Register NewVR = MRI->createVirtualRegister(RC);
2195     // Create copy from CSR to a virtual register.
2196     Entry->addLiveIn(*I);
2197     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2198       .addReg(*I);
2199 
2200     // Insert the copy-back instructions right before the terminator.
2201     for (auto *Exit : Exits)
2202       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2203               TII->get(TargetOpcode::COPY), *I)
2204         .addReg(NewVR);
2205   }
2206 }
2207 
2208 SDValue SITargetLowering::LowerFormalArguments(
2209     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2210     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2211     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2212   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2213 
2214   MachineFunction &MF = DAG.getMachineFunction();
2215   const Function &Fn = MF.getFunction();
2216   FunctionType *FType = MF.getFunction().getFunctionType();
2217   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2218 
2219   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2220     DiagnosticInfoUnsupported NoGraphicsHSA(
2221         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2222     DAG.getContext()->diagnose(NoGraphicsHSA);
2223     return DAG.getEntryNode();
2224   }
2225 
2226   SmallVector<ISD::InputArg, 16> Splits;
2227   SmallVector<CCValAssign, 16> ArgLocs;
2228   BitVector Skipped(Ins.size());
2229   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2230                  *DAG.getContext());
2231 
2232   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2233   bool IsKernel = AMDGPU::isKernel(CallConv);
2234   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2235 
2236   if (IsGraphics) {
2237     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2238            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2239            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2240            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2241            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2242            !Info->hasWorkItemIDZ());
2243   }
2244 
2245   if (CallConv == CallingConv::AMDGPU_PS) {
2246     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2247 
2248     // At least one interpolation mode must be enabled or else the GPU will
2249     // hang.
2250     //
2251     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2252     // set PSInputAddr, the user wants to enable some bits after the compilation
2253     // based on run-time states. Since we can't know what the final PSInputEna
2254     // will look like, so we shouldn't do anything here and the user should take
2255     // responsibility for the correct programming.
2256     //
2257     // Otherwise, the following restrictions apply:
2258     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2259     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2260     //   enabled too.
2261     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2262         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2263       CCInfo.AllocateReg(AMDGPU::VGPR0);
2264       CCInfo.AllocateReg(AMDGPU::VGPR1);
2265       Info->markPSInputAllocated(0);
2266       Info->markPSInputEnabled(0);
2267     }
2268     if (Subtarget->isAmdPalOS()) {
2269       // For isAmdPalOS, the user does not enable some bits after compilation
2270       // based on run-time states; the register values being generated here are
2271       // the final ones set in hardware. Therefore we need to apply the
2272       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2273       // a bit is set in PSInputAddr but not PSInputEnable is where the
2274       // frontend set up an input arg for a particular interpolation mode, but
2275       // nothing uses that input arg. Really we should have an earlier pass
2276       // that removes such an arg.)
2277       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2278       if ((PsInputBits & 0x7F) == 0 ||
2279           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2280         Info->markPSInputEnabled(
2281             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2282     }
2283   } else if (IsKernel) {
2284     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2285   } else {
2286     Splits.append(Ins.begin(), Ins.end());
2287   }
2288 
2289   if (IsEntryFunc) {
2290     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2291     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2292   } else {
2293     // For the fixed ABI, pass workitem IDs in the last argument register.
2294     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2295       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2296   }
2297 
2298   if (IsKernel) {
2299     analyzeFormalArgumentsCompute(CCInfo, Ins);
2300   } else {
2301     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2302     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2303   }
2304 
2305   SmallVector<SDValue, 16> Chains;
2306 
2307   // FIXME: This is the minimum kernel argument alignment. We should improve
2308   // this to the maximum alignment of the arguments.
2309   //
2310   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2311   // kern arg offset.
2312   const Align KernelArgBaseAlign = Align(16);
2313 
2314   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2315     const ISD::InputArg &Arg = Ins[i];
2316     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2317       InVals.push_back(DAG.getUNDEF(Arg.VT));
2318       continue;
2319     }
2320 
2321     CCValAssign &VA = ArgLocs[ArgIdx++];
2322     MVT VT = VA.getLocVT();
2323 
2324     if (IsEntryFunc && VA.isMemLoc()) {
2325       VT = Ins[i].VT;
2326       EVT MemVT = VA.getLocVT();
2327 
2328       const uint64_t Offset = VA.getLocMemOffset();
2329       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2330 
2331       if (Arg.Flags.isByRef()) {
2332         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2333 
2334         const GCNTargetMachine &TM =
2335             static_cast<const GCNTargetMachine &>(getTargetMachine());
2336         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2337                                     Arg.Flags.getPointerAddrSpace())) {
2338           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2339                                      Arg.Flags.getPointerAddrSpace());
2340         }
2341 
2342         InVals.push_back(Ptr);
2343         continue;
2344       }
2345 
2346       SDValue Arg = lowerKernargMemParameter(
2347         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2348       Chains.push_back(Arg.getValue(1));
2349 
2350       auto *ParamTy =
2351         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2352       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2353           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2354                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2355         // On SI local pointers are just offsets into LDS, so they are always
2356         // less than 16-bits.  On CI and newer they could potentially be
2357         // real pointers, so we can't guarantee their size.
2358         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2359                           DAG.getValueType(MVT::i16));
2360       }
2361 
2362       InVals.push_back(Arg);
2363       continue;
2364     } else if (!IsEntryFunc && VA.isMemLoc()) {
2365       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2366       InVals.push_back(Val);
2367       if (!Arg.Flags.isByVal())
2368         Chains.push_back(Val.getValue(1));
2369       continue;
2370     }
2371 
2372     assert(VA.isRegLoc() && "Parameter must be in a register!");
2373 
2374     Register Reg = VA.getLocReg();
2375     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2376     EVT ValVT = VA.getValVT();
2377 
2378     Reg = MF.addLiveIn(Reg, RC);
2379     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2380 
2381     if (Arg.Flags.isSRet()) {
2382       // The return object should be reasonably addressable.
2383 
2384       // FIXME: This helps when the return is a real sret. If it is a
2385       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2386       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2387       unsigned NumBits
2388         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2389       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2390         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2391     }
2392 
2393     // If this is an 8 or 16-bit value, it is really passed promoted
2394     // to 32 bits. Insert an assert[sz]ext to capture this, then
2395     // truncate to the right size.
2396     switch (VA.getLocInfo()) {
2397     case CCValAssign::Full:
2398       break;
2399     case CCValAssign::BCvt:
2400       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2401       break;
2402     case CCValAssign::SExt:
2403       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2404                         DAG.getValueType(ValVT));
2405       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2406       break;
2407     case CCValAssign::ZExt:
2408       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2409                         DAG.getValueType(ValVT));
2410       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2411       break;
2412     case CCValAssign::AExt:
2413       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2414       break;
2415     default:
2416       llvm_unreachable("Unknown loc info!");
2417     }
2418 
2419     InVals.push_back(Val);
2420   }
2421 
2422   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2423     // Special inputs come after user arguments.
2424     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2425   }
2426 
2427   // Start adding system SGPRs.
2428   if (IsEntryFunc) {
2429     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2430   } else {
2431     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2432     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2433   }
2434 
2435   auto &ArgUsageInfo =
2436     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2437   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2438 
2439   unsigned StackArgSize = CCInfo.getNextStackOffset();
2440   Info->setBytesInStackArgArea(StackArgSize);
2441 
2442   return Chains.empty() ? Chain :
2443     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2444 }
2445 
2446 // TODO: If return values can't fit in registers, we should return as many as
2447 // possible in registers before passing on stack.
2448 bool SITargetLowering::CanLowerReturn(
2449   CallingConv::ID CallConv,
2450   MachineFunction &MF, bool IsVarArg,
2451   const SmallVectorImpl<ISD::OutputArg> &Outs,
2452   LLVMContext &Context) const {
2453   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2454   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2455   // for shaders. Vector types should be explicitly handled by CC.
2456   if (AMDGPU::isEntryFunctionCC(CallConv))
2457     return true;
2458 
2459   SmallVector<CCValAssign, 16> RVLocs;
2460   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2461   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2462 }
2463 
2464 SDValue
2465 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2466                               bool isVarArg,
2467                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2468                               const SmallVectorImpl<SDValue> &OutVals,
2469                               const SDLoc &DL, SelectionDAG &DAG) const {
2470   MachineFunction &MF = DAG.getMachineFunction();
2471   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2472 
2473   if (AMDGPU::isKernel(CallConv)) {
2474     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2475                                              OutVals, DL, DAG);
2476   }
2477 
2478   bool IsShader = AMDGPU::isShader(CallConv);
2479 
2480   Info->setIfReturnsVoid(Outs.empty());
2481   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2482 
2483   // CCValAssign - represent the assignment of the return value to a location.
2484   SmallVector<CCValAssign, 48> RVLocs;
2485   SmallVector<ISD::OutputArg, 48> Splits;
2486 
2487   // CCState - Info about the registers and stack slots.
2488   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2489                  *DAG.getContext());
2490 
2491   // Analyze outgoing return values.
2492   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2493 
2494   SDValue Flag;
2495   SmallVector<SDValue, 48> RetOps;
2496   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2497 
2498   // Add return address for callable functions.
2499   if (!Info->isEntryFunction()) {
2500     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2501     SDValue ReturnAddrReg = CreateLiveInRegister(
2502       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2503 
2504     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2505         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2506         MVT::i64);
2507     Chain =
2508         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2509     Flag = Chain.getValue(1);
2510     RetOps.push_back(ReturnAddrVirtualReg);
2511   }
2512 
2513   // Copy the result values into the output registers.
2514   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2515        ++I, ++RealRVLocIdx) {
2516     CCValAssign &VA = RVLocs[I];
2517     assert(VA.isRegLoc() && "Can only return in registers!");
2518     // TODO: Partially return in registers if return values don't fit.
2519     SDValue Arg = OutVals[RealRVLocIdx];
2520 
2521     // Copied from other backends.
2522     switch (VA.getLocInfo()) {
2523     case CCValAssign::Full:
2524       break;
2525     case CCValAssign::BCvt:
2526       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2527       break;
2528     case CCValAssign::SExt:
2529       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2530       break;
2531     case CCValAssign::ZExt:
2532       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2533       break;
2534     case CCValAssign::AExt:
2535       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2536       break;
2537     default:
2538       llvm_unreachable("Unknown loc info!");
2539     }
2540 
2541     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2542     Flag = Chain.getValue(1);
2543     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2544   }
2545 
2546   // FIXME: Does sret work properly?
2547   if (!Info->isEntryFunction()) {
2548     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2549     const MCPhysReg *I =
2550       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2551     if (I) {
2552       for (; *I; ++I) {
2553         if (AMDGPU::SReg_64RegClass.contains(*I))
2554           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2555         else if (AMDGPU::SReg_32RegClass.contains(*I))
2556           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2557         else
2558           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2559       }
2560     }
2561   }
2562 
2563   // Update chain and glue.
2564   RetOps[0] = Chain;
2565   if (Flag.getNode())
2566     RetOps.push_back(Flag);
2567 
2568   unsigned Opc = AMDGPUISD::ENDPGM;
2569   if (!IsWaveEnd)
2570     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2571   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2572 }
2573 
2574 SDValue SITargetLowering::LowerCallResult(
2575     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2576     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2577     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2578     SDValue ThisVal) const {
2579   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2580 
2581   // Assign locations to each value returned by this call.
2582   SmallVector<CCValAssign, 16> RVLocs;
2583   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2584                  *DAG.getContext());
2585   CCInfo.AnalyzeCallResult(Ins, RetCC);
2586 
2587   // Copy all of the result registers out of their specified physreg.
2588   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2589     CCValAssign VA = RVLocs[i];
2590     SDValue Val;
2591 
2592     if (VA.isRegLoc()) {
2593       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2594       Chain = Val.getValue(1);
2595       InFlag = Val.getValue(2);
2596     } else if (VA.isMemLoc()) {
2597       report_fatal_error("TODO: return values in memory");
2598     } else
2599       llvm_unreachable("unknown argument location type");
2600 
2601     switch (VA.getLocInfo()) {
2602     case CCValAssign::Full:
2603       break;
2604     case CCValAssign::BCvt:
2605       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2606       break;
2607     case CCValAssign::ZExt:
2608       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2609                         DAG.getValueType(VA.getValVT()));
2610       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2611       break;
2612     case CCValAssign::SExt:
2613       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2614                         DAG.getValueType(VA.getValVT()));
2615       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2616       break;
2617     case CCValAssign::AExt:
2618       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2619       break;
2620     default:
2621       llvm_unreachable("Unknown loc info!");
2622     }
2623 
2624     InVals.push_back(Val);
2625   }
2626 
2627   return Chain;
2628 }
2629 
2630 // Add code to pass special inputs required depending on used features separate
2631 // from the explicit user arguments present in the IR.
2632 void SITargetLowering::passSpecialInputs(
2633     CallLoweringInfo &CLI,
2634     CCState &CCInfo,
2635     const SIMachineFunctionInfo &Info,
2636     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2637     SmallVectorImpl<SDValue> &MemOpChains,
2638     SDValue Chain) const {
2639   // If we don't have a call site, this was a call inserted by
2640   // legalization. These can never use special inputs.
2641   if (!CLI.CB)
2642     return;
2643 
2644   SelectionDAG &DAG = CLI.DAG;
2645   const SDLoc &DL = CLI.DL;
2646 
2647   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2648   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2649 
2650   const AMDGPUFunctionArgInfo *CalleeArgInfo
2651     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2652   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2653     auto &ArgUsageInfo =
2654       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2655     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2656   }
2657 
2658   // TODO: Unify with private memory register handling. This is complicated by
2659   // the fact that at least in kernels, the input argument is not necessarily
2660   // in the same location as the input.
2661   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2662     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2663     AMDGPUFunctionArgInfo::QUEUE_PTR,
2664     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2665     AMDGPUFunctionArgInfo::DISPATCH_ID,
2666     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2667     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2668     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2669   };
2670 
2671   for (auto InputID : InputRegs) {
2672     const ArgDescriptor *OutgoingArg;
2673     const TargetRegisterClass *ArgRC;
2674     LLT ArgTy;
2675 
2676     std::tie(OutgoingArg, ArgRC, ArgTy) =
2677         CalleeArgInfo->getPreloadedValue(InputID);
2678     if (!OutgoingArg)
2679       continue;
2680 
2681     const ArgDescriptor *IncomingArg;
2682     const TargetRegisterClass *IncomingArgRC;
2683     LLT Ty;
2684     std::tie(IncomingArg, IncomingArgRC, Ty) =
2685         CallerArgInfo.getPreloadedValue(InputID);
2686     assert(IncomingArgRC == ArgRC);
2687 
2688     // All special arguments are ints for now.
2689     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2690     SDValue InputReg;
2691 
2692     if (IncomingArg) {
2693       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2694     } else {
2695       // The implicit arg ptr is special because it doesn't have a corresponding
2696       // input for kernels, and is computed from the kernarg segment pointer.
2697       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2698       InputReg = getImplicitArgPtr(DAG, DL);
2699     }
2700 
2701     if (OutgoingArg->isRegister()) {
2702       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2703       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2704         report_fatal_error("failed to allocate implicit input argument");
2705     } else {
2706       unsigned SpecialArgOffset =
2707           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2708       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2709                                               SpecialArgOffset);
2710       MemOpChains.push_back(ArgStore);
2711     }
2712   }
2713 
2714   // Pack workitem IDs into a single register or pass it as is if already
2715   // packed.
2716   const ArgDescriptor *OutgoingArg;
2717   const TargetRegisterClass *ArgRC;
2718   LLT Ty;
2719 
2720   std::tie(OutgoingArg, ArgRC, Ty) =
2721       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2722   if (!OutgoingArg)
2723     std::tie(OutgoingArg, ArgRC, Ty) =
2724         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2725   if (!OutgoingArg)
2726     std::tie(OutgoingArg, ArgRC, Ty) =
2727         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2728   if (!OutgoingArg)
2729     return;
2730 
2731   const ArgDescriptor *IncomingArgX = std::get<0>(
2732       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2733   const ArgDescriptor *IncomingArgY = std::get<0>(
2734       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2735   const ArgDescriptor *IncomingArgZ = std::get<0>(
2736       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2737 
2738   SDValue InputReg;
2739   SDLoc SL;
2740 
2741   // If incoming ids are not packed we need to pack them.
2742   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2743     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2744 
2745   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2746     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2747     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2748                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2749     InputReg = InputReg.getNode() ?
2750                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2751   }
2752 
2753   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2754     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2755     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2756                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2757     InputReg = InputReg.getNode() ?
2758                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2759   }
2760 
2761   if (!InputReg.getNode()) {
2762     // Workitem ids are already packed, any of present incoming arguments
2763     // will carry all required fields.
2764     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2765       IncomingArgX ? *IncomingArgX :
2766       IncomingArgY ? *IncomingArgY :
2767                      *IncomingArgZ, ~0u);
2768     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2769   }
2770 
2771   if (OutgoingArg->isRegister()) {
2772     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2773     CCInfo.AllocateReg(OutgoingArg->getRegister());
2774   } else {
2775     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2776     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2777                                             SpecialArgOffset);
2778     MemOpChains.push_back(ArgStore);
2779   }
2780 }
2781 
2782 static bool canGuaranteeTCO(CallingConv::ID CC) {
2783   return CC == CallingConv::Fast;
2784 }
2785 
2786 /// Return true if we might ever do TCO for calls with this calling convention.
2787 static bool mayTailCallThisCC(CallingConv::ID CC) {
2788   switch (CC) {
2789   case CallingConv::C:
2790     return true;
2791   default:
2792     return canGuaranteeTCO(CC);
2793   }
2794 }
2795 
2796 bool SITargetLowering::isEligibleForTailCallOptimization(
2797     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2798     const SmallVectorImpl<ISD::OutputArg> &Outs,
2799     const SmallVectorImpl<SDValue> &OutVals,
2800     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2801   if (!mayTailCallThisCC(CalleeCC))
2802     return false;
2803 
2804   MachineFunction &MF = DAG.getMachineFunction();
2805   const Function &CallerF = MF.getFunction();
2806   CallingConv::ID CallerCC = CallerF.getCallingConv();
2807   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2808   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2809 
2810   // Kernels aren't callable, and don't have a live in return address so it
2811   // doesn't make sense to do a tail call with entry functions.
2812   if (!CallerPreserved)
2813     return false;
2814 
2815   bool CCMatch = CallerCC == CalleeCC;
2816 
2817   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2818     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2819       return true;
2820     return false;
2821   }
2822 
2823   // TODO: Can we handle var args?
2824   if (IsVarArg)
2825     return false;
2826 
2827   for (const Argument &Arg : CallerF.args()) {
2828     if (Arg.hasByValAttr())
2829       return false;
2830   }
2831 
2832   LLVMContext &Ctx = *DAG.getContext();
2833 
2834   // Check that the call results are passed in the same way.
2835   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2836                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2837                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2838     return false;
2839 
2840   // The callee has to preserve all registers the caller needs to preserve.
2841   if (!CCMatch) {
2842     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2843     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2844       return false;
2845   }
2846 
2847   // Nothing more to check if the callee is taking no arguments.
2848   if (Outs.empty())
2849     return true;
2850 
2851   SmallVector<CCValAssign, 16> ArgLocs;
2852   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2853 
2854   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2855 
2856   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2857   // If the stack arguments for this call do not fit into our own save area then
2858   // the call cannot be made tail.
2859   // TODO: Is this really necessary?
2860   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2861     return false;
2862 
2863   const MachineRegisterInfo &MRI = MF.getRegInfo();
2864   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2865 }
2866 
2867 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2868   if (!CI->isTailCall())
2869     return false;
2870 
2871   const Function *ParentFn = CI->getParent()->getParent();
2872   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2873     return false;
2874   return true;
2875 }
2876 
2877 // The wave scratch offset register is used as the global base pointer.
2878 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2879                                     SmallVectorImpl<SDValue> &InVals) const {
2880   SelectionDAG &DAG = CLI.DAG;
2881   const SDLoc &DL = CLI.DL;
2882   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2883   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2884   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2885   SDValue Chain = CLI.Chain;
2886   SDValue Callee = CLI.Callee;
2887   bool &IsTailCall = CLI.IsTailCall;
2888   CallingConv::ID CallConv = CLI.CallConv;
2889   bool IsVarArg = CLI.IsVarArg;
2890   bool IsSibCall = false;
2891   bool IsThisReturn = false;
2892   MachineFunction &MF = DAG.getMachineFunction();
2893 
2894   if (Callee.isUndef() || isNullConstant(Callee)) {
2895     if (!CLI.IsTailCall) {
2896       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2897         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2898     }
2899 
2900     return Chain;
2901   }
2902 
2903   if (IsVarArg) {
2904     return lowerUnhandledCall(CLI, InVals,
2905                               "unsupported call to variadic function ");
2906   }
2907 
2908   if (!CLI.CB)
2909     report_fatal_error("unsupported libcall legalization");
2910 
2911   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2912       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2913     return lowerUnhandledCall(CLI, InVals,
2914                               "unsupported indirect call to function ");
2915   }
2916 
2917   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2918     return lowerUnhandledCall(CLI, InVals,
2919                               "unsupported required tail call to function ");
2920   }
2921 
2922   if (AMDGPU::isShader(CallConv)) {
2923     // Note the issue is with the CC of the called function, not of the call
2924     // itself.
2925     return lowerUnhandledCall(CLI, InVals,
2926                               "unsupported call to a shader function ");
2927   }
2928 
2929   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2930       CallConv != CallingConv::AMDGPU_Gfx) {
2931     // Only allow calls with specific calling conventions.
2932     return lowerUnhandledCall(CLI, InVals,
2933                               "unsupported calling convention for call from "
2934                               "graphics shader of function ");
2935   }
2936 
2937   if (IsTailCall) {
2938     IsTailCall = isEligibleForTailCallOptimization(
2939       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2940     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2941       report_fatal_error("failed to perform tail call elimination on a call "
2942                          "site marked musttail");
2943     }
2944 
2945     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2946 
2947     // A sibling call is one where we're under the usual C ABI and not planning
2948     // to change that but can still do a tail call:
2949     if (!TailCallOpt && IsTailCall)
2950       IsSibCall = true;
2951 
2952     if (IsTailCall)
2953       ++NumTailCalls;
2954   }
2955 
2956   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2957   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2958   SmallVector<SDValue, 8> MemOpChains;
2959 
2960   // Analyze operands of the call, assigning locations to each operand.
2961   SmallVector<CCValAssign, 16> ArgLocs;
2962   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2963   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2964 
2965   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
2966       CallConv != CallingConv::AMDGPU_Gfx) {
2967     // With a fixed ABI, allocate fixed registers before user arguments.
2968     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2969   }
2970 
2971   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2972 
2973   // Get a count of how many bytes are to be pushed on the stack.
2974   unsigned NumBytes = CCInfo.getNextStackOffset();
2975 
2976   if (IsSibCall) {
2977     // Since we're not changing the ABI to make this a tail call, the memory
2978     // operands are already available in the caller's incoming argument space.
2979     NumBytes = 0;
2980   }
2981 
2982   // FPDiff is the byte offset of the call's argument area from the callee's.
2983   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2984   // by this amount for a tail call. In a sibling call it must be 0 because the
2985   // caller will deallocate the entire stack and the callee still expects its
2986   // arguments to begin at SP+0. Completely unused for non-tail calls.
2987   int32_t FPDiff = 0;
2988   MachineFrameInfo &MFI = MF.getFrameInfo();
2989 
2990   // Adjust the stack pointer for the new arguments...
2991   // These operations are automatically eliminated by the prolog/epilog pass
2992   if (!IsSibCall) {
2993     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2994 
2995     if (!Subtarget->enableFlatScratch()) {
2996       SmallVector<SDValue, 4> CopyFromChains;
2997 
2998       // In the HSA case, this should be an identity copy.
2999       SDValue ScratchRSrcReg
3000         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3001       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3002       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3003       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3004     }
3005   }
3006 
3007   MVT PtrVT = MVT::i32;
3008 
3009   // Walk the register/memloc assignments, inserting copies/loads.
3010   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3011     CCValAssign &VA = ArgLocs[i];
3012     SDValue Arg = OutVals[i];
3013 
3014     // Promote the value if needed.
3015     switch (VA.getLocInfo()) {
3016     case CCValAssign::Full:
3017       break;
3018     case CCValAssign::BCvt:
3019       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3020       break;
3021     case CCValAssign::ZExt:
3022       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3023       break;
3024     case CCValAssign::SExt:
3025       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3026       break;
3027     case CCValAssign::AExt:
3028       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3029       break;
3030     case CCValAssign::FPExt:
3031       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3032       break;
3033     default:
3034       llvm_unreachable("Unknown loc info!");
3035     }
3036 
3037     if (VA.isRegLoc()) {
3038       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3039     } else {
3040       assert(VA.isMemLoc());
3041 
3042       SDValue DstAddr;
3043       MachinePointerInfo DstInfo;
3044 
3045       unsigned LocMemOffset = VA.getLocMemOffset();
3046       int32_t Offset = LocMemOffset;
3047 
3048       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3049       MaybeAlign Alignment;
3050 
3051       if (IsTailCall) {
3052         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3053         unsigned OpSize = Flags.isByVal() ?
3054           Flags.getByValSize() : VA.getValVT().getStoreSize();
3055 
3056         // FIXME: We can have better than the minimum byval required alignment.
3057         Alignment =
3058             Flags.isByVal()
3059                 ? Flags.getNonZeroByValAlign()
3060                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3061 
3062         Offset = Offset + FPDiff;
3063         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3064 
3065         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3066         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3067 
3068         // Make sure any stack arguments overlapping with where we're storing
3069         // are loaded before this eventual operation. Otherwise they'll be
3070         // clobbered.
3071 
3072         // FIXME: Why is this really necessary? This seems to just result in a
3073         // lot of code to copy the stack and write them back to the same
3074         // locations, which are supposed to be immutable?
3075         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3076       } else {
3077         DstAddr = PtrOff;
3078         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3079         Alignment =
3080             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3081       }
3082 
3083       if (Outs[i].Flags.isByVal()) {
3084         SDValue SizeNode =
3085             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3086         SDValue Cpy =
3087             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3088                           Outs[i].Flags.getNonZeroByValAlign(),
3089                           /*isVol = */ false, /*AlwaysInline = */ true,
3090                           /*isTailCall = */ false, DstInfo,
3091                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3092 
3093         MemOpChains.push_back(Cpy);
3094       } else {
3095         SDValue Store =
3096             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3097         MemOpChains.push_back(Store);
3098       }
3099     }
3100   }
3101 
3102   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3103       CallConv != CallingConv::AMDGPU_Gfx) {
3104     // Copy special input registers after user input arguments.
3105     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3106   }
3107 
3108   if (!MemOpChains.empty())
3109     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3110 
3111   // Build a sequence of copy-to-reg nodes chained together with token chain
3112   // and flag operands which copy the outgoing args into the appropriate regs.
3113   SDValue InFlag;
3114   for (auto &RegToPass : RegsToPass) {
3115     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3116                              RegToPass.second, InFlag);
3117     InFlag = Chain.getValue(1);
3118   }
3119 
3120 
3121   SDValue PhysReturnAddrReg;
3122   if (IsTailCall) {
3123     // Since the return is being combined with the call, we need to pass on the
3124     // return address.
3125 
3126     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3127     SDValue ReturnAddrReg = CreateLiveInRegister(
3128       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3129 
3130     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3131                                         MVT::i64);
3132     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3133     InFlag = Chain.getValue(1);
3134   }
3135 
3136   // We don't usually want to end the call-sequence here because we would tidy
3137   // the frame up *after* the call, however in the ABI-changing tail-call case
3138   // we've carefully laid out the parameters so that when sp is reset they'll be
3139   // in the correct location.
3140   if (IsTailCall && !IsSibCall) {
3141     Chain = DAG.getCALLSEQ_END(Chain,
3142                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3143                                DAG.getTargetConstant(0, DL, MVT::i32),
3144                                InFlag, DL);
3145     InFlag = Chain.getValue(1);
3146   }
3147 
3148   std::vector<SDValue> Ops;
3149   Ops.push_back(Chain);
3150   Ops.push_back(Callee);
3151   // Add a redundant copy of the callee global which will not be legalized, as
3152   // we need direct access to the callee later.
3153   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3154     const GlobalValue *GV = GSD->getGlobal();
3155     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3156   } else {
3157     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3158   }
3159 
3160   if (IsTailCall) {
3161     // Each tail call may have to adjust the stack by a different amount, so
3162     // this information must travel along with the operation for eventual
3163     // consumption by emitEpilogue.
3164     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3165 
3166     Ops.push_back(PhysReturnAddrReg);
3167   }
3168 
3169   // Add argument registers to the end of the list so that they are known live
3170   // into the call.
3171   for (auto &RegToPass : RegsToPass) {
3172     Ops.push_back(DAG.getRegister(RegToPass.first,
3173                                   RegToPass.second.getValueType()));
3174   }
3175 
3176   // Add a register mask operand representing the call-preserved registers.
3177 
3178   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3179   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3180   assert(Mask && "Missing call preserved mask for calling convention");
3181   Ops.push_back(DAG.getRegisterMask(Mask));
3182 
3183   if (InFlag.getNode())
3184     Ops.push_back(InFlag);
3185 
3186   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3187 
3188   // If we're doing a tall call, use a TC_RETURN here rather than an
3189   // actual call instruction.
3190   if (IsTailCall) {
3191     MFI.setHasTailCall();
3192     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3193   }
3194 
3195   // Returns a chain and a flag for retval copy to use.
3196   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3197   Chain = Call.getValue(0);
3198   InFlag = Call.getValue(1);
3199 
3200   uint64_t CalleePopBytes = NumBytes;
3201   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3202                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3203                              InFlag, DL);
3204   if (!Ins.empty())
3205     InFlag = Chain.getValue(1);
3206 
3207   // Handle result values, copying them out of physregs into vregs that we
3208   // return.
3209   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3210                          InVals, IsThisReturn,
3211                          IsThisReturn ? OutVals[0] : SDValue());
3212 }
3213 
3214 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3215 // except for applying the wave size scale to the increment amount.
3216 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3217     SDValue Op, SelectionDAG &DAG) const {
3218   const MachineFunction &MF = DAG.getMachineFunction();
3219   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3220 
3221   SDLoc dl(Op);
3222   EVT VT = Op.getValueType();
3223   SDValue Tmp1 = Op;
3224   SDValue Tmp2 = Op.getValue(1);
3225   SDValue Tmp3 = Op.getOperand(2);
3226   SDValue Chain = Tmp1.getOperand(0);
3227 
3228   Register SPReg = Info->getStackPtrOffsetReg();
3229 
3230   // Chain the dynamic stack allocation so that it doesn't modify the stack
3231   // pointer when other instructions are using the stack.
3232   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3233 
3234   SDValue Size  = Tmp2.getOperand(1);
3235   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3236   Chain = SP.getValue(1);
3237   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3238   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3239   const TargetFrameLowering *TFL = ST.getFrameLowering();
3240   unsigned Opc =
3241     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3242     ISD::ADD : ISD::SUB;
3243 
3244   SDValue ScaledSize = DAG.getNode(
3245       ISD::SHL, dl, VT, Size,
3246       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3247 
3248   Align StackAlign = TFL->getStackAlign();
3249   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3250   if (Alignment && *Alignment > StackAlign) {
3251     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3252                        DAG.getConstant(-(uint64_t)Alignment->value()
3253                                            << ST.getWavefrontSizeLog2(),
3254                                        dl, VT));
3255   }
3256 
3257   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3258   Tmp2 = DAG.getCALLSEQ_END(
3259       Chain, DAG.getIntPtrConstant(0, dl, true),
3260       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3261 
3262   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3263 }
3264 
3265 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3266                                                   SelectionDAG &DAG) const {
3267   // We only handle constant sizes here to allow non-entry block, static sized
3268   // allocas. A truly dynamic value is more difficult to support because we
3269   // don't know if the size value is uniform or not. If the size isn't uniform,
3270   // we would need to do a wave reduction to get the maximum size to know how
3271   // much to increment the uniform stack pointer.
3272   SDValue Size = Op.getOperand(1);
3273   if (isa<ConstantSDNode>(Size))
3274       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3275 
3276   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3277 }
3278 
3279 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3280                                              const MachineFunction &MF) const {
3281   Register Reg = StringSwitch<Register>(RegName)
3282     .Case("m0", AMDGPU::M0)
3283     .Case("exec", AMDGPU::EXEC)
3284     .Case("exec_lo", AMDGPU::EXEC_LO)
3285     .Case("exec_hi", AMDGPU::EXEC_HI)
3286     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3287     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3288     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3289     .Default(Register());
3290 
3291   if (Reg == AMDGPU::NoRegister) {
3292     report_fatal_error(Twine("invalid register name \""
3293                              + StringRef(RegName)  + "\"."));
3294 
3295   }
3296 
3297   if (!Subtarget->hasFlatScrRegister() &&
3298        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3299     report_fatal_error(Twine("invalid register \""
3300                              + StringRef(RegName)  + "\" for subtarget."));
3301   }
3302 
3303   switch (Reg) {
3304   case AMDGPU::M0:
3305   case AMDGPU::EXEC_LO:
3306   case AMDGPU::EXEC_HI:
3307   case AMDGPU::FLAT_SCR_LO:
3308   case AMDGPU::FLAT_SCR_HI:
3309     if (VT.getSizeInBits() == 32)
3310       return Reg;
3311     break;
3312   case AMDGPU::EXEC:
3313   case AMDGPU::FLAT_SCR:
3314     if (VT.getSizeInBits() == 64)
3315       return Reg;
3316     break;
3317   default:
3318     llvm_unreachable("missing register type checking");
3319   }
3320 
3321   report_fatal_error(Twine("invalid type for register \""
3322                            + StringRef(RegName) + "\"."));
3323 }
3324 
3325 // If kill is not the last instruction, split the block so kill is always a
3326 // proper terminator.
3327 MachineBasicBlock *
3328 SITargetLowering::splitKillBlock(MachineInstr &MI,
3329                                  MachineBasicBlock *BB) const {
3330   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3331   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3332   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3333   return SplitBB;
3334 }
3335 
3336 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3337 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3338 // be the first instruction in the remainder block.
3339 //
3340 /// \returns { LoopBody, Remainder }
3341 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3342 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3343   MachineFunction *MF = MBB.getParent();
3344   MachineBasicBlock::iterator I(&MI);
3345 
3346   // To insert the loop we need to split the block. Move everything after this
3347   // point to a new block, and insert a new empty block between the two.
3348   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3349   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3350   MachineFunction::iterator MBBI(MBB);
3351   ++MBBI;
3352 
3353   MF->insert(MBBI, LoopBB);
3354   MF->insert(MBBI, RemainderBB);
3355 
3356   LoopBB->addSuccessor(LoopBB);
3357   LoopBB->addSuccessor(RemainderBB);
3358 
3359   // Move the rest of the block into a new block.
3360   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3361 
3362   if (InstInLoop) {
3363     auto Next = std::next(I);
3364 
3365     // Move instruction to loop body.
3366     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3367 
3368     // Move the rest of the block.
3369     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3370   } else {
3371     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3372   }
3373 
3374   MBB.addSuccessor(LoopBB);
3375 
3376   return std::make_pair(LoopBB, RemainderBB);
3377 }
3378 
3379 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3380 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3381   MachineBasicBlock *MBB = MI.getParent();
3382   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3383   auto I = MI.getIterator();
3384   auto E = std::next(I);
3385 
3386   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3387     .addImm(0);
3388 
3389   MIBundleBuilder Bundler(*MBB, I, E);
3390   finalizeBundle(*MBB, Bundler.begin());
3391 }
3392 
3393 MachineBasicBlock *
3394 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3395                                          MachineBasicBlock *BB) const {
3396   const DebugLoc &DL = MI.getDebugLoc();
3397 
3398   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3399 
3400   MachineBasicBlock *LoopBB;
3401   MachineBasicBlock *RemainderBB;
3402   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3403 
3404   // Apparently kill flags are only valid if the def is in the same block?
3405   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3406     Src->setIsKill(false);
3407 
3408   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3409 
3410   MachineBasicBlock::iterator I = LoopBB->end();
3411 
3412   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3413     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3414 
3415   // Clear TRAP_STS.MEM_VIOL
3416   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3417     .addImm(0)
3418     .addImm(EncodedReg);
3419 
3420   bundleInstWithWaitcnt(MI);
3421 
3422   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3423 
3424   // Load and check TRAP_STS.MEM_VIOL
3425   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3426     .addImm(EncodedReg);
3427 
3428   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3429   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3430     .addReg(Reg, RegState::Kill)
3431     .addImm(0);
3432   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3433     .addMBB(LoopBB);
3434 
3435   return RemainderBB;
3436 }
3437 
3438 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3439 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3440 // will only do one iteration. In the worst case, this will loop 64 times.
3441 //
3442 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3443 static MachineBasicBlock::iterator
3444 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3445                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3446                        const DebugLoc &DL, const MachineOperand &Idx,
3447                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3448                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3449                        Register &SGPRIdxReg) {
3450 
3451   MachineFunction *MF = OrigBB.getParent();
3452   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3453   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3454   MachineBasicBlock::iterator I = LoopBB.begin();
3455 
3456   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3457   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3458   Register NewExec = MRI.createVirtualRegister(BoolRC);
3459   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3460   Register CondReg = MRI.createVirtualRegister(BoolRC);
3461 
3462   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3463     .addReg(InitReg)
3464     .addMBB(&OrigBB)
3465     .addReg(ResultReg)
3466     .addMBB(&LoopBB);
3467 
3468   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3469     .addReg(InitSaveExecReg)
3470     .addMBB(&OrigBB)
3471     .addReg(NewExec)
3472     .addMBB(&LoopBB);
3473 
3474   // Read the next variant <- also loop target.
3475   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3476       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3477 
3478   // Compare the just read M0 value to all possible Idx values.
3479   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3480       .addReg(CurrentIdxReg)
3481       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3482 
3483   // Update EXEC, save the original EXEC value to VCC.
3484   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3485                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3486           NewExec)
3487     .addReg(CondReg, RegState::Kill);
3488 
3489   MRI.setSimpleHint(NewExec, CondReg);
3490 
3491   if (UseGPRIdxMode) {
3492     if (Offset == 0) {
3493       SGPRIdxReg = CurrentIdxReg;
3494     } else {
3495       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3496       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3497           .addReg(CurrentIdxReg, RegState::Kill)
3498           .addImm(Offset);
3499     }
3500   } else {
3501     // Move index from VCC into M0
3502     if (Offset == 0) {
3503       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3504         .addReg(CurrentIdxReg, RegState::Kill);
3505     } else {
3506       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3507         .addReg(CurrentIdxReg, RegState::Kill)
3508         .addImm(Offset);
3509     }
3510   }
3511 
3512   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3513   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3514   MachineInstr *InsertPt =
3515     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3516                                                   : AMDGPU::S_XOR_B64_term), Exec)
3517       .addReg(Exec)
3518       .addReg(NewExec);
3519 
3520   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3521   // s_cbranch_scc0?
3522 
3523   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3524   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3525     .addMBB(&LoopBB);
3526 
3527   return InsertPt->getIterator();
3528 }
3529 
3530 // This has slightly sub-optimal regalloc when the source vector is killed by
3531 // the read. The register allocator does not understand that the kill is
3532 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3533 // subregister from it, using 1 more VGPR than necessary. This was saved when
3534 // this was expanded after register allocation.
3535 static MachineBasicBlock::iterator
3536 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3537                unsigned InitResultReg, unsigned PhiReg, int Offset,
3538                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3539   MachineFunction *MF = MBB.getParent();
3540   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3541   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3542   MachineRegisterInfo &MRI = MF->getRegInfo();
3543   const DebugLoc &DL = MI.getDebugLoc();
3544   MachineBasicBlock::iterator I(&MI);
3545 
3546   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3547   Register DstReg = MI.getOperand(0).getReg();
3548   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3549   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3550   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3551   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3552 
3553   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3554 
3555   // Save the EXEC mask
3556   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3557     .addReg(Exec);
3558 
3559   MachineBasicBlock *LoopBB;
3560   MachineBasicBlock *RemainderBB;
3561   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3562 
3563   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3564 
3565   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3566                                       InitResultReg, DstReg, PhiReg, TmpExec,
3567                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3568 
3569   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3570   MachineFunction::iterator MBBI(LoopBB);
3571   ++MBBI;
3572   MF->insert(MBBI, LandingPad);
3573   LoopBB->removeSuccessor(RemainderBB);
3574   LandingPad->addSuccessor(RemainderBB);
3575   LoopBB->addSuccessor(LandingPad);
3576   MachineBasicBlock::iterator First = LandingPad->begin();
3577   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3578     .addReg(SaveExec);
3579 
3580   return InsPt;
3581 }
3582 
3583 // Returns subreg index, offset
3584 static std::pair<unsigned, int>
3585 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3586                             const TargetRegisterClass *SuperRC,
3587                             unsigned VecReg,
3588                             int Offset) {
3589   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3590 
3591   // Skip out of bounds offsets, or else we would end up using an undefined
3592   // register.
3593   if (Offset >= NumElts || Offset < 0)
3594     return std::make_pair(AMDGPU::sub0, Offset);
3595 
3596   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3597 }
3598 
3599 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3600                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3601                                  int Offset) {
3602   MachineBasicBlock *MBB = MI.getParent();
3603   const DebugLoc &DL = MI.getDebugLoc();
3604   MachineBasicBlock::iterator I(&MI);
3605 
3606   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3607 
3608   assert(Idx->getReg() != AMDGPU::NoRegister);
3609 
3610   if (Offset == 0) {
3611     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3612   } else {
3613     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3614         .add(*Idx)
3615         .addImm(Offset);
3616   }
3617 }
3618 
3619 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3620                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3621                                    int Offset) {
3622   MachineBasicBlock *MBB = MI.getParent();
3623   const DebugLoc &DL = MI.getDebugLoc();
3624   MachineBasicBlock::iterator I(&MI);
3625 
3626   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3627 
3628   if (Offset == 0)
3629     return Idx->getReg();
3630 
3631   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3632   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3633       .add(*Idx)
3634       .addImm(Offset);
3635   return Tmp;
3636 }
3637 
3638 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3639                                           MachineBasicBlock &MBB,
3640                                           const GCNSubtarget &ST) {
3641   const SIInstrInfo *TII = ST.getInstrInfo();
3642   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3643   MachineFunction *MF = MBB.getParent();
3644   MachineRegisterInfo &MRI = MF->getRegInfo();
3645 
3646   Register Dst = MI.getOperand(0).getReg();
3647   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3648   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3649   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3650 
3651   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3652   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3653 
3654   unsigned SubReg;
3655   std::tie(SubReg, Offset)
3656     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3657 
3658   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3659 
3660   // Check for a SGPR index.
3661   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3662     MachineBasicBlock::iterator I(&MI);
3663     const DebugLoc &DL = MI.getDebugLoc();
3664 
3665     if (UseGPRIdxMode) {
3666       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3667       // to avoid interfering with other uses, so probably requires a new
3668       // optimization pass.
3669       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3670 
3671       const MCInstrDesc &GPRIDXDesc =
3672           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3673       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3674           .addReg(SrcReg)
3675           .addReg(Idx)
3676           .addImm(SubReg);
3677     } else {
3678       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3679 
3680       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3681         .addReg(SrcReg, 0, SubReg)
3682         .addReg(SrcReg, RegState::Implicit);
3683     }
3684 
3685     MI.eraseFromParent();
3686 
3687     return &MBB;
3688   }
3689 
3690   // Control flow needs to be inserted if indexing with a VGPR.
3691   const DebugLoc &DL = MI.getDebugLoc();
3692   MachineBasicBlock::iterator I(&MI);
3693 
3694   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3695   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3696 
3697   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3698 
3699   Register SGPRIdxReg;
3700   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3701                               UseGPRIdxMode, SGPRIdxReg);
3702 
3703   MachineBasicBlock *LoopBB = InsPt->getParent();
3704 
3705   if (UseGPRIdxMode) {
3706     const MCInstrDesc &GPRIDXDesc =
3707         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3708 
3709     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3710         .addReg(SrcReg)
3711         .addReg(SGPRIdxReg)
3712         .addImm(SubReg);
3713   } else {
3714     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3715       .addReg(SrcReg, 0, SubReg)
3716       .addReg(SrcReg, RegState::Implicit);
3717   }
3718 
3719   MI.eraseFromParent();
3720 
3721   return LoopBB;
3722 }
3723 
3724 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3725                                           MachineBasicBlock &MBB,
3726                                           const GCNSubtarget &ST) {
3727   const SIInstrInfo *TII = ST.getInstrInfo();
3728   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3729   MachineFunction *MF = MBB.getParent();
3730   MachineRegisterInfo &MRI = MF->getRegInfo();
3731 
3732   Register Dst = MI.getOperand(0).getReg();
3733   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3734   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3735   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3736   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3737   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3738   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3739 
3740   // This can be an immediate, but will be folded later.
3741   assert(Val->getReg());
3742 
3743   unsigned SubReg;
3744   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3745                                                          SrcVec->getReg(),
3746                                                          Offset);
3747   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3748 
3749   if (Idx->getReg() == AMDGPU::NoRegister) {
3750     MachineBasicBlock::iterator I(&MI);
3751     const DebugLoc &DL = MI.getDebugLoc();
3752 
3753     assert(Offset == 0);
3754 
3755     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3756         .add(*SrcVec)
3757         .add(*Val)
3758         .addImm(SubReg);
3759 
3760     MI.eraseFromParent();
3761     return &MBB;
3762   }
3763 
3764   // Check for a SGPR index.
3765   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3766     MachineBasicBlock::iterator I(&MI);
3767     const DebugLoc &DL = MI.getDebugLoc();
3768 
3769     if (UseGPRIdxMode) {
3770       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3771 
3772       const MCInstrDesc &GPRIDXDesc =
3773           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3774       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3775           .addReg(SrcVec->getReg())
3776           .add(*Val)
3777           .addReg(Idx)
3778           .addImm(SubReg);
3779     } else {
3780       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3781 
3782       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3783           TRI.getRegSizeInBits(*VecRC), 32, false);
3784       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3785           .addReg(SrcVec->getReg())
3786           .add(*Val)
3787           .addImm(SubReg);
3788     }
3789     MI.eraseFromParent();
3790     return &MBB;
3791   }
3792 
3793   // Control flow needs to be inserted if indexing with a VGPR.
3794   if (Val->isReg())
3795     MRI.clearKillFlags(Val->getReg());
3796 
3797   const DebugLoc &DL = MI.getDebugLoc();
3798 
3799   Register PhiReg = MRI.createVirtualRegister(VecRC);
3800 
3801   Register SGPRIdxReg;
3802   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3803                               UseGPRIdxMode, SGPRIdxReg);
3804   MachineBasicBlock *LoopBB = InsPt->getParent();
3805 
3806   if (UseGPRIdxMode) {
3807     const MCInstrDesc &GPRIDXDesc =
3808         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3809 
3810     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3811         .addReg(PhiReg)
3812         .add(*Val)
3813         .addReg(SGPRIdxReg)
3814         .addImm(AMDGPU::sub0);
3815   } else {
3816     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3817         TRI.getRegSizeInBits(*VecRC), 32, false);
3818     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3819         .addReg(PhiReg)
3820         .add(*Val)
3821         .addImm(AMDGPU::sub0);
3822   }
3823 
3824   MI.eraseFromParent();
3825   return LoopBB;
3826 }
3827 
3828 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3829   MachineInstr &MI, MachineBasicBlock *BB) const {
3830 
3831   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3832   MachineFunction *MF = BB->getParent();
3833   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3834 
3835   switch (MI.getOpcode()) {
3836   case AMDGPU::S_UADDO_PSEUDO:
3837   case AMDGPU::S_USUBO_PSEUDO: {
3838     const DebugLoc &DL = MI.getDebugLoc();
3839     MachineOperand &Dest0 = MI.getOperand(0);
3840     MachineOperand &Dest1 = MI.getOperand(1);
3841     MachineOperand &Src0 = MI.getOperand(2);
3842     MachineOperand &Src1 = MI.getOperand(3);
3843 
3844     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3845                        ? AMDGPU::S_ADD_I32
3846                        : AMDGPU::S_SUB_I32;
3847     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3848 
3849     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3850         .addImm(1)
3851         .addImm(0);
3852 
3853     MI.eraseFromParent();
3854     return BB;
3855   }
3856   case AMDGPU::S_ADD_U64_PSEUDO:
3857   case AMDGPU::S_SUB_U64_PSEUDO: {
3858     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3859     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3860     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3861     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3862     const DebugLoc &DL = MI.getDebugLoc();
3863 
3864     MachineOperand &Dest = MI.getOperand(0);
3865     MachineOperand &Src0 = MI.getOperand(1);
3866     MachineOperand &Src1 = MI.getOperand(2);
3867 
3868     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3869     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3870 
3871     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3872         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3873     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3874         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3875 
3876     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3877         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3878     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3879         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3880 
3881     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3882 
3883     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3884     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3885     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3886     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3887     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3888         .addReg(DestSub0)
3889         .addImm(AMDGPU::sub0)
3890         .addReg(DestSub1)
3891         .addImm(AMDGPU::sub1);
3892     MI.eraseFromParent();
3893     return BB;
3894   }
3895   case AMDGPU::V_ADD_U64_PSEUDO:
3896   case AMDGPU::V_SUB_U64_PSEUDO: {
3897     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3898     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3899     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3900     const DebugLoc &DL = MI.getDebugLoc();
3901 
3902     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3903 
3904     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3905 
3906     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3907     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3908 
3909     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3910     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3911 
3912     MachineOperand &Dest = MI.getOperand(0);
3913     MachineOperand &Src0 = MI.getOperand(1);
3914     MachineOperand &Src1 = MI.getOperand(2);
3915 
3916     const TargetRegisterClass *Src0RC = Src0.isReg()
3917                                             ? MRI.getRegClass(Src0.getReg())
3918                                             : &AMDGPU::VReg_64RegClass;
3919     const TargetRegisterClass *Src1RC = Src1.isReg()
3920                                             ? MRI.getRegClass(Src1.getReg())
3921                                             : &AMDGPU::VReg_64RegClass;
3922 
3923     const TargetRegisterClass *Src0SubRC =
3924         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3925     const TargetRegisterClass *Src1SubRC =
3926         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3927 
3928     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3929         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3930     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3931         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3932 
3933     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3934         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3935     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3936         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3937 
3938     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3939     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3940                                .addReg(CarryReg, RegState::Define)
3941                                .add(SrcReg0Sub0)
3942                                .add(SrcReg1Sub0)
3943                                .addImm(0); // clamp bit
3944 
3945     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3946     MachineInstr *HiHalf =
3947         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3948             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3949             .add(SrcReg0Sub1)
3950             .add(SrcReg1Sub1)
3951             .addReg(CarryReg, RegState::Kill)
3952             .addImm(0); // clamp bit
3953 
3954     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3955         .addReg(DestSub0)
3956         .addImm(AMDGPU::sub0)
3957         .addReg(DestSub1)
3958         .addImm(AMDGPU::sub1);
3959     TII->legalizeOperands(*LoHalf);
3960     TII->legalizeOperands(*HiHalf);
3961     MI.eraseFromParent();
3962     return BB;
3963   }
3964   case AMDGPU::S_ADD_CO_PSEUDO:
3965   case AMDGPU::S_SUB_CO_PSEUDO: {
3966     // This pseudo has a chance to be selected
3967     // only from uniform add/subcarry node. All the VGPR operands
3968     // therefore assumed to be splat vectors.
3969     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3970     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3971     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3972     MachineBasicBlock::iterator MII = MI;
3973     const DebugLoc &DL = MI.getDebugLoc();
3974     MachineOperand &Dest = MI.getOperand(0);
3975     MachineOperand &CarryDest = MI.getOperand(1);
3976     MachineOperand &Src0 = MI.getOperand(2);
3977     MachineOperand &Src1 = MI.getOperand(3);
3978     MachineOperand &Src2 = MI.getOperand(4);
3979     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3980                        ? AMDGPU::S_ADDC_U32
3981                        : AMDGPU::S_SUBB_U32;
3982     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3983       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3984       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3985           .addReg(Src0.getReg());
3986       Src0.setReg(RegOp0);
3987     }
3988     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3989       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3990       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3991           .addReg(Src1.getReg());
3992       Src1.setReg(RegOp1);
3993     }
3994     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3995     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3996       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3997           .addReg(Src2.getReg());
3998       Src2.setReg(RegOp2);
3999     }
4000 
4001     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4002     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4003       if (ST.hasScalarCompareEq64()) {
4004         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4005             .addReg(Src2.getReg())
4006             .addImm(0);
4007       } else {
4008         const TargetRegisterClass *SubRC =
4009             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4010         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4011             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4012         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4013             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4014         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4015 
4016         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4017             .add(Src2Sub0)
4018             .add(Src2Sub1);
4019 
4020         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4021             .addReg(Src2_32, RegState::Kill)
4022             .addImm(0);
4023       }
4024     } else {
4025       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4026           .addReg(Src2.getReg())
4027           .addImm(0);
4028     }
4029 
4030     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4031 
4032     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4033       .addReg(AMDGPU::SCC);
4034     MI.eraseFromParent();
4035     return BB;
4036   }
4037   case AMDGPU::SI_INIT_M0: {
4038     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4039             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4040         .add(MI.getOperand(0));
4041     MI.eraseFromParent();
4042     return BB;
4043   }
4044   case AMDGPU::GET_GROUPSTATICSIZE: {
4045     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4046            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4047     DebugLoc DL = MI.getDebugLoc();
4048     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4049         .add(MI.getOperand(0))
4050         .addImm(MFI->getLDSSize());
4051     MI.eraseFromParent();
4052     return BB;
4053   }
4054   case AMDGPU::SI_INDIRECT_SRC_V1:
4055   case AMDGPU::SI_INDIRECT_SRC_V2:
4056   case AMDGPU::SI_INDIRECT_SRC_V4:
4057   case AMDGPU::SI_INDIRECT_SRC_V8:
4058   case AMDGPU::SI_INDIRECT_SRC_V16:
4059   case AMDGPU::SI_INDIRECT_SRC_V32:
4060     return emitIndirectSrc(MI, *BB, *getSubtarget());
4061   case AMDGPU::SI_INDIRECT_DST_V1:
4062   case AMDGPU::SI_INDIRECT_DST_V2:
4063   case AMDGPU::SI_INDIRECT_DST_V4:
4064   case AMDGPU::SI_INDIRECT_DST_V8:
4065   case AMDGPU::SI_INDIRECT_DST_V16:
4066   case AMDGPU::SI_INDIRECT_DST_V32:
4067     return emitIndirectDst(MI, *BB, *getSubtarget());
4068   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4069   case AMDGPU::SI_KILL_I1_PSEUDO:
4070     return splitKillBlock(MI, BB);
4071   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4072     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4073     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4074     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4075 
4076     Register Dst = MI.getOperand(0).getReg();
4077     Register Src0 = MI.getOperand(1).getReg();
4078     Register Src1 = MI.getOperand(2).getReg();
4079     const DebugLoc &DL = MI.getDebugLoc();
4080     Register SrcCond = MI.getOperand(3).getReg();
4081 
4082     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4083     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4084     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4085     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4086 
4087     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4088       .addReg(SrcCond);
4089     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4090       .addImm(0)
4091       .addReg(Src0, 0, AMDGPU::sub0)
4092       .addImm(0)
4093       .addReg(Src1, 0, AMDGPU::sub0)
4094       .addReg(SrcCondCopy);
4095     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4096       .addImm(0)
4097       .addReg(Src0, 0, AMDGPU::sub1)
4098       .addImm(0)
4099       .addReg(Src1, 0, AMDGPU::sub1)
4100       .addReg(SrcCondCopy);
4101 
4102     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4103       .addReg(DstLo)
4104       .addImm(AMDGPU::sub0)
4105       .addReg(DstHi)
4106       .addImm(AMDGPU::sub1);
4107     MI.eraseFromParent();
4108     return BB;
4109   }
4110   case AMDGPU::SI_BR_UNDEF: {
4111     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4112     const DebugLoc &DL = MI.getDebugLoc();
4113     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4114                            .add(MI.getOperand(0));
4115     Br->getOperand(1).setIsUndef(true); // read undef SCC
4116     MI.eraseFromParent();
4117     return BB;
4118   }
4119   case AMDGPU::ADJCALLSTACKUP:
4120   case AMDGPU::ADJCALLSTACKDOWN: {
4121     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4122     MachineInstrBuilder MIB(*MF, &MI);
4123     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4124        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4125     return BB;
4126   }
4127   case AMDGPU::SI_CALL_ISEL: {
4128     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4129     const DebugLoc &DL = MI.getDebugLoc();
4130 
4131     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4132 
4133     MachineInstrBuilder MIB;
4134     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4135 
4136     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4137       MIB.add(MI.getOperand(I));
4138 
4139     MIB.cloneMemRefs(MI);
4140     MI.eraseFromParent();
4141     return BB;
4142   }
4143   case AMDGPU::V_ADD_CO_U32_e32:
4144   case AMDGPU::V_SUB_CO_U32_e32:
4145   case AMDGPU::V_SUBREV_CO_U32_e32: {
4146     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4147     const DebugLoc &DL = MI.getDebugLoc();
4148     unsigned Opc = MI.getOpcode();
4149 
4150     bool NeedClampOperand = false;
4151     if (TII->pseudoToMCOpcode(Opc) == -1) {
4152       Opc = AMDGPU::getVOPe64(Opc);
4153       NeedClampOperand = true;
4154     }
4155 
4156     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4157     if (TII->isVOP3(*I)) {
4158       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4159       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4160       I.addReg(TRI->getVCC(), RegState::Define);
4161     }
4162     I.add(MI.getOperand(1))
4163      .add(MI.getOperand(2));
4164     if (NeedClampOperand)
4165       I.addImm(0); // clamp bit for e64 encoding
4166 
4167     TII->legalizeOperands(*I);
4168 
4169     MI.eraseFromParent();
4170     return BB;
4171   }
4172   case AMDGPU::DS_GWS_INIT:
4173   case AMDGPU::DS_GWS_SEMA_V:
4174   case AMDGPU::DS_GWS_SEMA_BR:
4175   case AMDGPU::DS_GWS_SEMA_P:
4176   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4177   case AMDGPU::DS_GWS_BARRIER:
4178     // A s_waitcnt 0 is required to be the instruction immediately following.
4179     if (getSubtarget()->hasGWSAutoReplay()) {
4180       bundleInstWithWaitcnt(MI);
4181       return BB;
4182     }
4183 
4184     return emitGWSMemViolTestLoop(MI, BB);
4185   case AMDGPU::S_SETREG_B32: {
4186     // Try to optimize cases that only set the denormal mode or rounding mode.
4187     //
4188     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4189     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4190     // instead.
4191     //
4192     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4193     // allow you to have a no side effect instruction in the output of a
4194     // sideeffecting pattern.
4195     unsigned ID, Offset, Width;
4196     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4197     if (ID != AMDGPU::Hwreg::ID_MODE)
4198       return BB;
4199 
4200     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4201     const unsigned SetMask = WidthMask << Offset;
4202 
4203     if (getSubtarget()->hasDenormModeInst()) {
4204       unsigned SetDenormOp = 0;
4205       unsigned SetRoundOp = 0;
4206 
4207       // The dedicated instructions can only set the whole denorm or round mode
4208       // at once, not a subset of bits in either.
4209       if (SetMask ==
4210           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4211         // If this fully sets both the round and denorm mode, emit the two
4212         // dedicated instructions for these.
4213         SetRoundOp = AMDGPU::S_ROUND_MODE;
4214         SetDenormOp = AMDGPU::S_DENORM_MODE;
4215       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4216         SetRoundOp = AMDGPU::S_ROUND_MODE;
4217       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4218         SetDenormOp = AMDGPU::S_DENORM_MODE;
4219       }
4220 
4221       if (SetRoundOp || SetDenormOp) {
4222         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4223         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4224         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4225           unsigned ImmVal = Def->getOperand(1).getImm();
4226           if (SetRoundOp) {
4227             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4228                 .addImm(ImmVal & 0xf);
4229 
4230             // If we also have the denorm mode, get just the denorm mode bits.
4231             ImmVal >>= 4;
4232           }
4233 
4234           if (SetDenormOp) {
4235             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4236                 .addImm(ImmVal & 0xf);
4237           }
4238 
4239           MI.eraseFromParent();
4240           return BB;
4241         }
4242       }
4243     }
4244 
4245     // If only FP bits are touched, used the no side effects pseudo.
4246     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4247                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4248       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4249 
4250     return BB;
4251   }
4252   default:
4253     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4254   }
4255 }
4256 
4257 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4258   return isTypeLegal(VT.getScalarType());
4259 }
4260 
4261 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4262   // This currently forces unfolding various combinations of fsub into fma with
4263   // free fneg'd operands. As long as we have fast FMA (controlled by
4264   // isFMAFasterThanFMulAndFAdd), we should perform these.
4265 
4266   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4267   // most of these combines appear to be cycle neutral but save on instruction
4268   // count / code size.
4269   return true;
4270 }
4271 
4272 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4273                                          EVT VT) const {
4274   if (!VT.isVector()) {
4275     return MVT::i1;
4276   }
4277   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4278 }
4279 
4280 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4281   // TODO: Should i16 be used always if legal? For now it would force VALU
4282   // shifts.
4283   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4284 }
4285 
4286 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4287   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4288              ? Ty.changeElementSize(16)
4289              : Ty.changeElementSize(32);
4290 }
4291 
4292 // Answering this is somewhat tricky and depends on the specific device which
4293 // have different rates for fma or all f64 operations.
4294 //
4295 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4296 // regardless of which device (although the number of cycles differs between
4297 // devices), so it is always profitable for f64.
4298 //
4299 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4300 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4301 // which we can always do even without fused FP ops since it returns the same
4302 // result as the separate operations and since it is always full
4303 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4304 // however does not support denormals, so we do report fma as faster if we have
4305 // a fast fma device and require denormals.
4306 //
4307 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4308                                                   EVT VT) const {
4309   VT = VT.getScalarType();
4310 
4311   switch (VT.getSimpleVT().SimpleTy) {
4312   case MVT::f32: {
4313     // If mad is not available this depends only on if f32 fma is full rate.
4314     if (!Subtarget->hasMadMacF32Insts())
4315       return Subtarget->hasFastFMAF32();
4316 
4317     // Otherwise f32 mad is always full rate and returns the same result as
4318     // the separate operations so should be preferred over fma.
4319     // However does not support denomals.
4320     if (hasFP32Denormals(MF))
4321       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4322 
4323     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4324     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4325   }
4326   case MVT::f64:
4327     return true;
4328   case MVT::f16:
4329     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4330   default:
4331     break;
4332   }
4333 
4334   return false;
4335 }
4336 
4337 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4338                                    const SDNode *N) const {
4339   // TODO: Check future ftz flag
4340   // v_mad_f32/v_mac_f32 do not support denormals.
4341   EVT VT = N->getValueType(0);
4342   if (VT == MVT::f32)
4343     return Subtarget->hasMadMacF32Insts() &&
4344            !hasFP32Denormals(DAG.getMachineFunction());
4345   if (VT == MVT::f16) {
4346     return Subtarget->hasMadF16() &&
4347            !hasFP64FP16Denormals(DAG.getMachineFunction());
4348   }
4349 
4350   return false;
4351 }
4352 
4353 //===----------------------------------------------------------------------===//
4354 // Custom DAG Lowering Operations
4355 //===----------------------------------------------------------------------===//
4356 
4357 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4358 // wider vector type is legal.
4359 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4360                                              SelectionDAG &DAG) const {
4361   unsigned Opc = Op.getOpcode();
4362   EVT VT = Op.getValueType();
4363   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4364 
4365   SDValue Lo, Hi;
4366   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4367 
4368   SDLoc SL(Op);
4369   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4370                              Op->getFlags());
4371   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4372                              Op->getFlags());
4373 
4374   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4375 }
4376 
4377 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4378 // wider vector type is legal.
4379 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4380                                               SelectionDAG &DAG) const {
4381   unsigned Opc = Op.getOpcode();
4382   EVT VT = Op.getValueType();
4383   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4384 
4385   SDValue Lo0, Hi0;
4386   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4387   SDValue Lo1, Hi1;
4388   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4389 
4390   SDLoc SL(Op);
4391 
4392   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4393                              Op->getFlags());
4394   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4395                              Op->getFlags());
4396 
4397   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4398 }
4399 
4400 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4401                                               SelectionDAG &DAG) const {
4402   unsigned Opc = Op.getOpcode();
4403   EVT VT = Op.getValueType();
4404   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4405 
4406   SDValue Lo0, Hi0;
4407   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4408   SDValue Lo1, Hi1;
4409   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4410   SDValue Lo2, Hi2;
4411   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4412 
4413   SDLoc SL(Op);
4414 
4415   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4416                              Op->getFlags());
4417   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4418                              Op->getFlags());
4419 
4420   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4421 }
4422 
4423 
4424 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4425   switch (Op.getOpcode()) {
4426   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4427   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4428   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4429   case ISD::LOAD: {
4430     SDValue Result = LowerLOAD(Op, DAG);
4431     assert((!Result.getNode() ||
4432             Result.getNode()->getNumValues() == 2) &&
4433            "Load should return a value and a chain");
4434     return Result;
4435   }
4436 
4437   case ISD::FSIN:
4438   case ISD::FCOS:
4439     return LowerTrig(Op, DAG);
4440   case ISD::SELECT: return LowerSELECT(Op, DAG);
4441   case ISD::FDIV: return LowerFDIV(Op, DAG);
4442   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4443   case ISD::STORE: return LowerSTORE(Op, DAG);
4444   case ISD::GlobalAddress: {
4445     MachineFunction &MF = DAG.getMachineFunction();
4446     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4447     return LowerGlobalAddress(MFI, Op, DAG);
4448   }
4449   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4450   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4451   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4452   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4453   case ISD::INSERT_SUBVECTOR:
4454     return lowerINSERT_SUBVECTOR(Op, DAG);
4455   case ISD::INSERT_VECTOR_ELT:
4456     return lowerINSERT_VECTOR_ELT(Op, DAG);
4457   case ISD::EXTRACT_VECTOR_ELT:
4458     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4459   case ISD::VECTOR_SHUFFLE:
4460     return lowerVECTOR_SHUFFLE(Op, DAG);
4461   case ISD::BUILD_VECTOR:
4462     return lowerBUILD_VECTOR(Op, DAG);
4463   case ISD::FP_ROUND:
4464     return lowerFP_ROUND(Op, DAG);
4465   case ISD::TRAP:
4466     return lowerTRAP(Op, DAG);
4467   case ISD::DEBUGTRAP:
4468     return lowerDEBUGTRAP(Op, DAG);
4469   case ISD::FABS:
4470   case ISD::FNEG:
4471   case ISD::FCANONICALIZE:
4472   case ISD::BSWAP:
4473     return splitUnaryVectorOp(Op, DAG);
4474   case ISD::FMINNUM:
4475   case ISD::FMAXNUM:
4476     return lowerFMINNUM_FMAXNUM(Op, DAG);
4477   case ISD::FMA:
4478     return splitTernaryVectorOp(Op, DAG);
4479   case ISD::SHL:
4480   case ISD::SRA:
4481   case ISD::SRL:
4482   case ISD::ADD:
4483   case ISD::SUB:
4484   case ISD::MUL:
4485   case ISD::SMIN:
4486   case ISD::SMAX:
4487   case ISD::UMIN:
4488   case ISD::UMAX:
4489   case ISD::FADD:
4490   case ISD::FMUL:
4491   case ISD::FMINNUM_IEEE:
4492   case ISD::FMAXNUM_IEEE:
4493   case ISD::UADDSAT:
4494   case ISD::USUBSAT:
4495   case ISD::SADDSAT:
4496   case ISD::SSUBSAT:
4497     return splitBinaryVectorOp(Op, DAG);
4498   case ISD::SMULO:
4499   case ISD::UMULO:
4500     return lowerXMULO(Op, DAG);
4501   case ISD::DYNAMIC_STACKALLOC:
4502     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4503   }
4504   return SDValue();
4505 }
4506 
4507 // Used for D16: Casts the result of an instruction into the right vector,
4508 // packs values if loads return unpacked values.
4509 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4510                                        const SDLoc &DL,
4511                                        SelectionDAG &DAG, bool Unpacked) {
4512   if (!LoadVT.isVector())
4513     return Result;
4514 
4515   // Cast back to the original packed type or to a larger type that is a
4516   // multiple of 32 bit for D16. Widening the return type is a required for
4517   // legalization.
4518   EVT FittingLoadVT = LoadVT;
4519   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4520     FittingLoadVT =
4521         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4522                          LoadVT.getVectorNumElements() + 1);
4523   }
4524 
4525   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4526     // Truncate to v2i16/v4i16.
4527     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4528 
4529     // Workaround legalizer not scalarizing truncate after vector op
4530     // legalization but not creating intermediate vector trunc.
4531     SmallVector<SDValue, 4> Elts;
4532     DAG.ExtractVectorElements(Result, Elts);
4533     for (SDValue &Elt : Elts)
4534       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4535 
4536     // Pad illegal v1i16/v3fi6 to v4i16
4537     if ((LoadVT.getVectorNumElements() % 2) == 1)
4538       Elts.push_back(DAG.getUNDEF(MVT::i16));
4539 
4540     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4541 
4542     // Bitcast to original type (v2f16/v4f16).
4543     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4544   }
4545 
4546   // Cast back to the original packed type.
4547   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4548 }
4549 
4550 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4551                                               MemSDNode *M,
4552                                               SelectionDAG &DAG,
4553                                               ArrayRef<SDValue> Ops,
4554                                               bool IsIntrinsic) const {
4555   SDLoc DL(M);
4556 
4557   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4558   EVT LoadVT = M->getValueType(0);
4559 
4560   EVT EquivLoadVT = LoadVT;
4561   if (LoadVT.isVector()) {
4562     if (Unpacked) {
4563       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4564                                      LoadVT.getVectorNumElements());
4565     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4566       // Widen v3f16 to legal type
4567       EquivLoadVT =
4568           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4569                            LoadVT.getVectorNumElements() + 1);
4570     }
4571   }
4572 
4573   // Change from v4f16/v2f16 to EquivLoadVT.
4574   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4575 
4576   SDValue Load
4577     = DAG.getMemIntrinsicNode(
4578       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4579       VTList, Ops, M->getMemoryVT(),
4580       M->getMemOperand());
4581 
4582   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4583 
4584   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4585 }
4586 
4587 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4588                                              SelectionDAG &DAG,
4589                                              ArrayRef<SDValue> Ops) const {
4590   SDLoc DL(M);
4591   EVT LoadVT = M->getValueType(0);
4592   EVT EltType = LoadVT.getScalarType();
4593   EVT IntVT = LoadVT.changeTypeToInteger();
4594 
4595   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4596 
4597   unsigned Opc =
4598       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4599 
4600   if (IsD16) {
4601     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4602   }
4603 
4604   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4605   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4606     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4607 
4608   if (isTypeLegal(LoadVT)) {
4609     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4610                                M->getMemOperand(), DAG);
4611   }
4612 
4613   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4614   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4615   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4616                                         M->getMemOperand(), DAG);
4617   return DAG.getMergeValues(
4618       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4619       DL);
4620 }
4621 
4622 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4623                                   SDNode *N, SelectionDAG &DAG) {
4624   EVT VT = N->getValueType(0);
4625   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4626   unsigned CondCode = CD->getZExtValue();
4627   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4628     return DAG.getUNDEF(VT);
4629 
4630   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4631 
4632   SDValue LHS = N->getOperand(1);
4633   SDValue RHS = N->getOperand(2);
4634 
4635   SDLoc DL(N);
4636 
4637   EVT CmpVT = LHS.getValueType();
4638   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4639     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4640       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4641     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4642     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4643   }
4644 
4645   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4646 
4647   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4648   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4649 
4650   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4651                               DAG.getCondCode(CCOpcode));
4652   if (VT.bitsEq(CCVT))
4653     return SetCC;
4654   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4655 }
4656 
4657 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4658                                   SDNode *N, SelectionDAG &DAG) {
4659   EVT VT = N->getValueType(0);
4660   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4661 
4662   unsigned CondCode = CD->getZExtValue();
4663   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4664     return DAG.getUNDEF(VT);
4665 
4666   SDValue Src0 = N->getOperand(1);
4667   SDValue Src1 = N->getOperand(2);
4668   EVT CmpVT = Src0.getValueType();
4669   SDLoc SL(N);
4670 
4671   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4672     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4673     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4674   }
4675 
4676   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4677   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4678   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4679   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4680   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4681                               Src1, DAG.getCondCode(CCOpcode));
4682   if (VT.bitsEq(CCVT))
4683     return SetCC;
4684   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4685 }
4686 
4687 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4688                                     SelectionDAG &DAG) {
4689   EVT VT = N->getValueType(0);
4690   SDValue Src = N->getOperand(1);
4691   SDLoc SL(N);
4692 
4693   if (Src.getOpcode() == ISD::SETCC) {
4694     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4695     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4696                        Src.getOperand(1), Src.getOperand(2));
4697   }
4698   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4699     // (ballot 0) -> 0
4700     if (Arg->isNullValue())
4701       return DAG.getConstant(0, SL, VT);
4702 
4703     // (ballot 1) -> EXEC/EXEC_LO
4704     if (Arg->isOne()) {
4705       Register Exec;
4706       if (VT.getScalarSizeInBits() == 32)
4707         Exec = AMDGPU::EXEC_LO;
4708       else if (VT.getScalarSizeInBits() == 64)
4709         Exec = AMDGPU::EXEC;
4710       else
4711         return SDValue();
4712 
4713       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4714     }
4715   }
4716 
4717   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4718   // ISD::SETNE)
4719   return DAG.getNode(
4720       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4721       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4722 }
4723 
4724 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4725                                           SmallVectorImpl<SDValue> &Results,
4726                                           SelectionDAG &DAG) const {
4727   switch (N->getOpcode()) {
4728   case ISD::INSERT_VECTOR_ELT: {
4729     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4730       Results.push_back(Res);
4731     return;
4732   }
4733   case ISD::EXTRACT_VECTOR_ELT: {
4734     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4735       Results.push_back(Res);
4736     return;
4737   }
4738   case ISD::INTRINSIC_WO_CHAIN: {
4739     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4740     switch (IID) {
4741     case Intrinsic::amdgcn_cvt_pkrtz: {
4742       SDValue Src0 = N->getOperand(1);
4743       SDValue Src1 = N->getOperand(2);
4744       SDLoc SL(N);
4745       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4746                                 Src0, Src1);
4747       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4748       return;
4749     }
4750     case Intrinsic::amdgcn_cvt_pknorm_i16:
4751     case Intrinsic::amdgcn_cvt_pknorm_u16:
4752     case Intrinsic::amdgcn_cvt_pk_i16:
4753     case Intrinsic::amdgcn_cvt_pk_u16: {
4754       SDValue Src0 = N->getOperand(1);
4755       SDValue Src1 = N->getOperand(2);
4756       SDLoc SL(N);
4757       unsigned Opcode;
4758 
4759       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4760         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4761       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4762         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4763       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4764         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4765       else
4766         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4767 
4768       EVT VT = N->getValueType(0);
4769       if (isTypeLegal(VT))
4770         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4771       else {
4772         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4773         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4774       }
4775       return;
4776     }
4777     }
4778     break;
4779   }
4780   case ISD::INTRINSIC_W_CHAIN: {
4781     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4782       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4783         // FIXME: Hacky
4784         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4785           Results.push_back(Res.getOperand(I));
4786         }
4787       } else {
4788         Results.push_back(Res);
4789         Results.push_back(Res.getValue(1));
4790       }
4791       return;
4792     }
4793 
4794     break;
4795   }
4796   case ISD::SELECT: {
4797     SDLoc SL(N);
4798     EVT VT = N->getValueType(0);
4799     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4800     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4801     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4802 
4803     EVT SelectVT = NewVT;
4804     if (NewVT.bitsLT(MVT::i32)) {
4805       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4806       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4807       SelectVT = MVT::i32;
4808     }
4809 
4810     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4811                                     N->getOperand(0), LHS, RHS);
4812 
4813     if (NewVT != SelectVT)
4814       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4815     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4816     return;
4817   }
4818   case ISD::FNEG: {
4819     if (N->getValueType(0) != MVT::v2f16)
4820       break;
4821 
4822     SDLoc SL(N);
4823     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4824 
4825     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4826                              BC,
4827                              DAG.getConstant(0x80008000, SL, MVT::i32));
4828     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4829     return;
4830   }
4831   case ISD::FABS: {
4832     if (N->getValueType(0) != MVT::v2f16)
4833       break;
4834 
4835     SDLoc SL(N);
4836     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4837 
4838     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4839                              BC,
4840                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4841     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4842     return;
4843   }
4844   default:
4845     break;
4846   }
4847 }
4848 
4849 /// Helper function for LowerBRCOND
4850 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4851 
4852   SDNode *Parent = Value.getNode();
4853   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4854        I != E; ++I) {
4855 
4856     if (I.getUse().get() != Value)
4857       continue;
4858 
4859     if (I->getOpcode() == Opcode)
4860       return *I;
4861   }
4862   return nullptr;
4863 }
4864 
4865 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4866   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4867     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4868     case Intrinsic::amdgcn_if:
4869       return AMDGPUISD::IF;
4870     case Intrinsic::amdgcn_else:
4871       return AMDGPUISD::ELSE;
4872     case Intrinsic::amdgcn_loop:
4873       return AMDGPUISD::LOOP;
4874     case Intrinsic::amdgcn_end_cf:
4875       llvm_unreachable("should not occur");
4876     default:
4877       return 0;
4878     }
4879   }
4880 
4881   // break, if_break, else_break are all only used as inputs to loop, not
4882   // directly as branch conditions.
4883   return 0;
4884 }
4885 
4886 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4887   const Triple &TT = getTargetMachine().getTargetTriple();
4888   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4889           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4890          AMDGPU::shouldEmitConstantsToTextSection(TT);
4891 }
4892 
4893 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4894   // FIXME: Either avoid relying on address space here or change the default
4895   // address space for functions to avoid the explicit check.
4896   return (GV->getValueType()->isFunctionTy() ||
4897           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4898          !shouldEmitFixup(GV) &&
4899          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4900 }
4901 
4902 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4903   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4904 }
4905 
4906 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4907   if (!GV->hasExternalLinkage())
4908     return true;
4909 
4910   const auto OS = getTargetMachine().getTargetTriple().getOS();
4911   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4912 }
4913 
4914 /// This transforms the control flow intrinsics to get the branch destination as
4915 /// last parameter, also switches branch target with BR if the need arise
4916 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4917                                       SelectionDAG &DAG) const {
4918   SDLoc DL(BRCOND);
4919 
4920   SDNode *Intr = BRCOND.getOperand(1).getNode();
4921   SDValue Target = BRCOND.getOperand(2);
4922   SDNode *BR = nullptr;
4923   SDNode *SetCC = nullptr;
4924 
4925   if (Intr->getOpcode() == ISD::SETCC) {
4926     // As long as we negate the condition everything is fine
4927     SetCC = Intr;
4928     Intr = SetCC->getOperand(0).getNode();
4929 
4930   } else {
4931     // Get the target from BR if we don't negate the condition
4932     BR = findUser(BRCOND, ISD::BR);
4933     assert(BR && "brcond missing unconditional branch user");
4934     Target = BR->getOperand(1);
4935   }
4936 
4937   unsigned CFNode = isCFIntrinsic(Intr);
4938   if (CFNode == 0) {
4939     // This is a uniform branch so we don't need to legalize.
4940     return BRCOND;
4941   }
4942 
4943   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4944                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4945 
4946   assert(!SetCC ||
4947         (SetCC->getConstantOperandVal(1) == 1 &&
4948          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4949                                                              ISD::SETNE));
4950 
4951   // operands of the new intrinsic call
4952   SmallVector<SDValue, 4> Ops;
4953   if (HaveChain)
4954     Ops.push_back(BRCOND.getOperand(0));
4955 
4956   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4957   Ops.push_back(Target);
4958 
4959   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4960 
4961   // build the new intrinsic call
4962   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4963 
4964   if (!HaveChain) {
4965     SDValue Ops[] =  {
4966       SDValue(Result, 0),
4967       BRCOND.getOperand(0)
4968     };
4969 
4970     Result = DAG.getMergeValues(Ops, DL).getNode();
4971   }
4972 
4973   if (BR) {
4974     // Give the branch instruction our target
4975     SDValue Ops[] = {
4976       BR->getOperand(0),
4977       BRCOND.getOperand(2)
4978     };
4979     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4980     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4981   }
4982 
4983   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4984 
4985   // Copy the intrinsic results to registers
4986   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4987     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4988     if (!CopyToReg)
4989       continue;
4990 
4991     Chain = DAG.getCopyToReg(
4992       Chain, DL,
4993       CopyToReg->getOperand(1),
4994       SDValue(Result, i - 1),
4995       SDValue());
4996 
4997     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4998   }
4999 
5000   // Remove the old intrinsic from the chain
5001   DAG.ReplaceAllUsesOfValueWith(
5002     SDValue(Intr, Intr->getNumValues() - 1),
5003     Intr->getOperand(0));
5004 
5005   return Chain;
5006 }
5007 
5008 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5009                                           SelectionDAG &DAG) const {
5010   MVT VT = Op.getSimpleValueType();
5011   SDLoc DL(Op);
5012   // Checking the depth
5013   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5014     return DAG.getConstant(0, DL, VT);
5015 
5016   MachineFunction &MF = DAG.getMachineFunction();
5017   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5018   // Check for kernel and shader functions
5019   if (Info->isEntryFunction())
5020     return DAG.getConstant(0, DL, VT);
5021 
5022   MachineFrameInfo &MFI = MF.getFrameInfo();
5023   // There is a call to @llvm.returnaddress in this function
5024   MFI.setReturnAddressIsTaken(true);
5025 
5026   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5027   // Get the return address reg and mark it as an implicit live-in
5028   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5029 
5030   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5031 }
5032 
5033 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5034                                             SDValue Op,
5035                                             const SDLoc &DL,
5036                                             EVT VT) const {
5037   return Op.getValueType().bitsLE(VT) ?
5038       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5039     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5040                 DAG.getTargetConstant(0, DL, MVT::i32));
5041 }
5042 
5043 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5044   assert(Op.getValueType() == MVT::f16 &&
5045          "Do not know how to custom lower FP_ROUND for non-f16 type");
5046 
5047   SDValue Src = Op.getOperand(0);
5048   EVT SrcVT = Src.getValueType();
5049   if (SrcVT != MVT::f64)
5050     return Op;
5051 
5052   SDLoc DL(Op);
5053 
5054   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5055   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5056   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5057 }
5058 
5059 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5060                                                SelectionDAG &DAG) const {
5061   EVT VT = Op.getValueType();
5062   const MachineFunction &MF = DAG.getMachineFunction();
5063   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5064   bool IsIEEEMode = Info->getMode().IEEE;
5065 
5066   // FIXME: Assert during selection that this is only selected for
5067   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5068   // mode functions, but this happens to be OK since it's only done in cases
5069   // where there is known no sNaN.
5070   if (IsIEEEMode)
5071     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5072 
5073   if (VT == MVT::v4f16)
5074     return splitBinaryVectorOp(Op, DAG);
5075   return Op;
5076 }
5077 
5078 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5079   EVT VT = Op.getValueType();
5080   SDLoc SL(Op);
5081   SDValue LHS = Op.getOperand(0);
5082   SDValue RHS = Op.getOperand(1);
5083   bool isSigned = Op.getOpcode() == ISD::SMULO;
5084 
5085   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5086     const APInt &C = RHSC->getAPIntValue();
5087     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5088     if (C.isPowerOf2()) {
5089       // smulo(x, signed_min) is same as umulo(x, signed_min).
5090       bool UseArithShift = isSigned && !C.isMinSignedValue();
5091       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5092       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5093       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5094           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5095                       SL, VT, Result, ShiftAmt),
5096           LHS, ISD::SETNE);
5097       return DAG.getMergeValues({ Result, Overflow }, SL);
5098     }
5099   }
5100 
5101   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5102   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5103                             SL, VT, LHS, RHS);
5104 
5105   SDValue Sign = isSigned
5106     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5107                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5108     : DAG.getConstant(0, SL, VT);
5109   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5110 
5111   return DAG.getMergeValues({ Result, Overflow }, SL);
5112 }
5113 
5114 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5115   SDLoc SL(Op);
5116   SDValue Chain = Op.getOperand(0);
5117 
5118   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5119       !Subtarget->isTrapHandlerEnabled())
5120     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5121 
5122   MachineFunction &MF = DAG.getMachineFunction();
5123   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5124   Register UserSGPR = Info->getQueuePtrUserSGPR();
5125   assert(UserSGPR != AMDGPU::NoRegister);
5126   SDValue QueuePtr = CreateLiveInRegister(
5127     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5128   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5129   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5130                                    QueuePtr, SDValue());
5131   SDValue Ops[] = {
5132     ToReg,
5133     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5134     SGPR01,
5135     ToReg.getValue(1)
5136   };
5137   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5138 }
5139 
5140 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5141   SDLoc SL(Op);
5142   SDValue Chain = Op.getOperand(0);
5143   MachineFunction &MF = DAG.getMachineFunction();
5144 
5145   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5146       !Subtarget->isTrapHandlerEnabled()) {
5147     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5148                                      "debugtrap handler not supported",
5149                                      Op.getDebugLoc(),
5150                                      DS_Warning);
5151     LLVMContext &Ctx = MF.getFunction().getContext();
5152     Ctx.diagnose(NoTrap);
5153     return Chain;
5154   }
5155 
5156   SDValue Ops[] = {
5157     Chain,
5158     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5159   };
5160   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5161 }
5162 
5163 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5164                                              SelectionDAG &DAG) const {
5165   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5166   if (Subtarget->hasApertureRegs()) {
5167     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5168         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5169         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5170     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5171         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5172         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5173     unsigned Encoding =
5174         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5175         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5176         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5177 
5178     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5179     SDValue ApertureReg = SDValue(
5180         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5181     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5182     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5183   }
5184 
5185   MachineFunction &MF = DAG.getMachineFunction();
5186   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5187   Register UserSGPR = Info->getQueuePtrUserSGPR();
5188   assert(UserSGPR != AMDGPU::NoRegister);
5189 
5190   SDValue QueuePtr = CreateLiveInRegister(
5191     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5192 
5193   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5194   // private_segment_aperture_base_hi.
5195   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5196 
5197   SDValue Ptr =
5198       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5199 
5200   // TODO: Use custom target PseudoSourceValue.
5201   // TODO: We should use the value from the IR intrinsic call, but it might not
5202   // be available and how do we get it?
5203   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5204   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5205                      commonAlignment(Align(64), StructOffset),
5206                      MachineMemOperand::MODereferenceable |
5207                          MachineMemOperand::MOInvariant);
5208 }
5209 
5210 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5211                                              SelectionDAG &DAG) const {
5212   SDLoc SL(Op);
5213   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5214 
5215   SDValue Src = ASC->getOperand(0);
5216   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5217 
5218   const AMDGPUTargetMachine &TM =
5219     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5220 
5221   // flat -> local/private
5222   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5223     unsigned DestAS = ASC->getDestAddressSpace();
5224 
5225     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5226         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5227       unsigned NullVal = TM.getNullPointerValue(DestAS);
5228       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5229       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5230       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5231 
5232       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5233                          NonNull, Ptr, SegmentNullPtr);
5234     }
5235   }
5236 
5237   // local/private -> flat
5238   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5239     unsigned SrcAS = ASC->getSrcAddressSpace();
5240 
5241     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5242         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5243       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5244       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5245 
5246       SDValue NonNull
5247         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5248 
5249       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5250       SDValue CvtPtr
5251         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5252 
5253       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5254                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5255                          FlatNullPtr);
5256     }
5257   }
5258 
5259   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5260       Src.getValueType() == MVT::i64)
5261     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5262 
5263   // global <-> flat are no-ops and never emitted.
5264 
5265   const MachineFunction &MF = DAG.getMachineFunction();
5266   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5267     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5268   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5269 
5270   return DAG.getUNDEF(ASC->getValueType(0));
5271 }
5272 
5273 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5274 // the small vector and inserting them into the big vector. That is better than
5275 // the default expansion of doing it via a stack slot. Even though the use of
5276 // the stack slot would be optimized away afterwards, the stack slot itself
5277 // remains.
5278 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5279                                                 SelectionDAG &DAG) const {
5280   SDValue Vec = Op.getOperand(0);
5281   SDValue Ins = Op.getOperand(1);
5282   SDValue Idx = Op.getOperand(2);
5283   EVT VecVT = Vec.getValueType();
5284   EVT InsVT = Ins.getValueType();
5285   EVT EltVT = VecVT.getVectorElementType();
5286   unsigned InsNumElts = InsVT.getVectorNumElements();
5287   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5288   SDLoc SL(Op);
5289 
5290   for (unsigned I = 0; I != InsNumElts; ++I) {
5291     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5292                               DAG.getConstant(I, SL, MVT::i32));
5293     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5294                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5295   }
5296   return Vec;
5297 }
5298 
5299 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5300                                                  SelectionDAG &DAG) const {
5301   SDValue Vec = Op.getOperand(0);
5302   SDValue InsVal = Op.getOperand(1);
5303   SDValue Idx = Op.getOperand(2);
5304   EVT VecVT = Vec.getValueType();
5305   EVT EltVT = VecVT.getVectorElementType();
5306   unsigned VecSize = VecVT.getSizeInBits();
5307   unsigned EltSize = EltVT.getSizeInBits();
5308 
5309 
5310   assert(VecSize <= 64);
5311 
5312   unsigned NumElts = VecVT.getVectorNumElements();
5313   SDLoc SL(Op);
5314   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5315 
5316   if (NumElts == 4 && EltSize == 16 && KIdx) {
5317     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5318 
5319     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5320                                  DAG.getConstant(0, SL, MVT::i32));
5321     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5322                                  DAG.getConstant(1, SL, MVT::i32));
5323 
5324     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5325     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5326 
5327     unsigned Idx = KIdx->getZExtValue();
5328     bool InsertLo = Idx < 2;
5329     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5330       InsertLo ? LoVec : HiVec,
5331       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5332       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5333 
5334     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5335 
5336     SDValue Concat = InsertLo ?
5337       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5338       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5339 
5340     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5341   }
5342 
5343   if (isa<ConstantSDNode>(Idx))
5344     return SDValue();
5345 
5346   MVT IntVT = MVT::getIntegerVT(VecSize);
5347 
5348   // Avoid stack access for dynamic indexing.
5349   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5350 
5351   // Create a congruent vector with the target value in each element so that
5352   // the required element can be masked and ORed into the target vector.
5353   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5354                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5355 
5356   assert(isPowerOf2_32(EltSize));
5357   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5358 
5359   // Convert vector index to bit-index.
5360   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5361 
5362   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5363   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5364                             DAG.getConstant(0xffff, SL, IntVT),
5365                             ScaledIdx);
5366 
5367   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5368   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5369                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5370 
5371   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5372   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5373 }
5374 
5375 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5376                                                   SelectionDAG &DAG) const {
5377   SDLoc SL(Op);
5378 
5379   EVT ResultVT = Op.getValueType();
5380   SDValue Vec = Op.getOperand(0);
5381   SDValue Idx = Op.getOperand(1);
5382   EVT VecVT = Vec.getValueType();
5383   unsigned VecSize = VecVT.getSizeInBits();
5384   EVT EltVT = VecVT.getVectorElementType();
5385   assert(VecSize <= 64);
5386 
5387   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5388 
5389   // Make sure we do any optimizations that will make it easier to fold
5390   // source modifiers before obscuring it with bit operations.
5391 
5392   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5393   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5394     return Combined;
5395 
5396   unsigned EltSize = EltVT.getSizeInBits();
5397   assert(isPowerOf2_32(EltSize));
5398 
5399   MVT IntVT = MVT::getIntegerVT(VecSize);
5400   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5401 
5402   // Convert vector index to bit-index (* EltSize)
5403   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5404 
5405   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5406   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5407 
5408   if (ResultVT == MVT::f16) {
5409     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5410     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5411   }
5412 
5413   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5414 }
5415 
5416 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5417   assert(Elt % 2 == 0);
5418   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5419 }
5420 
5421 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5422                                               SelectionDAG &DAG) const {
5423   SDLoc SL(Op);
5424   EVT ResultVT = Op.getValueType();
5425   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5426 
5427   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5428   EVT EltVT = PackVT.getVectorElementType();
5429   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5430 
5431   // vector_shuffle <0,1,6,7> lhs, rhs
5432   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5433   //
5434   // vector_shuffle <6,7,2,3> lhs, rhs
5435   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5436   //
5437   // vector_shuffle <6,7,0,1> lhs, rhs
5438   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5439 
5440   // Avoid scalarizing when both halves are reading from consecutive elements.
5441   SmallVector<SDValue, 4> Pieces;
5442   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5443     if (elementPairIsContiguous(SVN->getMask(), I)) {
5444       const int Idx = SVN->getMaskElt(I);
5445       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5446       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5447       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5448                                     PackVT, SVN->getOperand(VecIdx),
5449                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5450       Pieces.push_back(SubVec);
5451     } else {
5452       const int Idx0 = SVN->getMaskElt(I);
5453       const int Idx1 = SVN->getMaskElt(I + 1);
5454       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5455       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5456       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5457       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5458 
5459       SDValue Vec0 = SVN->getOperand(VecIdx0);
5460       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5461                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5462 
5463       SDValue Vec1 = SVN->getOperand(VecIdx1);
5464       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5465                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5466       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5467     }
5468   }
5469 
5470   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5471 }
5472 
5473 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5474                                             SelectionDAG &DAG) const {
5475   SDLoc SL(Op);
5476   EVT VT = Op.getValueType();
5477 
5478   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5479     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5480 
5481     // Turn into pair of packed build_vectors.
5482     // TODO: Special case for constants that can be materialized with s_mov_b64.
5483     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5484                                     { Op.getOperand(0), Op.getOperand(1) });
5485     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5486                                     { Op.getOperand(2), Op.getOperand(3) });
5487 
5488     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5489     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5490 
5491     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5492     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5493   }
5494 
5495   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5496   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5497 
5498   SDValue Lo = Op.getOperand(0);
5499   SDValue Hi = Op.getOperand(1);
5500 
5501   // Avoid adding defined bits with the zero_extend.
5502   if (Hi.isUndef()) {
5503     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5504     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5505     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5506   }
5507 
5508   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5509   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5510 
5511   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5512                               DAG.getConstant(16, SL, MVT::i32));
5513   if (Lo.isUndef())
5514     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5515 
5516   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5517   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5518 
5519   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5520   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5521 }
5522 
5523 bool
5524 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5525   // We can fold offsets for anything that doesn't require a GOT relocation.
5526   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5527           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5528           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5529          !shouldEmitGOTReloc(GA->getGlobal());
5530 }
5531 
5532 static SDValue
5533 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5534                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5535                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5536   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5537   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5538   // lowered to the following code sequence:
5539   //
5540   // For constant address space:
5541   //   s_getpc_b64 s[0:1]
5542   //   s_add_u32 s0, s0, $symbol
5543   //   s_addc_u32 s1, s1, 0
5544   //
5545   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5546   //   a fixup or relocation is emitted to replace $symbol with a literal
5547   //   constant, which is a pc-relative offset from the encoding of the $symbol
5548   //   operand to the global variable.
5549   //
5550   // For global address space:
5551   //   s_getpc_b64 s[0:1]
5552   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5553   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5554   //
5555   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5556   //   fixups or relocations are emitted to replace $symbol@*@lo and
5557   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5558   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5559   //   operand to the global variable.
5560   //
5561   // What we want here is an offset from the value returned by s_getpc
5562   // (which is the address of the s_add_u32 instruction) to the global
5563   // variable, but since the encoding of $symbol starts 4 bytes after the start
5564   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5565   // small. This requires us to add 4 to the global variable offset in order to
5566   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5567   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5568   // instruction.
5569   SDValue PtrLo =
5570       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5571   SDValue PtrHi;
5572   if (GAFlags == SIInstrInfo::MO_NONE) {
5573     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5574   } else {
5575     PtrHi =
5576         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5577   }
5578   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5579 }
5580 
5581 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5582                                              SDValue Op,
5583                                              SelectionDAG &DAG) const {
5584   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5585   SDLoc DL(GSD);
5586   EVT PtrVT = Op.getValueType();
5587 
5588   const GlobalValue *GV = GSD->getGlobal();
5589   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5590        shouldUseLDSConstAddress(GV)) ||
5591       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5592       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5593     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5594         GV->hasExternalLinkage()) {
5595       Type *Ty = GV->getValueType();
5596       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5597       // zero-sized type in other languages to declare the dynamic shared
5598       // memory which size is not known at the compile time. They will be
5599       // allocated by the runtime and placed directly after the static
5600       // allocated ones. They all share the same offset.
5601       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5602         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5603         // Adjust alignment for that dynamic shared memory array.
5604         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5605         return SDValue(
5606             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5607       }
5608     }
5609     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5610   }
5611 
5612   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5613     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5614                                             SIInstrInfo::MO_ABS32_LO);
5615     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5616   }
5617 
5618   if (shouldEmitFixup(GV))
5619     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5620   else if (shouldEmitPCReloc(GV))
5621     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5622                                    SIInstrInfo::MO_REL32);
5623 
5624   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5625                                             SIInstrInfo::MO_GOTPCREL32);
5626 
5627   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5628   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5629   const DataLayout &DataLayout = DAG.getDataLayout();
5630   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5631   MachinePointerInfo PtrInfo
5632     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5633 
5634   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5635                      MachineMemOperand::MODereferenceable |
5636                          MachineMemOperand::MOInvariant);
5637 }
5638 
5639 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5640                                    const SDLoc &DL, SDValue V) const {
5641   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5642   // the destination register.
5643   //
5644   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5645   // so we will end up with redundant moves to m0.
5646   //
5647   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5648 
5649   // A Null SDValue creates a glue result.
5650   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5651                                   V, Chain);
5652   return SDValue(M0, 0);
5653 }
5654 
5655 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5656                                                  SDValue Op,
5657                                                  MVT VT,
5658                                                  unsigned Offset) const {
5659   SDLoc SL(Op);
5660   SDValue Param = lowerKernargMemParameter(
5661       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5662   // The local size values will have the hi 16-bits as zero.
5663   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5664                      DAG.getValueType(VT));
5665 }
5666 
5667 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5668                                         EVT VT) {
5669   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5670                                       "non-hsa intrinsic with hsa target",
5671                                       DL.getDebugLoc());
5672   DAG.getContext()->diagnose(BadIntrin);
5673   return DAG.getUNDEF(VT);
5674 }
5675 
5676 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5677                                          EVT VT) {
5678   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5679                                       "intrinsic not supported on subtarget",
5680                                       DL.getDebugLoc());
5681   DAG.getContext()->diagnose(BadIntrin);
5682   return DAG.getUNDEF(VT);
5683 }
5684 
5685 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5686                                     ArrayRef<SDValue> Elts) {
5687   assert(!Elts.empty());
5688   MVT Type;
5689   unsigned NumElts;
5690 
5691   if (Elts.size() == 1) {
5692     Type = MVT::f32;
5693     NumElts = 1;
5694   } else if (Elts.size() == 2) {
5695     Type = MVT::v2f32;
5696     NumElts = 2;
5697   } else if (Elts.size() == 3) {
5698     Type = MVT::v3f32;
5699     NumElts = 3;
5700   } else if (Elts.size() <= 4) {
5701     Type = MVT::v4f32;
5702     NumElts = 4;
5703   } else if (Elts.size() <= 8) {
5704     Type = MVT::v8f32;
5705     NumElts = 8;
5706   } else {
5707     assert(Elts.size() <= 16);
5708     Type = MVT::v16f32;
5709     NumElts = 16;
5710   }
5711 
5712   SmallVector<SDValue, 16> VecElts(NumElts);
5713   for (unsigned i = 0; i < Elts.size(); ++i) {
5714     SDValue Elt = Elts[i];
5715     if (Elt.getValueType() != MVT::f32)
5716       Elt = DAG.getBitcast(MVT::f32, Elt);
5717     VecElts[i] = Elt;
5718   }
5719   for (unsigned i = Elts.size(); i < NumElts; ++i)
5720     VecElts[i] = DAG.getUNDEF(MVT::f32);
5721 
5722   if (NumElts == 1)
5723     return VecElts[0];
5724   return DAG.getBuildVector(Type, DL, VecElts);
5725 }
5726 
5727 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5728                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5729   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5730 
5731   uint64_t Value = CachePolicyConst->getZExtValue();
5732   SDLoc DL(CachePolicy);
5733   if (GLC) {
5734     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5735     Value &= ~(uint64_t)0x1;
5736   }
5737   if (SLC) {
5738     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5739     Value &= ~(uint64_t)0x2;
5740   }
5741   if (DLC) {
5742     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5743     Value &= ~(uint64_t)0x4;
5744   }
5745 
5746   return Value == 0;
5747 }
5748 
5749 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5750                               SDValue Src, int ExtraElts) {
5751   EVT SrcVT = Src.getValueType();
5752 
5753   SmallVector<SDValue, 8> Elts;
5754 
5755   if (SrcVT.isVector())
5756     DAG.ExtractVectorElements(Src, Elts);
5757   else
5758     Elts.push_back(Src);
5759 
5760   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5761   while (ExtraElts--)
5762     Elts.push_back(Undef);
5763 
5764   return DAG.getBuildVector(CastVT, DL, Elts);
5765 }
5766 
5767 // Re-construct the required return value for a image load intrinsic.
5768 // This is more complicated due to the optional use TexFailCtrl which means the required
5769 // return type is an aggregate
5770 static SDValue constructRetValue(SelectionDAG &DAG,
5771                                  MachineSDNode *Result,
5772                                  ArrayRef<EVT> ResultTypes,
5773                                  bool IsTexFail, bool Unpacked, bool IsD16,
5774                                  int DMaskPop, int NumVDataDwords,
5775                                  const SDLoc &DL, LLVMContext &Context) {
5776   // Determine the required return type. This is the same regardless of IsTexFail flag
5777   EVT ReqRetVT = ResultTypes[0];
5778   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5779   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5780     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5781 
5782   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5783     DMaskPop : (DMaskPop + 1) / 2;
5784 
5785   MVT DataDwordVT = NumDataDwords == 1 ?
5786     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5787 
5788   MVT MaskPopVT = MaskPopDwords == 1 ?
5789     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5790 
5791   SDValue Data(Result, 0);
5792   SDValue TexFail;
5793 
5794   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5795     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5796     if (MaskPopVT.isVector()) {
5797       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5798                          SDValue(Result, 0), ZeroIdx);
5799     } else {
5800       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5801                          SDValue(Result, 0), ZeroIdx);
5802     }
5803   }
5804 
5805   if (DataDwordVT.isVector())
5806     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5807                           NumDataDwords - MaskPopDwords);
5808 
5809   if (IsD16)
5810     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5811 
5812   EVT LegalReqRetVT = ReqRetVT;
5813   if (!ReqRetVT.isVector()) {
5814     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5815   } else {
5816     // We need to widen the return vector to a legal type
5817     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5818         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5819       LegalReqRetVT =
5820           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5821                            ReqRetVT.getVectorNumElements() + 1);
5822     }
5823   }
5824   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5825 
5826   if (IsTexFail) {
5827     TexFail =
5828         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5829                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5830 
5831     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5832   }
5833 
5834   if (Result->getNumValues() == 1)
5835     return Data;
5836 
5837   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5838 }
5839 
5840 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5841                          SDValue *LWE, bool &IsTexFail) {
5842   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5843 
5844   uint64_t Value = TexFailCtrlConst->getZExtValue();
5845   if (Value) {
5846     IsTexFail = true;
5847   }
5848 
5849   SDLoc DL(TexFailCtrlConst);
5850   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5851   Value &= ~(uint64_t)0x1;
5852   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5853   Value &= ~(uint64_t)0x2;
5854 
5855   return Value == 0;
5856 }
5857 
5858 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5859                                         MVT PackVectorVT,
5860                                         SmallVectorImpl<SDValue> &PackedAddrs,
5861                                         unsigned DimIdx, unsigned EndIdx,
5862                                         unsigned NumGradients) {
5863   SDLoc DL(Op);
5864   for (unsigned I = DimIdx; I < EndIdx; I++) {
5865     SDValue Addr = Op.getOperand(I);
5866 
5867     // Gradients are packed with undef for each coordinate.
5868     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5869     // 1D: undef,dx/dh; undef,dx/dv
5870     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5871     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5872     if (((I + 1) >= EndIdx) ||
5873         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5874                                          I == DimIdx + NumGradients - 1))) {
5875       if (Addr.getValueType() != MVT::i16)
5876         Addr = DAG.getBitcast(MVT::i16, Addr);
5877       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5878     } else {
5879       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5880       I++;
5881     }
5882     Addr = DAG.getBitcast(MVT::f32, Addr);
5883     PackedAddrs.push_back(Addr);
5884   }
5885 }
5886 
5887 SDValue SITargetLowering::lowerImage(SDValue Op,
5888                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5889                                      SelectionDAG &DAG, bool WithChain) const {
5890   SDLoc DL(Op);
5891   MachineFunction &MF = DAG.getMachineFunction();
5892   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5893   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5894       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5895   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5896   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5897       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5898   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5899       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5900   unsigned IntrOpcode = Intr->BaseOpcode;
5901   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5902 
5903   SmallVector<EVT, 3> ResultTypes(Op->values());
5904   SmallVector<EVT, 3> OrigResultTypes(Op->values());
5905   bool IsD16 = false;
5906   bool IsG16 = false;
5907   bool IsA16 = false;
5908   SDValue VData;
5909   int NumVDataDwords;
5910   bool AdjustRetType = false;
5911 
5912   // Offset of intrinsic arguments
5913   const unsigned ArgOffset = WithChain ? 2 : 1;
5914 
5915   unsigned DMask;
5916   unsigned DMaskLanes = 0;
5917 
5918   if (BaseOpcode->Atomic) {
5919     VData = Op.getOperand(2);
5920 
5921     bool Is64Bit = VData.getValueType() == MVT::i64;
5922     if (BaseOpcode->AtomicX2) {
5923       SDValue VData2 = Op.getOperand(3);
5924       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5925                                  {VData, VData2});
5926       if (Is64Bit)
5927         VData = DAG.getBitcast(MVT::v4i32, VData);
5928 
5929       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5930       DMask = Is64Bit ? 0xf : 0x3;
5931       NumVDataDwords = Is64Bit ? 4 : 2;
5932     } else {
5933       DMask = Is64Bit ? 0x3 : 0x1;
5934       NumVDataDwords = Is64Bit ? 2 : 1;
5935     }
5936   } else {
5937     auto *DMaskConst =
5938         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
5939     DMask = DMaskConst->getZExtValue();
5940     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5941 
5942     if (BaseOpcode->Store) {
5943       VData = Op.getOperand(2);
5944 
5945       MVT StoreVT = VData.getSimpleValueType();
5946       if (StoreVT.getScalarType() == MVT::f16) {
5947         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5948           return Op; // D16 is unsupported for this instruction
5949 
5950         IsD16 = true;
5951         VData = handleD16VData(VData, DAG, true);
5952       }
5953 
5954       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5955     } else {
5956       // Work out the num dwords based on the dmask popcount and underlying type
5957       // and whether packing is supported.
5958       MVT LoadVT = ResultTypes[0].getSimpleVT();
5959       if (LoadVT.getScalarType() == MVT::f16) {
5960         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5961           return Op; // D16 is unsupported for this instruction
5962 
5963         IsD16 = true;
5964       }
5965 
5966       // Confirm that the return type is large enough for the dmask specified
5967       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5968           (!LoadVT.isVector() && DMaskLanes > 1))
5969           return Op;
5970 
5971       // The sq block of gfx8 and gfx9 do not estimate register use correctly
5972       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
5973       // instructions.
5974       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
5975           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
5976         NumVDataDwords = (DMaskLanes + 1) / 2;
5977       else
5978         NumVDataDwords = DMaskLanes;
5979 
5980       AdjustRetType = true;
5981     }
5982   }
5983 
5984   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
5985   SmallVector<SDValue, 4> VAddrs;
5986 
5987   // Optimize _L to _LZ when _L is zero
5988   if (LZMappingInfo) {
5989     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
5990             Op.getOperand(ArgOffset + Intr->LodIndex))) {
5991       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5992         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5993         VAddrEnd--;                      // remove 'lod'
5994       }
5995     }
5996   }
5997 
5998   // Optimize _mip away, when 'lod' is zero
5999   if (MIPMappingInfo) {
6000     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6001             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6002       if (ConstantLod->isNullValue()) {
6003         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6004         VAddrEnd--;                           // remove 'mip'
6005       }
6006     }
6007   }
6008 
6009   // Push back extra arguments.
6010   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6011     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6012 
6013   // Check for 16 bit addresses or derivatives and pack if true.
6014   MVT VAddrVT =
6015       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6016   MVT VAddrScalarVT = VAddrVT.getScalarType();
6017   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6018   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6019 
6020   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6021   VAddrScalarVT = VAddrVT.getScalarType();
6022   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6023   if (IsA16 || IsG16) {
6024     if (IsA16) {
6025       if (!ST->hasA16()) {
6026         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6027                              "support 16 bit addresses\n");
6028         return Op;
6029       }
6030       if (!IsG16) {
6031         LLVM_DEBUG(
6032             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6033                       "need 16 bit derivatives but got 32 bit derivatives\n");
6034         return Op;
6035       }
6036     } else if (!ST->hasG16()) {
6037       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6038                            "support 16 bit derivatives\n");
6039       return Op;
6040     }
6041 
6042     if (BaseOpcode->Gradients && !IsA16) {
6043       if (!ST->hasG16()) {
6044         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6045                              "support 16 bit derivatives\n");
6046         return Op;
6047       }
6048       // Activate g16
6049       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6050           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6051       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6052     }
6053 
6054     // Don't compress addresses for G16
6055     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6056     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6057                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6058                                 Intr->NumGradients);
6059 
6060     if (!IsA16) {
6061       // Add uncompressed address
6062       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6063         VAddrs.push_back(Op.getOperand(I));
6064     }
6065   } else {
6066     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6067       VAddrs.push_back(Op.getOperand(I));
6068   }
6069 
6070   // If the register allocator cannot place the address registers contiguously
6071   // without introducing moves, then using the non-sequential address encoding
6072   // is always preferable, since it saves VALU instructions and is usually a
6073   // wash in terms of code size or even better.
6074   //
6075   // However, we currently have no way of hinting to the register allocator that
6076   // MIMG addresses should be placed contiguously when it is possible to do so,
6077   // so force non-NSA for the common 2-address case as a heuristic.
6078   //
6079   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6080   // allocation when possible.
6081   bool UseNSA =
6082       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6083   SDValue VAddr;
6084   if (!UseNSA)
6085     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6086 
6087   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6088   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6089   SDValue Unorm;
6090   if (!BaseOpcode->Sampler) {
6091     Unorm = True;
6092   } else {
6093     auto UnormConst =
6094         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6095 
6096     Unorm = UnormConst->getZExtValue() ? True : False;
6097   }
6098 
6099   SDValue TFE;
6100   SDValue LWE;
6101   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6102   bool IsTexFail = false;
6103   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6104     return Op;
6105 
6106   if (IsTexFail) {
6107     if (!DMaskLanes) {
6108       // Expecting to get an error flag since TFC is on - and dmask is 0
6109       // Force dmask to be at least 1 otherwise the instruction will fail
6110       DMask = 0x1;
6111       DMaskLanes = 1;
6112       NumVDataDwords = 1;
6113     }
6114     NumVDataDwords += 1;
6115     AdjustRetType = true;
6116   }
6117 
6118   // Has something earlier tagged that the return type needs adjusting
6119   // This happens if the instruction is a load or has set TexFailCtrl flags
6120   if (AdjustRetType) {
6121     // NumVDataDwords reflects the true number of dwords required in the return type
6122     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6123       // This is a no-op load. This can be eliminated
6124       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6125       if (isa<MemSDNode>(Op))
6126         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6127       return Undef;
6128     }
6129 
6130     EVT NewVT = NumVDataDwords > 1 ?
6131                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6132                 : MVT::i32;
6133 
6134     ResultTypes[0] = NewVT;
6135     if (ResultTypes.size() == 3) {
6136       // Original result was aggregate type used for TexFailCtrl results
6137       // The actual instruction returns as a vector type which has now been
6138       // created. Remove the aggregate result.
6139       ResultTypes.erase(&ResultTypes[1]);
6140     }
6141   }
6142 
6143   SDValue GLC;
6144   SDValue SLC;
6145   SDValue DLC;
6146   if (BaseOpcode->Atomic) {
6147     GLC = True; // TODO no-return optimization
6148     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6149                           DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr))
6150       return Op;
6151   } else {
6152     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6153                           DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr))
6154       return Op;
6155   }
6156 
6157   SmallVector<SDValue, 26> Ops;
6158   if (BaseOpcode->Store || BaseOpcode->Atomic)
6159     Ops.push_back(VData); // vdata
6160   if (UseNSA)
6161     append_range(Ops, VAddrs);
6162   else
6163     Ops.push_back(VAddr);
6164   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6165   if (BaseOpcode->Sampler)
6166     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6167   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6168   if (IsGFX10Plus)
6169     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6170   Ops.push_back(Unorm);
6171   if (IsGFX10Plus)
6172     Ops.push_back(DLC);
6173   Ops.push_back(GLC);
6174   Ops.push_back(SLC);
6175   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6176                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6177   if (IsGFX10Plus)
6178     Ops.push_back(IsA16 ? True : False);
6179   Ops.push_back(TFE);
6180   Ops.push_back(LWE);
6181   if (!IsGFX10Plus)
6182     Ops.push_back(DimInfo->DA ? True : False);
6183   if (BaseOpcode->HasD16)
6184     Ops.push_back(IsD16 ? True : False);
6185   if (isa<MemSDNode>(Op))
6186     Ops.push_back(Op.getOperand(0)); // chain
6187 
6188   int NumVAddrDwords =
6189       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6190   int Opcode = -1;
6191 
6192   if (IsGFX10Plus) {
6193     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6194                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6195                                           : AMDGPU::MIMGEncGfx10Default,
6196                                    NumVDataDwords, NumVAddrDwords);
6197   } else {
6198     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6199       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6200                                      NumVDataDwords, NumVAddrDwords);
6201     if (Opcode == -1)
6202       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6203                                      NumVDataDwords, NumVAddrDwords);
6204   }
6205   assert(Opcode != -1);
6206 
6207   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6208   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6209     MachineMemOperand *MemRef = MemOp->getMemOperand();
6210     DAG.setNodeMemRefs(NewNode, {MemRef});
6211   }
6212 
6213   if (BaseOpcode->AtomicX2) {
6214     SmallVector<SDValue, 1> Elt;
6215     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6216     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6217   } else if (!BaseOpcode->Store) {
6218     return constructRetValue(DAG, NewNode,
6219                              OrigResultTypes, IsTexFail,
6220                              Subtarget->hasUnpackedD16VMem(), IsD16,
6221                              DMaskLanes, NumVDataDwords, DL,
6222                              *DAG.getContext());
6223   }
6224 
6225   return SDValue(NewNode, 0);
6226 }
6227 
6228 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6229                                        SDValue Offset, SDValue CachePolicy,
6230                                        SelectionDAG &DAG) const {
6231   MachineFunction &MF = DAG.getMachineFunction();
6232 
6233   const DataLayout &DataLayout = DAG.getDataLayout();
6234   Align Alignment =
6235       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6236 
6237   MachineMemOperand *MMO = MF.getMachineMemOperand(
6238       MachinePointerInfo(),
6239       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6240           MachineMemOperand::MOInvariant,
6241       VT.getStoreSize(), Alignment);
6242 
6243   if (!Offset->isDivergent()) {
6244     SDValue Ops[] = {
6245         Rsrc,
6246         Offset, // Offset
6247         CachePolicy
6248     };
6249 
6250     // Widen vec3 load to vec4.
6251     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6252       EVT WidenedVT =
6253           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6254       auto WidenedOp = DAG.getMemIntrinsicNode(
6255           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6256           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6257       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6258                                    DAG.getVectorIdxConstant(0, DL));
6259       return Subvector;
6260     }
6261 
6262     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6263                                    DAG.getVTList(VT), Ops, VT, MMO);
6264   }
6265 
6266   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6267   // assume that the buffer is unswizzled.
6268   SmallVector<SDValue, 4> Loads;
6269   unsigned NumLoads = 1;
6270   MVT LoadVT = VT.getSimpleVT();
6271   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6272   assert((LoadVT.getScalarType() == MVT::i32 ||
6273           LoadVT.getScalarType() == MVT::f32));
6274 
6275   if (NumElts == 8 || NumElts == 16) {
6276     NumLoads = NumElts / 4;
6277     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6278   }
6279 
6280   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6281   SDValue Ops[] = {
6282       DAG.getEntryNode(),                               // Chain
6283       Rsrc,                                             // rsrc
6284       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6285       {},                                               // voffset
6286       {},                                               // soffset
6287       {},                                               // offset
6288       CachePolicy,                                      // cachepolicy
6289       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6290   };
6291 
6292   // Use the alignment to ensure that the required offsets will fit into the
6293   // immediate offsets.
6294   setBufferOffsets(Offset, DAG, &Ops[3],
6295                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6296 
6297   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6298   for (unsigned i = 0; i < NumLoads; ++i) {
6299     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6300     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6301                                         LoadVT, MMO, DAG));
6302   }
6303 
6304   if (NumElts == 8 || NumElts == 16)
6305     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6306 
6307   return Loads[0];
6308 }
6309 
6310 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6311                                                   SelectionDAG &DAG) const {
6312   MachineFunction &MF = DAG.getMachineFunction();
6313   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6314 
6315   EVT VT = Op.getValueType();
6316   SDLoc DL(Op);
6317   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6318 
6319   // TODO: Should this propagate fast-math-flags?
6320 
6321   switch (IntrinsicID) {
6322   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6323     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6324       return emitNonHSAIntrinsicError(DAG, DL, VT);
6325     return getPreloadedValue(DAG, *MFI, VT,
6326                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6327   }
6328   case Intrinsic::amdgcn_dispatch_ptr:
6329   case Intrinsic::amdgcn_queue_ptr: {
6330     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6331       DiagnosticInfoUnsupported BadIntrin(
6332           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6333           DL.getDebugLoc());
6334       DAG.getContext()->diagnose(BadIntrin);
6335       return DAG.getUNDEF(VT);
6336     }
6337 
6338     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6339       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6340     return getPreloadedValue(DAG, *MFI, VT, RegID);
6341   }
6342   case Intrinsic::amdgcn_implicitarg_ptr: {
6343     if (MFI->isEntryFunction())
6344       return getImplicitArgPtr(DAG, DL);
6345     return getPreloadedValue(DAG, *MFI, VT,
6346                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6347   }
6348   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6349     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6350       // This only makes sense to call in a kernel, so just lower to null.
6351       return DAG.getConstant(0, DL, VT);
6352     }
6353 
6354     return getPreloadedValue(DAG, *MFI, VT,
6355                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6356   }
6357   case Intrinsic::amdgcn_dispatch_id: {
6358     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6359   }
6360   case Intrinsic::amdgcn_rcp:
6361     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6362   case Intrinsic::amdgcn_rsq:
6363     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6364   case Intrinsic::amdgcn_rsq_legacy:
6365     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6366       return emitRemovedIntrinsicError(DAG, DL, VT);
6367     return SDValue();
6368   case Intrinsic::amdgcn_rcp_legacy:
6369     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6370       return emitRemovedIntrinsicError(DAG, DL, VT);
6371     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6372   case Intrinsic::amdgcn_rsq_clamp: {
6373     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6374       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6375 
6376     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6377     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6378     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6379 
6380     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6381     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6382                               DAG.getConstantFP(Max, DL, VT));
6383     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6384                        DAG.getConstantFP(Min, DL, VT));
6385   }
6386   case Intrinsic::r600_read_ngroups_x:
6387     if (Subtarget->isAmdHsaOS())
6388       return emitNonHSAIntrinsicError(DAG, DL, VT);
6389 
6390     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6391                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6392                                     false);
6393   case Intrinsic::r600_read_ngroups_y:
6394     if (Subtarget->isAmdHsaOS())
6395       return emitNonHSAIntrinsicError(DAG, DL, VT);
6396 
6397     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6398                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6399                                     false);
6400   case Intrinsic::r600_read_ngroups_z:
6401     if (Subtarget->isAmdHsaOS())
6402       return emitNonHSAIntrinsicError(DAG, DL, VT);
6403 
6404     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6405                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6406                                     false);
6407   case Intrinsic::r600_read_global_size_x:
6408     if (Subtarget->isAmdHsaOS())
6409       return emitNonHSAIntrinsicError(DAG, DL, VT);
6410 
6411     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6412                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6413                                     Align(4), false);
6414   case Intrinsic::r600_read_global_size_y:
6415     if (Subtarget->isAmdHsaOS())
6416       return emitNonHSAIntrinsicError(DAG, DL, VT);
6417 
6418     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6419                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6420                                     Align(4), false);
6421   case Intrinsic::r600_read_global_size_z:
6422     if (Subtarget->isAmdHsaOS())
6423       return emitNonHSAIntrinsicError(DAG, DL, VT);
6424 
6425     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6426                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6427                                     Align(4), false);
6428   case Intrinsic::r600_read_local_size_x:
6429     if (Subtarget->isAmdHsaOS())
6430       return emitNonHSAIntrinsicError(DAG, DL, VT);
6431 
6432     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6433                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6434   case Intrinsic::r600_read_local_size_y:
6435     if (Subtarget->isAmdHsaOS())
6436       return emitNonHSAIntrinsicError(DAG, DL, VT);
6437 
6438     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6439                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6440   case Intrinsic::r600_read_local_size_z:
6441     if (Subtarget->isAmdHsaOS())
6442       return emitNonHSAIntrinsicError(DAG, DL, VT);
6443 
6444     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6445                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6446   case Intrinsic::amdgcn_workgroup_id_x:
6447     return getPreloadedValue(DAG, *MFI, VT,
6448                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6449   case Intrinsic::amdgcn_workgroup_id_y:
6450     return getPreloadedValue(DAG, *MFI, VT,
6451                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6452   case Intrinsic::amdgcn_workgroup_id_z:
6453     return getPreloadedValue(DAG, *MFI, VT,
6454                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6455   case Intrinsic::amdgcn_workitem_id_x:
6456     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6457                           SDLoc(DAG.getEntryNode()),
6458                           MFI->getArgInfo().WorkItemIDX);
6459   case Intrinsic::amdgcn_workitem_id_y:
6460     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6461                           SDLoc(DAG.getEntryNode()),
6462                           MFI->getArgInfo().WorkItemIDY);
6463   case Intrinsic::amdgcn_workitem_id_z:
6464     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6465                           SDLoc(DAG.getEntryNode()),
6466                           MFI->getArgInfo().WorkItemIDZ);
6467   case Intrinsic::amdgcn_wavefrontsize:
6468     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6469                            SDLoc(Op), MVT::i32);
6470   case Intrinsic::amdgcn_s_buffer_load: {
6471     bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6472     SDValue GLC;
6473     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6474     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6475                           IsGFX10Plus ? &DLC : nullptr))
6476       return Op;
6477     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6478                         DAG);
6479   }
6480   case Intrinsic::amdgcn_fdiv_fast:
6481     return lowerFDIV_FAST(Op, DAG);
6482   case Intrinsic::amdgcn_sin:
6483     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6484 
6485   case Intrinsic::amdgcn_cos:
6486     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6487 
6488   case Intrinsic::amdgcn_mul_u24:
6489     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6490   case Intrinsic::amdgcn_mul_i24:
6491     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6492 
6493   case Intrinsic::amdgcn_log_clamp: {
6494     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6495       return SDValue();
6496 
6497     return emitRemovedIntrinsicError(DAG, DL, VT);
6498   }
6499   case Intrinsic::amdgcn_ldexp:
6500     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6501                        Op.getOperand(1), Op.getOperand(2));
6502 
6503   case Intrinsic::amdgcn_fract:
6504     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6505 
6506   case Intrinsic::amdgcn_class:
6507     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6508                        Op.getOperand(1), Op.getOperand(2));
6509   case Intrinsic::amdgcn_div_fmas:
6510     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6511                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6512                        Op.getOperand(4));
6513 
6514   case Intrinsic::amdgcn_div_fixup:
6515     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6516                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6517 
6518   case Intrinsic::amdgcn_div_scale: {
6519     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6520 
6521     // Translate to the operands expected by the machine instruction. The
6522     // first parameter must be the same as the first instruction.
6523     SDValue Numerator = Op.getOperand(1);
6524     SDValue Denominator = Op.getOperand(2);
6525 
6526     // Note this order is opposite of the machine instruction's operations,
6527     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6528     // intrinsic has the numerator as the first operand to match a normal
6529     // division operation.
6530 
6531     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6532 
6533     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6534                        Denominator, Numerator);
6535   }
6536   case Intrinsic::amdgcn_icmp: {
6537     // There is a Pat that handles this variant, so return it as-is.
6538     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6539         Op.getConstantOperandVal(2) == 0 &&
6540         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6541       return Op;
6542     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6543   }
6544   case Intrinsic::amdgcn_fcmp: {
6545     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6546   }
6547   case Intrinsic::amdgcn_ballot:
6548     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6549   case Intrinsic::amdgcn_fmed3:
6550     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6551                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6552   case Intrinsic::amdgcn_fdot2:
6553     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6554                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6555                        Op.getOperand(4));
6556   case Intrinsic::amdgcn_fmul_legacy:
6557     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6558                        Op.getOperand(1), Op.getOperand(2));
6559   case Intrinsic::amdgcn_sffbh:
6560     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6561   case Intrinsic::amdgcn_sbfe:
6562     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6563                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6564   case Intrinsic::amdgcn_ubfe:
6565     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6566                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6567   case Intrinsic::amdgcn_cvt_pkrtz:
6568   case Intrinsic::amdgcn_cvt_pknorm_i16:
6569   case Intrinsic::amdgcn_cvt_pknorm_u16:
6570   case Intrinsic::amdgcn_cvt_pk_i16:
6571   case Intrinsic::amdgcn_cvt_pk_u16: {
6572     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6573     EVT VT = Op.getValueType();
6574     unsigned Opcode;
6575 
6576     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6577       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6578     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6579       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6580     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6581       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6582     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6583       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6584     else
6585       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6586 
6587     if (isTypeLegal(VT))
6588       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6589 
6590     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6591                                Op.getOperand(1), Op.getOperand(2));
6592     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6593   }
6594   case Intrinsic::amdgcn_fmad_ftz:
6595     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6596                        Op.getOperand(2), Op.getOperand(3));
6597 
6598   case Intrinsic::amdgcn_if_break:
6599     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6600                                       Op->getOperand(1), Op->getOperand(2)), 0);
6601 
6602   case Intrinsic::amdgcn_groupstaticsize: {
6603     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6604     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6605       return Op;
6606 
6607     const Module *M = MF.getFunction().getParent();
6608     const GlobalValue *GV =
6609         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6610     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6611                                             SIInstrInfo::MO_ABS32_LO);
6612     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6613   }
6614   case Intrinsic::amdgcn_is_shared:
6615   case Intrinsic::amdgcn_is_private: {
6616     SDLoc SL(Op);
6617     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6618       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6619     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6620     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6621                                  Op.getOperand(1));
6622 
6623     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6624                                 DAG.getConstant(1, SL, MVT::i32));
6625     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6626   }
6627   case Intrinsic::amdgcn_alignbit:
6628     return DAG.getNode(ISD::FSHR, DL, VT,
6629                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6630   case Intrinsic::amdgcn_reloc_constant: {
6631     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6632     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6633     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6634     auto RelocSymbol = cast<GlobalVariable>(
6635         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6636     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6637                                             SIInstrInfo::MO_ABS32_LO);
6638     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6639   }
6640   default:
6641     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6642             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6643       return lowerImage(Op, ImageDimIntr, DAG, false);
6644 
6645     return Op;
6646   }
6647 }
6648 
6649 // This function computes an appropriate offset to pass to
6650 // MachineMemOperand::setOffset() based on the offset inputs to
6651 // an intrinsic.  If any of the offsets are non-contstant or
6652 // if VIndex is non-zero then this function returns 0.  Otherwise,
6653 // it returns the sum of VOffset, SOffset, and Offset.
6654 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6655                                       SDValue SOffset,
6656                                       SDValue Offset,
6657                                       SDValue VIndex = SDValue()) {
6658 
6659   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6660       !isa<ConstantSDNode>(Offset))
6661     return 0;
6662 
6663   if (VIndex) {
6664     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6665       return 0;
6666   }
6667 
6668   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6669          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6670          cast<ConstantSDNode>(Offset)->getSExtValue();
6671 }
6672 
6673 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6674                                                      SelectionDAG &DAG,
6675                                                      unsigned NewOpcode) const {
6676   SDLoc DL(Op);
6677 
6678   SDValue VData = Op.getOperand(2);
6679   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6680   SDValue Ops[] = {
6681     Op.getOperand(0), // Chain
6682     VData,            // vdata
6683     Op.getOperand(3), // rsrc
6684     DAG.getConstant(0, DL, MVT::i32), // vindex
6685     Offsets.first,    // voffset
6686     Op.getOperand(5), // soffset
6687     Offsets.second,   // offset
6688     Op.getOperand(6), // cachepolicy
6689     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6690   };
6691 
6692   auto *M = cast<MemSDNode>(Op);
6693   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6694 
6695   EVT MemVT = VData.getValueType();
6696   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6697                                  M->getMemOperand());
6698 }
6699 
6700 SDValue
6701 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6702                                                 unsigned NewOpcode) const {
6703   SDLoc DL(Op);
6704 
6705   SDValue VData = Op.getOperand(2);
6706   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6707   SDValue Ops[] = {
6708     Op.getOperand(0), // Chain
6709     VData,            // vdata
6710     Op.getOperand(3), // rsrc
6711     Op.getOperand(4), // vindex
6712     Offsets.first,    // voffset
6713     Op.getOperand(6), // soffset
6714     Offsets.second,   // offset
6715     Op.getOperand(7), // cachepolicy
6716     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6717   };
6718 
6719   auto *M = cast<MemSDNode>(Op);
6720   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6721                                                       Ops[3]));
6722 
6723   EVT MemVT = VData.getValueType();
6724   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6725                                  M->getMemOperand());
6726 }
6727 
6728 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6729                                                  SelectionDAG &DAG) const {
6730   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6731   SDLoc DL(Op);
6732 
6733   switch (IntrID) {
6734   case Intrinsic::amdgcn_ds_ordered_add:
6735   case Intrinsic::amdgcn_ds_ordered_swap: {
6736     MemSDNode *M = cast<MemSDNode>(Op);
6737     SDValue Chain = M->getOperand(0);
6738     SDValue M0 = M->getOperand(2);
6739     SDValue Value = M->getOperand(3);
6740     unsigned IndexOperand = M->getConstantOperandVal(7);
6741     unsigned WaveRelease = M->getConstantOperandVal(8);
6742     unsigned WaveDone = M->getConstantOperandVal(9);
6743 
6744     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6745     IndexOperand &= ~0x3f;
6746     unsigned CountDw = 0;
6747 
6748     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6749       CountDw = (IndexOperand >> 24) & 0xf;
6750       IndexOperand &= ~(0xf << 24);
6751 
6752       if (CountDw < 1 || CountDw > 4) {
6753         report_fatal_error(
6754             "ds_ordered_count: dword count must be between 1 and 4");
6755       }
6756     }
6757 
6758     if (IndexOperand)
6759       report_fatal_error("ds_ordered_count: bad index operand");
6760 
6761     if (WaveDone && !WaveRelease)
6762       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6763 
6764     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6765     unsigned ShaderType =
6766         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6767     unsigned Offset0 = OrderedCountIndex << 2;
6768     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6769                        (Instruction << 4);
6770 
6771     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6772       Offset1 |= (CountDw - 1) << 6;
6773 
6774     unsigned Offset = Offset0 | (Offset1 << 8);
6775 
6776     SDValue Ops[] = {
6777       Chain,
6778       Value,
6779       DAG.getTargetConstant(Offset, DL, MVT::i16),
6780       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6781     };
6782     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6783                                    M->getVTList(), Ops, M->getMemoryVT(),
6784                                    M->getMemOperand());
6785   }
6786   case Intrinsic::amdgcn_ds_fadd: {
6787     MemSDNode *M = cast<MemSDNode>(Op);
6788     unsigned Opc;
6789     switch (IntrID) {
6790     case Intrinsic::amdgcn_ds_fadd:
6791       Opc = ISD::ATOMIC_LOAD_FADD;
6792       break;
6793     }
6794 
6795     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6796                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6797                          M->getMemOperand());
6798   }
6799   case Intrinsic::amdgcn_atomic_inc:
6800   case Intrinsic::amdgcn_atomic_dec:
6801   case Intrinsic::amdgcn_ds_fmin:
6802   case Intrinsic::amdgcn_ds_fmax: {
6803     MemSDNode *M = cast<MemSDNode>(Op);
6804     unsigned Opc;
6805     switch (IntrID) {
6806     case Intrinsic::amdgcn_atomic_inc:
6807       Opc = AMDGPUISD::ATOMIC_INC;
6808       break;
6809     case Intrinsic::amdgcn_atomic_dec:
6810       Opc = AMDGPUISD::ATOMIC_DEC;
6811       break;
6812     case Intrinsic::amdgcn_ds_fmin:
6813       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6814       break;
6815     case Intrinsic::amdgcn_ds_fmax:
6816       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6817       break;
6818     default:
6819       llvm_unreachable("Unknown intrinsic!");
6820     }
6821     SDValue Ops[] = {
6822       M->getOperand(0), // Chain
6823       M->getOperand(2), // Ptr
6824       M->getOperand(3)  // Value
6825     };
6826 
6827     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6828                                    M->getMemoryVT(), M->getMemOperand());
6829   }
6830   case Intrinsic::amdgcn_buffer_load:
6831   case Intrinsic::amdgcn_buffer_load_format: {
6832     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6833     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6834     unsigned IdxEn = 1;
6835     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6836       IdxEn = Idx->getZExtValue() != 0;
6837     SDValue Ops[] = {
6838       Op.getOperand(0), // Chain
6839       Op.getOperand(2), // rsrc
6840       Op.getOperand(3), // vindex
6841       SDValue(),        // voffset -- will be set by setBufferOffsets
6842       SDValue(),        // soffset -- will be set by setBufferOffsets
6843       SDValue(),        // offset -- will be set by setBufferOffsets
6844       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6845       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6846     };
6847 
6848     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6849     // We don't know the offset if vindex is non-zero, so clear it.
6850     if (IdxEn)
6851       Offset = 0;
6852 
6853     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6854         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6855 
6856     EVT VT = Op.getValueType();
6857     EVT IntVT = VT.changeTypeToInteger();
6858     auto *M = cast<MemSDNode>(Op);
6859     M->getMemOperand()->setOffset(Offset);
6860     EVT LoadVT = Op.getValueType();
6861 
6862     if (LoadVT.getScalarType() == MVT::f16)
6863       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6864                                  M, DAG, Ops);
6865 
6866     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6867     if (LoadVT.getScalarType() == MVT::i8 ||
6868         LoadVT.getScalarType() == MVT::i16)
6869       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6870 
6871     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6872                                M->getMemOperand(), DAG);
6873   }
6874   case Intrinsic::amdgcn_raw_buffer_load:
6875   case Intrinsic::amdgcn_raw_buffer_load_format: {
6876     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6877 
6878     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6879     SDValue Ops[] = {
6880       Op.getOperand(0), // Chain
6881       Op.getOperand(2), // rsrc
6882       DAG.getConstant(0, DL, MVT::i32), // vindex
6883       Offsets.first,    // voffset
6884       Op.getOperand(4), // soffset
6885       Offsets.second,   // offset
6886       Op.getOperand(5), // cachepolicy, swizzled buffer
6887       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6888     };
6889 
6890     auto *M = cast<MemSDNode>(Op);
6891     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6892     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6893   }
6894   case Intrinsic::amdgcn_struct_buffer_load:
6895   case Intrinsic::amdgcn_struct_buffer_load_format: {
6896     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6897 
6898     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6899     SDValue Ops[] = {
6900       Op.getOperand(0), // Chain
6901       Op.getOperand(2), // rsrc
6902       Op.getOperand(3), // vindex
6903       Offsets.first,    // voffset
6904       Op.getOperand(5), // soffset
6905       Offsets.second,   // offset
6906       Op.getOperand(6), // cachepolicy, swizzled buffer
6907       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6908     };
6909 
6910     auto *M = cast<MemSDNode>(Op);
6911     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6912                                                         Ops[2]));
6913     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6914   }
6915   case Intrinsic::amdgcn_tbuffer_load: {
6916     MemSDNode *M = cast<MemSDNode>(Op);
6917     EVT LoadVT = Op.getValueType();
6918 
6919     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6920     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6921     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6922     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6923     unsigned IdxEn = 1;
6924     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6925       IdxEn = Idx->getZExtValue() != 0;
6926     SDValue Ops[] = {
6927       Op.getOperand(0),  // Chain
6928       Op.getOperand(2),  // rsrc
6929       Op.getOperand(3),  // vindex
6930       Op.getOperand(4),  // voffset
6931       Op.getOperand(5),  // soffset
6932       Op.getOperand(6),  // offset
6933       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6934       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6935       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6936     };
6937 
6938     if (LoadVT.getScalarType() == MVT::f16)
6939       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6940                                  M, DAG, Ops);
6941     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6942                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6943                                DAG);
6944   }
6945   case Intrinsic::amdgcn_raw_tbuffer_load: {
6946     MemSDNode *M = cast<MemSDNode>(Op);
6947     EVT LoadVT = Op.getValueType();
6948     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6949 
6950     SDValue Ops[] = {
6951       Op.getOperand(0),  // Chain
6952       Op.getOperand(2),  // rsrc
6953       DAG.getConstant(0, DL, MVT::i32), // vindex
6954       Offsets.first,     // voffset
6955       Op.getOperand(4),  // soffset
6956       Offsets.second,    // offset
6957       Op.getOperand(5),  // format
6958       Op.getOperand(6),  // cachepolicy, swizzled buffer
6959       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6960     };
6961 
6962     if (LoadVT.getScalarType() == MVT::f16)
6963       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6964                                  M, DAG, Ops);
6965     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6966                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6967                                DAG);
6968   }
6969   case Intrinsic::amdgcn_struct_tbuffer_load: {
6970     MemSDNode *M = cast<MemSDNode>(Op);
6971     EVT LoadVT = Op.getValueType();
6972     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6973 
6974     SDValue Ops[] = {
6975       Op.getOperand(0),  // Chain
6976       Op.getOperand(2),  // rsrc
6977       Op.getOperand(3),  // vindex
6978       Offsets.first,     // voffset
6979       Op.getOperand(5),  // soffset
6980       Offsets.second,    // offset
6981       Op.getOperand(6),  // format
6982       Op.getOperand(7),  // cachepolicy, swizzled buffer
6983       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6984     };
6985 
6986     if (LoadVT.getScalarType() == MVT::f16)
6987       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6988                                  M, DAG, Ops);
6989     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6990                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6991                                DAG);
6992   }
6993   case Intrinsic::amdgcn_buffer_atomic_swap:
6994   case Intrinsic::amdgcn_buffer_atomic_add:
6995   case Intrinsic::amdgcn_buffer_atomic_sub:
6996   case Intrinsic::amdgcn_buffer_atomic_csub:
6997   case Intrinsic::amdgcn_buffer_atomic_smin:
6998   case Intrinsic::amdgcn_buffer_atomic_umin:
6999   case Intrinsic::amdgcn_buffer_atomic_smax:
7000   case Intrinsic::amdgcn_buffer_atomic_umax:
7001   case Intrinsic::amdgcn_buffer_atomic_and:
7002   case Intrinsic::amdgcn_buffer_atomic_or:
7003   case Intrinsic::amdgcn_buffer_atomic_xor:
7004   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7005     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7006     unsigned IdxEn = 1;
7007     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7008       IdxEn = Idx->getZExtValue() != 0;
7009     SDValue Ops[] = {
7010       Op.getOperand(0), // Chain
7011       Op.getOperand(2), // vdata
7012       Op.getOperand(3), // rsrc
7013       Op.getOperand(4), // vindex
7014       SDValue(),        // voffset -- will be set by setBufferOffsets
7015       SDValue(),        // soffset -- will be set by setBufferOffsets
7016       SDValue(),        // offset -- will be set by setBufferOffsets
7017       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7018       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7019     };
7020     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7021     // We don't know the offset if vindex is non-zero, so clear it.
7022     if (IdxEn)
7023       Offset = 0;
7024     EVT VT = Op.getValueType();
7025 
7026     auto *M = cast<MemSDNode>(Op);
7027     M->getMemOperand()->setOffset(Offset);
7028     unsigned Opcode = 0;
7029 
7030     switch (IntrID) {
7031     case Intrinsic::amdgcn_buffer_atomic_swap:
7032       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7033       break;
7034     case Intrinsic::amdgcn_buffer_atomic_add:
7035       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7036       break;
7037     case Intrinsic::amdgcn_buffer_atomic_sub:
7038       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7039       break;
7040     case Intrinsic::amdgcn_buffer_atomic_csub:
7041       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7042       break;
7043     case Intrinsic::amdgcn_buffer_atomic_smin:
7044       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7045       break;
7046     case Intrinsic::amdgcn_buffer_atomic_umin:
7047       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7048       break;
7049     case Intrinsic::amdgcn_buffer_atomic_smax:
7050       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7051       break;
7052     case Intrinsic::amdgcn_buffer_atomic_umax:
7053       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7054       break;
7055     case Intrinsic::amdgcn_buffer_atomic_and:
7056       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7057       break;
7058     case Intrinsic::amdgcn_buffer_atomic_or:
7059       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7060       break;
7061     case Intrinsic::amdgcn_buffer_atomic_xor:
7062       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7063       break;
7064     case Intrinsic::amdgcn_buffer_atomic_fadd:
7065       if (!Op.getValue(0).use_empty()) {
7066         DiagnosticInfoUnsupported
7067           NoFpRet(DAG.getMachineFunction().getFunction(),
7068                   "return versions of fp atomics not supported",
7069                   DL.getDebugLoc(), DS_Error);
7070         DAG.getContext()->diagnose(NoFpRet);
7071         return SDValue();
7072       }
7073       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7074       break;
7075     default:
7076       llvm_unreachable("unhandled atomic opcode");
7077     }
7078 
7079     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7080                                    M->getMemOperand());
7081   }
7082   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7083     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7084   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7085     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7086   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7087     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7088   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7089     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7090   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7091     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7092   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7093     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7094   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7095     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7096   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7097     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7098   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7099     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7100   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7101     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7102   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7103     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7104   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7105     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7106   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7107     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7108   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7109     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7110   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7111     return lowerStructBufferAtomicIntrin(Op, DAG,
7112                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7113   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7114     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7115   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7116     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7117   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7118     return lowerStructBufferAtomicIntrin(Op, DAG,
7119                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7120   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7121     return lowerStructBufferAtomicIntrin(Op, DAG,
7122                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7123   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7124     return lowerStructBufferAtomicIntrin(Op, DAG,
7125                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7126   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7127     return lowerStructBufferAtomicIntrin(Op, DAG,
7128                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7129   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7130     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7131   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7132     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7133   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7134     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7135   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7136     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7137   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7138     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7139 
7140   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7141     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7142     unsigned IdxEn = 1;
7143     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7144       IdxEn = Idx->getZExtValue() != 0;
7145     SDValue Ops[] = {
7146       Op.getOperand(0), // Chain
7147       Op.getOperand(2), // src
7148       Op.getOperand(3), // cmp
7149       Op.getOperand(4), // rsrc
7150       Op.getOperand(5), // vindex
7151       SDValue(),        // voffset -- will be set by setBufferOffsets
7152       SDValue(),        // soffset -- will be set by setBufferOffsets
7153       SDValue(),        // offset -- will be set by setBufferOffsets
7154       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7155       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7156     };
7157     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7158     // We don't know the offset if vindex is non-zero, so clear it.
7159     if (IdxEn)
7160       Offset = 0;
7161     EVT VT = Op.getValueType();
7162     auto *M = cast<MemSDNode>(Op);
7163     M->getMemOperand()->setOffset(Offset);
7164 
7165     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7166                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7167   }
7168   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7169     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7170     SDValue Ops[] = {
7171       Op.getOperand(0), // Chain
7172       Op.getOperand(2), // src
7173       Op.getOperand(3), // cmp
7174       Op.getOperand(4), // rsrc
7175       DAG.getConstant(0, DL, MVT::i32), // vindex
7176       Offsets.first,    // voffset
7177       Op.getOperand(6), // soffset
7178       Offsets.second,   // offset
7179       Op.getOperand(7), // cachepolicy
7180       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7181     };
7182     EVT VT = Op.getValueType();
7183     auto *M = cast<MemSDNode>(Op);
7184     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7185 
7186     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7187                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7188   }
7189   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7190     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7191     SDValue Ops[] = {
7192       Op.getOperand(0), // Chain
7193       Op.getOperand(2), // src
7194       Op.getOperand(3), // cmp
7195       Op.getOperand(4), // rsrc
7196       Op.getOperand(5), // vindex
7197       Offsets.first,    // voffset
7198       Op.getOperand(7), // soffset
7199       Offsets.second,   // offset
7200       Op.getOperand(8), // cachepolicy
7201       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7202     };
7203     EVT VT = Op.getValueType();
7204     auto *M = cast<MemSDNode>(Op);
7205     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7206                                                         Ops[4]));
7207 
7208     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7209                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7210   }
7211   case Intrinsic::amdgcn_global_atomic_fadd: {
7212     if (!Op.getValue(0).use_empty()) {
7213       DiagnosticInfoUnsupported
7214         NoFpRet(DAG.getMachineFunction().getFunction(),
7215                 "return versions of fp atomics not supported",
7216                 DL.getDebugLoc(), DS_Error);
7217       DAG.getContext()->diagnose(NoFpRet);
7218       return SDValue();
7219     }
7220     MemSDNode *M = cast<MemSDNode>(Op);
7221     SDValue Ops[] = {
7222       M->getOperand(0), // Chain
7223       M->getOperand(2), // Ptr
7224       M->getOperand(3)  // Value
7225     };
7226 
7227     EVT VT = Op.getOperand(3).getValueType();
7228     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7229                          DAG.getVTList(VT, MVT::Other), Ops,
7230                          M->getMemOperand());
7231   }
7232   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7233     SDLoc DL(Op);
7234     MemSDNode *M = cast<MemSDNode>(Op);
7235     SDValue NodePtr = M->getOperand(2);
7236     SDValue RayExtent = M->getOperand(3);
7237     SDValue RayOrigin = M->getOperand(4);
7238     SDValue RayDir = M->getOperand(5);
7239     SDValue RayInvDir = M->getOperand(6);
7240     SDValue TDescr = M->getOperand(7);
7241 
7242     assert(NodePtr.getValueType() == MVT::i32 ||
7243            NodePtr.getValueType() == MVT::i64);
7244     assert(RayDir.getValueType() == MVT::v4f16 ||
7245            RayDir.getValueType() == MVT::v4f32);
7246 
7247     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7248     bool Is64 = NodePtr.getValueType() == MVT::i64;
7249     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7250                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7251                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7252                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7253 
7254     SmallVector<SDValue, 16> Ops;
7255 
7256     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7257       SmallVector<SDValue, 3> Lanes;
7258       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7259       if (Lanes[0].getValueSizeInBits() == 32) {
7260         for (unsigned I = 0; I < 3; ++I)
7261           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7262       } else {
7263         if (IsAligned) {
7264           Ops.push_back(
7265             DAG.getBitcast(MVT::i32,
7266                            DAG.getBuildVector(MVT::v2f16, DL,
7267                                               { Lanes[0], Lanes[1] })));
7268           Ops.push_back(Lanes[2]);
7269         } else {
7270           SDValue Elt0 = Ops.pop_back_val();
7271           Ops.push_back(
7272             DAG.getBitcast(MVT::i32,
7273                            DAG.getBuildVector(MVT::v2f16, DL,
7274                                               { Elt0, Lanes[0] })));
7275           Ops.push_back(
7276             DAG.getBitcast(MVT::i32,
7277                            DAG.getBuildVector(MVT::v2f16, DL,
7278                                               { Lanes[1], Lanes[2] })));
7279         }
7280       }
7281     };
7282 
7283     if (Is64)
7284       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7285     else
7286       Ops.push_back(NodePtr);
7287 
7288     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7289     packLanes(RayOrigin, true);
7290     packLanes(RayDir, true);
7291     packLanes(RayInvDir, false);
7292     Ops.push_back(TDescr);
7293     if (IsA16)
7294       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7295     Ops.push_back(M->getChain());
7296 
7297     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7298     MachineMemOperand *MemRef = M->getMemOperand();
7299     DAG.setNodeMemRefs(NewNode, {MemRef});
7300     return SDValue(NewNode, 0);
7301   }
7302   default:
7303     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7304             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7305       return lowerImage(Op, ImageDimIntr, DAG, true);
7306 
7307     return SDValue();
7308   }
7309 }
7310 
7311 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7312 // dwordx4 if on SI.
7313 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7314                                               SDVTList VTList,
7315                                               ArrayRef<SDValue> Ops, EVT MemVT,
7316                                               MachineMemOperand *MMO,
7317                                               SelectionDAG &DAG) const {
7318   EVT VT = VTList.VTs[0];
7319   EVT WidenedVT = VT;
7320   EVT WidenedMemVT = MemVT;
7321   if (!Subtarget->hasDwordx3LoadStores() &&
7322       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7323     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7324                                  WidenedVT.getVectorElementType(), 4);
7325     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7326                                     WidenedMemVT.getVectorElementType(), 4);
7327     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7328   }
7329 
7330   assert(VTList.NumVTs == 2);
7331   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7332 
7333   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7334                                        WidenedMemVT, MMO);
7335   if (WidenedVT != VT) {
7336     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7337                                DAG.getVectorIdxConstant(0, DL));
7338     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7339   }
7340   return NewOp;
7341 }
7342 
7343 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7344                                          bool ImageStore) const {
7345   EVT StoreVT = VData.getValueType();
7346 
7347   // No change for f16 and legal vector D16 types.
7348   if (!StoreVT.isVector())
7349     return VData;
7350 
7351   SDLoc DL(VData);
7352   unsigned NumElements = StoreVT.getVectorNumElements();
7353 
7354   if (Subtarget->hasUnpackedD16VMem()) {
7355     // We need to unpack the packed data to store.
7356     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7357     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7358 
7359     EVT EquivStoreVT =
7360         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7361     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7362     return DAG.UnrollVectorOp(ZExt.getNode());
7363   }
7364 
7365   // The sq block of gfx8.1 does not estimate register use correctly for d16
7366   // image store instructions. The data operand is computed as if it were not a
7367   // d16 image instruction.
7368   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7369     // Bitcast to i16
7370     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7371     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7372 
7373     // Decompose into scalars
7374     SmallVector<SDValue, 4> Elts;
7375     DAG.ExtractVectorElements(IntVData, Elts);
7376 
7377     // Group pairs of i16 into v2i16 and bitcast to i32
7378     SmallVector<SDValue, 4> PackedElts;
7379     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7380       SDValue Pair =
7381           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7382       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7383       PackedElts.push_back(IntPair);
7384     }
7385     if ((NumElements % 2) == 1) {
7386       // Handle v3i16
7387       unsigned I = Elts.size() / 2;
7388       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7389                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7390       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7391       PackedElts.push_back(IntPair);
7392     }
7393 
7394     // Pad using UNDEF
7395     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7396 
7397     // Build final vector
7398     EVT VecVT =
7399         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7400     return DAG.getBuildVector(VecVT, DL, PackedElts);
7401   }
7402 
7403   if (NumElements == 3) {
7404     EVT IntStoreVT =
7405         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7406     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7407 
7408     EVT WidenedStoreVT = EVT::getVectorVT(
7409         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7410     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7411                                          WidenedStoreVT.getStoreSizeInBits());
7412     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7413     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7414   }
7415 
7416   assert(isTypeLegal(StoreVT));
7417   return VData;
7418 }
7419 
7420 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7421                                               SelectionDAG &DAG) const {
7422   SDLoc DL(Op);
7423   SDValue Chain = Op.getOperand(0);
7424   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7425   MachineFunction &MF = DAG.getMachineFunction();
7426 
7427   switch (IntrinsicID) {
7428   case Intrinsic::amdgcn_exp_compr: {
7429     SDValue Src0 = Op.getOperand(4);
7430     SDValue Src1 = Op.getOperand(5);
7431     // Hack around illegal type on SI by directly selecting it.
7432     if (isTypeLegal(Src0.getValueType()))
7433       return SDValue();
7434 
7435     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7436     SDValue Undef = DAG.getUNDEF(MVT::f32);
7437     const SDValue Ops[] = {
7438       Op.getOperand(2), // tgt
7439       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7440       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7441       Undef, // src2
7442       Undef, // src3
7443       Op.getOperand(7), // vm
7444       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7445       Op.getOperand(3), // en
7446       Op.getOperand(0) // Chain
7447     };
7448 
7449     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7450     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7451   }
7452   case Intrinsic::amdgcn_s_barrier: {
7453     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7454       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7455       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7456       if (WGSize <= ST.getWavefrontSize())
7457         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7458                                           Op.getOperand(0)), 0);
7459     }
7460     return SDValue();
7461   };
7462   case Intrinsic::amdgcn_tbuffer_store: {
7463     SDValue VData = Op.getOperand(2);
7464     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7465     if (IsD16)
7466       VData = handleD16VData(VData, DAG);
7467     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7468     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7469     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7470     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7471     unsigned IdxEn = 1;
7472     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7473       IdxEn = Idx->getZExtValue() != 0;
7474     SDValue Ops[] = {
7475       Chain,
7476       VData,             // vdata
7477       Op.getOperand(3),  // rsrc
7478       Op.getOperand(4),  // vindex
7479       Op.getOperand(5),  // voffset
7480       Op.getOperand(6),  // soffset
7481       Op.getOperand(7),  // offset
7482       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7483       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7484       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7485     };
7486     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7487                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7488     MemSDNode *M = cast<MemSDNode>(Op);
7489     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7490                                    M->getMemoryVT(), M->getMemOperand());
7491   }
7492 
7493   case Intrinsic::amdgcn_struct_tbuffer_store: {
7494     SDValue VData = Op.getOperand(2);
7495     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7496     if (IsD16)
7497       VData = handleD16VData(VData, DAG);
7498     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7499     SDValue Ops[] = {
7500       Chain,
7501       VData,             // vdata
7502       Op.getOperand(3),  // rsrc
7503       Op.getOperand(4),  // vindex
7504       Offsets.first,     // voffset
7505       Op.getOperand(6),  // soffset
7506       Offsets.second,    // offset
7507       Op.getOperand(7),  // format
7508       Op.getOperand(8),  // cachepolicy, swizzled buffer
7509       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7510     };
7511     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7512                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7513     MemSDNode *M = cast<MemSDNode>(Op);
7514     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7515                                    M->getMemoryVT(), M->getMemOperand());
7516   }
7517 
7518   case Intrinsic::amdgcn_raw_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     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7524     SDValue Ops[] = {
7525       Chain,
7526       VData,             // vdata
7527       Op.getOperand(3),  // rsrc
7528       DAG.getConstant(0, DL, MVT::i32), // vindex
7529       Offsets.first,     // voffset
7530       Op.getOperand(5),  // soffset
7531       Offsets.second,    // offset
7532       Op.getOperand(6),  // format
7533       Op.getOperand(7),  // cachepolicy, swizzled buffer
7534       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7535     };
7536     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7537                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7538     MemSDNode *M = cast<MemSDNode>(Op);
7539     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7540                                    M->getMemoryVT(), M->getMemOperand());
7541   }
7542 
7543   case Intrinsic::amdgcn_buffer_store:
7544   case Intrinsic::amdgcn_buffer_store_format: {
7545     SDValue VData = Op.getOperand(2);
7546     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7547     if (IsD16)
7548       VData = handleD16VData(VData, DAG);
7549     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7550     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7551     unsigned IdxEn = 1;
7552     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7553       IdxEn = Idx->getZExtValue() != 0;
7554     SDValue Ops[] = {
7555       Chain,
7556       VData,
7557       Op.getOperand(3), // rsrc
7558       Op.getOperand(4), // vindex
7559       SDValue(), // voffset -- will be set by setBufferOffsets
7560       SDValue(), // soffset -- will be set by setBufferOffsets
7561       SDValue(), // offset -- will be set by setBufferOffsets
7562       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7563       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7564     };
7565     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7566     // We don't know the offset if vindex is non-zero, so clear it.
7567     if (IdxEn)
7568       Offset = 0;
7569     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7570                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7571     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7572     MemSDNode *M = cast<MemSDNode>(Op);
7573     M->getMemOperand()->setOffset(Offset);
7574 
7575     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7576     EVT VDataType = VData.getValueType().getScalarType();
7577     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7578       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7579 
7580     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7581                                    M->getMemoryVT(), M->getMemOperand());
7582   }
7583 
7584   case Intrinsic::amdgcn_raw_buffer_store:
7585   case Intrinsic::amdgcn_raw_buffer_store_format: {
7586     const bool IsFormat =
7587         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7588 
7589     SDValue VData = Op.getOperand(2);
7590     EVT VDataVT = VData.getValueType();
7591     EVT EltType = VDataVT.getScalarType();
7592     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7593     if (IsD16) {
7594       VData = handleD16VData(VData, DAG);
7595       VDataVT = VData.getValueType();
7596     }
7597 
7598     if (!isTypeLegal(VDataVT)) {
7599       VData =
7600           DAG.getNode(ISD::BITCAST, DL,
7601                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7602     }
7603 
7604     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7605     SDValue Ops[] = {
7606       Chain,
7607       VData,
7608       Op.getOperand(3), // rsrc
7609       DAG.getConstant(0, DL, MVT::i32), // vindex
7610       Offsets.first,    // voffset
7611       Op.getOperand(5), // soffset
7612       Offsets.second,   // offset
7613       Op.getOperand(6), // cachepolicy, swizzled buffer
7614       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7615     };
7616     unsigned Opc =
7617         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7618     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7619     MemSDNode *M = cast<MemSDNode>(Op);
7620     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7621 
7622     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7623     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7624       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7625 
7626     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7627                                    M->getMemoryVT(), M->getMemOperand());
7628   }
7629 
7630   case Intrinsic::amdgcn_struct_buffer_store:
7631   case Intrinsic::amdgcn_struct_buffer_store_format: {
7632     const bool IsFormat =
7633         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7634 
7635     SDValue VData = Op.getOperand(2);
7636     EVT VDataVT = VData.getValueType();
7637     EVT EltType = VDataVT.getScalarType();
7638     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7639 
7640     if (IsD16) {
7641       VData = handleD16VData(VData, DAG);
7642       VDataVT = VData.getValueType();
7643     }
7644 
7645     if (!isTypeLegal(VDataVT)) {
7646       VData =
7647           DAG.getNode(ISD::BITCAST, DL,
7648                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7649     }
7650 
7651     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7652     SDValue Ops[] = {
7653       Chain,
7654       VData,
7655       Op.getOperand(3), // rsrc
7656       Op.getOperand(4), // vindex
7657       Offsets.first,    // voffset
7658       Op.getOperand(6), // soffset
7659       Offsets.second,   // offset
7660       Op.getOperand(7), // cachepolicy, swizzled buffer
7661       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7662     };
7663     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7664                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7665     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7666     MemSDNode *M = cast<MemSDNode>(Op);
7667     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7668                                                         Ops[3]));
7669 
7670     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7671     EVT VDataType = VData.getValueType().getScalarType();
7672     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7673       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7674 
7675     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7676                                    M->getMemoryVT(), M->getMemOperand());
7677   }
7678   case Intrinsic::amdgcn_end_cf:
7679     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7680                                       Op->getOperand(2), Chain), 0);
7681 
7682   default: {
7683     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7684             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7685       return lowerImage(Op, ImageDimIntr, DAG, true);
7686 
7687     return Op;
7688   }
7689   }
7690 }
7691 
7692 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7693 // offset (the offset that is included in bounds checking and swizzling, to be
7694 // split between the instruction's voffset and immoffset fields) and soffset
7695 // (the offset that is excluded from bounds checking and swizzling, to go in
7696 // the instruction's soffset field).  This function takes the first kind of
7697 // offset and figures out how to split it between voffset and immoffset.
7698 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7699     SDValue Offset, SelectionDAG &DAG) const {
7700   SDLoc DL(Offset);
7701   const unsigned MaxImm = 4095;
7702   SDValue N0 = Offset;
7703   ConstantSDNode *C1 = nullptr;
7704 
7705   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7706     N0 = SDValue();
7707   else if (DAG.isBaseWithConstantOffset(N0)) {
7708     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7709     N0 = N0.getOperand(0);
7710   }
7711 
7712   if (C1) {
7713     unsigned ImmOffset = C1->getZExtValue();
7714     // If the immediate value is too big for the immoffset field, put the value
7715     // and -4096 into the immoffset field so that the value that is copied/added
7716     // for the voffset field is a multiple of 4096, and it stands more chance
7717     // of being CSEd with the copy/add for another similar load/store.
7718     // However, do not do that rounding down to a multiple of 4096 if that is a
7719     // negative number, as it appears to be illegal to have a negative offset
7720     // in the vgpr, even if adding the immediate offset makes it positive.
7721     unsigned Overflow = ImmOffset & ~MaxImm;
7722     ImmOffset -= Overflow;
7723     if ((int32_t)Overflow < 0) {
7724       Overflow += ImmOffset;
7725       ImmOffset = 0;
7726     }
7727     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7728     if (Overflow) {
7729       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7730       if (!N0)
7731         N0 = OverflowVal;
7732       else {
7733         SDValue Ops[] = { N0, OverflowVal };
7734         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7735       }
7736     }
7737   }
7738   if (!N0)
7739     N0 = DAG.getConstant(0, DL, MVT::i32);
7740   if (!C1)
7741     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7742   return {N0, SDValue(C1, 0)};
7743 }
7744 
7745 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7746 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7747 // pointed to by Offsets.
7748 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7749                                             SelectionDAG &DAG, SDValue *Offsets,
7750                                             Align Alignment) const {
7751   SDLoc DL(CombinedOffset);
7752   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7753     uint32_t Imm = C->getZExtValue();
7754     uint32_t SOffset, ImmOffset;
7755     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7756                                  Alignment)) {
7757       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7758       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7759       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7760       return SOffset + ImmOffset;
7761     }
7762   }
7763   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7764     SDValue N0 = CombinedOffset.getOperand(0);
7765     SDValue N1 = CombinedOffset.getOperand(1);
7766     uint32_t SOffset, ImmOffset;
7767     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7768     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7769                                                 Subtarget, Alignment)) {
7770       Offsets[0] = N0;
7771       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7772       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7773       return 0;
7774     }
7775   }
7776   Offsets[0] = CombinedOffset;
7777   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7778   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7779   return 0;
7780 }
7781 
7782 // Handle 8 bit and 16 bit buffer loads
7783 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7784                                                      EVT LoadVT, SDLoc DL,
7785                                                      ArrayRef<SDValue> Ops,
7786                                                      MemSDNode *M) const {
7787   EVT IntVT = LoadVT.changeTypeToInteger();
7788   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7789          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7790 
7791   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7792   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7793                                                Ops, IntVT,
7794                                                M->getMemOperand());
7795   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7796   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7797 
7798   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7799 }
7800 
7801 // Handle 8 bit and 16 bit buffer stores
7802 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7803                                                       EVT VDataType, SDLoc DL,
7804                                                       SDValue Ops[],
7805                                                       MemSDNode *M) const {
7806   if (VDataType == MVT::f16)
7807     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7808 
7809   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7810   Ops[1] = BufferStoreExt;
7811   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7812                                  AMDGPUISD::BUFFER_STORE_SHORT;
7813   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7814   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7815                                      M->getMemOperand());
7816 }
7817 
7818 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7819                                  ISD::LoadExtType ExtType, SDValue Op,
7820                                  const SDLoc &SL, EVT VT) {
7821   if (VT.bitsLT(Op.getValueType()))
7822     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7823 
7824   switch (ExtType) {
7825   case ISD::SEXTLOAD:
7826     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7827   case ISD::ZEXTLOAD:
7828     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7829   case ISD::EXTLOAD:
7830     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7831   case ISD::NON_EXTLOAD:
7832     return Op;
7833   }
7834 
7835   llvm_unreachable("invalid ext type");
7836 }
7837 
7838 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7839   SelectionDAG &DAG = DCI.DAG;
7840   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7841     return SDValue();
7842 
7843   // FIXME: Constant loads should all be marked invariant.
7844   unsigned AS = Ld->getAddressSpace();
7845   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7846       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7847       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7848     return SDValue();
7849 
7850   // Don't do this early, since it may interfere with adjacent load merging for
7851   // illegal types. We can avoid losing alignment information for exotic types
7852   // pre-legalize.
7853   EVT MemVT = Ld->getMemoryVT();
7854   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7855       MemVT.getSizeInBits() >= 32)
7856     return SDValue();
7857 
7858   SDLoc SL(Ld);
7859 
7860   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7861          "unexpected vector extload");
7862 
7863   // TODO: Drop only high part of range.
7864   SDValue Ptr = Ld->getBasePtr();
7865   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7866                                 MVT::i32, SL, Ld->getChain(), Ptr,
7867                                 Ld->getOffset(),
7868                                 Ld->getPointerInfo(), MVT::i32,
7869                                 Ld->getAlignment(),
7870                                 Ld->getMemOperand()->getFlags(),
7871                                 Ld->getAAInfo(),
7872                                 nullptr); // Drop ranges
7873 
7874   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7875   if (MemVT.isFloatingPoint()) {
7876     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7877            "unexpected fp extload");
7878     TruncVT = MemVT.changeTypeToInteger();
7879   }
7880 
7881   SDValue Cvt = NewLoad;
7882   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7883     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7884                       DAG.getValueType(TruncVT));
7885   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7886              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7887     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7888   } else {
7889     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7890   }
7891 
7892   EVT VT = Ld->getValueType(0);
7893   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7894 
7895   DCI.AddToWorklist(Cvt.getNode());
7896 
7897   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7898   // the appropriate extension from the 32-bit load.
7899   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7900   DCI.AddToWorklist(Cvt.getNode());
7901 
7902   // Handle conversion back to floating point if necessary.
7903   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7904 
7905   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7906 }
7907 
7908 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7909   SDLoc DL(Op);
7910   LoadSDNode *Load = cast<LoadSDNode>(Op);
7911   ISD::LoadExtType ExtType = Load->getExtensionType();
7912   EVT MemVT = Load->getMemoryVT();
7913 
7914   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7915     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7916       return SDValue();
7917 
7918     // FIXME: Copied from PPC
7919     // First, load into 32 bits, then truncate to 1 bit.
7920 
7921     SDValue Chain = Load->getChain();
7922     SDValue BasePtr = Load->getBasePtr();
7923     MachineMemOperand *MMO = Load->getMemOperand();
7924 
7925     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7926 
7927     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7928                                    BasePtr, RealMemVT, MMO);
7929 
7930     if (!MemVT.isVector()) {
7931       SDValue Ops[] = {
7932         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7933         NewLD.getValue(1)
7934       };
7935 
7936       return DAG.getMergeValues(Ops, DL);
7937     }
7938 
7939     SmallVector<SDValue, 3> Elts;
7940     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7941       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7942                                 DAG.getConstant(I, DL, MVT::i32));
7943 
7944       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7945     }
7946 
7947     SDValue Ops[] = {
7948       DAG.getBuildVector(MemVT, DL, Elts),
7949       NewLD.getValue(1)
7950     };
7951 
7952     return DAG.getMergeValues(Ops, DL);
7953   }
7954 
7955   if (!MemVT.isVector())
7956     return SDValue();
7957 
7958   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7959          "Custom lowering for non-i32 vectors hasn't been implemented.");
7960 
7961   unsigned Alignment = Load->getAlignment();
7962   unsigned AS = Load->getAddressSpace();
7963   if (Subtarget->hasLDSMisalignedBug() &&
7964       AS == AMDGPUAS::FLAT_ADDRESS &&
7965       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7966     return SplitVectorLoad(Op, DAG);
7967   }
7968 
7969   MachineFunction &MF = DAG.getMachineFunction();
7970   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7971   // If there is a possibilty that flat instruction access scratch memory
7972   // then we need to use the same legalization rules we use for private.
7973   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7974       !Subtarget->hasMultiDwordFlatScratchAddressing())
7975     AS = MFI->hasFlatScratchInit() ?
7976          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7977 
7978   unsigned NumElements = MemVT.getVectorNumElements();
7979 
7980   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7981       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7982     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7983       if (MemVT.isPow2VectorType())
7984         return SDValue();
7985       return WidenOrSplitVectorLoad(Op, DAG);
7986     }
7987     // Non-uniform loads will be selected to MUBUF instructions, so they
7988     // have the same legalization requirements as global and private
7989     // loads.
7990     //
7991   }
7992 
7993   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7994       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7995       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7996     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7997         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7998         Alignment >= 4 && NumElements < 32) {
7999       if (MemVT.isPow2VectorType())
8000         return SDValue();
8001       return WidenOrSplitVectorLoad(Op, DAG);
8002     }
8003     // Non-uniform loads will be selected to MUBUF instructions, so they
8004     // have the same legalization requirements as global and private
8005     // loads.
8006     //
8007   }
8008   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8009       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8010       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8011       AS == AMDGPUAS::FLAT_ADDRESS) {
8012     if (NumElements > 4)
8013       return SplitVectorLoad(Op, DAG);
8014     // v3 loads not supported on SI.
8015     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8016       return WidenOrSplitVectorLoad(Op, DAG);
8017 
8018     // v3 and v4 loads are supported for private and global memory.
8019     return SDValue();
8020   }
8021   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8022     // Depending on the setting of the private_element_size field in the
8023     // resource descriptor, we can only make private accesses up to a certain
8024     // size.
8025     switch (Subtarget->getMaxPrivateElementSize()) {
8026     case 4: {
8027       SDValue Ops[2];
8028       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8029       return DAG.getMergeValues(Ops, DL);
8030     }
8031     case 8:
8032       if (NumElements > 2)
8033         return SplitVectorLoad(Op, DAG);
8034       return SDValue();
8035     case 16:
8036       // Same as global/flat
8037       if (NumElements > 4)
8038         return SplitVectorLoad(Op, DAG);
8039       // v3 loads not supported on SI.
8040       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8041         return WidenOrSplitVectorLoad(Op, DAG);
8042 
8043       return SDValue();
8044     default:
8045       llvm_unreachable("unsupported private_element_size");
8046     }
8047   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8048     // Use ds_read_b128 or ds_read_b96 when possible.
8049     if (Subtarget->hasDS96AndDS128() &&
8050         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8051          MemVT.getStoreSize() == 12) &&
8052         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8053                                            Load->getAlign()))
8054       return SDValue();
8055 
8056     if (NumElements > 2)
8057       return SplitVectorLoad(Op, DAG);
8058 
8059     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8060     // address is negative, then the instruction is incorrectly treated as
8061     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8062     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8063     // load later in the SILoadStoreOptimizer.
8064     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8065         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8066         Load->getAlignment() < 8) {
8067       return SplitVectorLoad(Op, DAG);
8068     }
8069   }
8070 
8071   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8072                                       MemVT, *Load->getMemOperand())) {
8073     SDValue Ops[2];
8074     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8075     return DAG.getMergeValues(Ops, DL);
8076   }
8077 
8078   return SDValue();
8079 }
8080 
8081 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8082   EVT VT = Op.getValueType();
8083   assert(VT.getSizeInBits() == 64);
8084 
8085   SDLoc DL(Op);
8086   SDValue Cond = Op.getOperand(0);
8087 
8088   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8089   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8090 
8091   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8092   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8093 
8094   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8095   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8096 
8097   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8098 
8099   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8100   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8101 
8102   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8103 
8104   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8105   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8106 }
8107 
8108 // Catch division cases where we can use shortcuts with rcp and rsq
8109 // instructions.
8110 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8111                                               SelectionDAG &DAG) const {
8112   SDLoc SL(Op);
8113   SDValue LHS = Op.getOperand(0);
8114   SDValue RHS = Op.getOperand(1);
8115   EVT VT = Op.getValueType();
8116   const SDNodeFlags Flags = Op->getFlags();
8117 
8118   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8119 
8120   // Without !fpmath accuracy information, we can't do more because we don't
8121   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8122   if (!AllowInaccurateRcp)
8123     return SDValue();
8124 
8125   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8126     if (CLHS->isExactlyValue(1.0)) {
8127       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8128       // the CI documentation has a worst case error of 1 ulp.
8129       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8130       // use it as long as we aren't trying to use denormals.
8131       //
8132       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8133 
8134       // 1.0 / sqrt(x) -> rsq(x)
8135 
8136       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8137       // error seems really high at 2^29 ULP.
8138       if (RHS.getOpcode() == ISD::FSQRT)
8139         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8140 
8141       // 1.0 / x -> rcp(x)
8142       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8143     }
8144 
8145     // Same as for 1.0, but expand the sign out of the constant.
8146     if (CLHS->isExactlyValue(-1.0)) {
8147       // -1.0 / x -> rcp (fneg x)
8148       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8149       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8150     }
8151   }
8152 
8153   // Turn into multiply by the reciprocal.
8154   // x / y -> x * (1.0 / y)
8155   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8156   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8157 }
8158 
8159 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8160                                                 SelectionDAG &DAG) const {
8161   SDLoc SL(Op);
8162   SDValue X = Op.getOperand(0);
8163   SDValue Y = Op.getOperand(1);
8164   EVT VT = Op.getValueType();
8165   const SDNodeFlags Flags = Op->getFlags();
8166 
8167   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8168                             DAG.getTarget().Options.UnsafeFPMath;
8169   if (!AllowInaccurateDiv)
8170     return SDValue();
8171 
8172   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8173   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8174 
8175   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8176   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8177 
8178   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8179   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8180   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8181   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8182   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8183   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8184 }
8185 
8186 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8187                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8188                           SDNodeFlags Flags) {
8189   if (GlueChain->getNumValues() <= 1) {
8190     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8191   }
8192 
8193   assert(GlueChain->getNumValues() == 3);
8194 
8195   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8196   switch (Opcode) {
8197   default: llvm_unreachable("no chain equivalent for opcode");
8198   case ISD::FMUL:
8199     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8200     break;
8201   }
8202 
8203   return DAG.getNode(Opcode, SL, VTList,
8204                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8205                      Flags);
8206 }
8207 
8208 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8209                            EVT VT, SDValue A, SDValue B, SDValue C,
8210                            SDValue GlueChain, SDNodeFlags Flags) {
8211   if (GlueChain->getNumValues() <= 1) {
8212     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8213   }
8214 
8215   assert(GlueChain->getNumValues() == 3);
8216 
8217   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8218   switch (Opcode) {
8219   default: llvm_unreachable("no chain equivalent for opcode");
8220   case ISD::FMA:
8221     Opcode = AMDGPUISD::FMA_W_CHAIN;
8222     break;
8223   }
8224 
8225   return DAG.getNode(Opcode, SL, VTList,
8226                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8227                      Flags);
8228 }
8229 
8230 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8231   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8232     return FastLowered;
8233 
8234   SDLoc SL(Op);
8235   SDValue Src0 = Op.getOperand(0);
8236   SDValue Src1 = Op.getOperand(1);
8237 
8238   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8239   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8240 
8241   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8242   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8243 
8244   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8245   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8246 
8247   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8248 }
8249 
8250 // Faster 2.5 ULP division that does not support denormals.
8251 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8252   SDLoc SL(Op);
8253   SDValue LHS = Op.getOperand(1);
8254   SDValue RHS = Op.getOperand(2);
8255 
8256   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8257 
8258   const APFloat K0Val(BitsToFloat(0x6f800000));
8259   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8260 
8261   const APFloat K1Val(BitsToFloat(0x2f800000));
8262   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8263 
8264   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8265 
8266   EVT SetCCVT =
8267     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8268 
8269   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8270 
8271   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8272 
8273   // TODO: Should this propagate fast-math-flags?
8274   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8275 
8276   // rcp does not support denormals.
8277   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8278 
8279   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8280 
8281   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8282 }
8283 
8284 // Returns immediate value for setting the F32 denorm mode when using the
8285 // S_DENORM_MODE instruction.
8286 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8287                                     const SDLoc &SL, const GCNSubtarget *ST) {
8288   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8289   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8290                                 ? FP_DENORM_FLUSH_NONE
8291                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8292 
8293   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8294   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8295 }
8296 
8297 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8298   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8299     return FastLowered;
8300 
8301   // The selection matcher assumes anything with a chain selecting to a
8302   // mayRaiseFPException machine instruction. Since we're introducing a chain
8303   // here, we need to explicitly report nofpexcept for the regular fdiv
8304   // lowering.
8305   SDNodeFlags Flags = Op->getFlags();
8306   Flags.setNoFPExcept(true);
8307 
8308   SDLoc SL(Op);
8309   SDValue LHS = Op.getOperand(0);
8310   SDValue RHS = Op.getOperand(1);
8311 
8312   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8313 
8314   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8315 
8316   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8317                                           {RHS, RHS, LHS}, Flags);
8318   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8319                                         {LHS, RHS, LHS}, Flags);
8320 
8321   // Denominator is scaled to not be denormal, so using rcp is ok.
8322   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8323                                   DenominatorScaled, Flags);
8324   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8325                                      DenominatorScaled, Flags);
8326 
8327   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8328                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8329                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8330   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8331 
8332   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8333 
8334   if (!HasFP32Denormals) {
8335     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8336     // lowering. The chain dependence is insufficient, and we need glue. We do
8337     // not need the glue variants in a strictfp function.
8338 
8339     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8340 
8341     SDNode *EnableDenorm;
8342     if (Subtarget->hasDenormModeInst()) {
8343       const SDValue EnableDenormValue =
8344           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8345 
8346       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8347                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8348     } else {
8349       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8350                                                         SL, MVT::i32);
8351       EnableDenorm =
8352           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8353                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8354     }
8355 
8356     SDValue Ops[3] = {
8357       NegDivScale0,
8358       SDValue(EnableDenorm, 0),
8359       SDValue(EnableDenorm, 1)
8360     };
8361 
8362     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8363   }
8364 
8365   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8366                              ApproxRcp, One, NegDivScale0, Flags);
8367 
8368   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8369                              ApproxRcp, Fma0, Flags);
8370 
8371   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8372                            Fma1, Fma1, Flags);
8373 
8374   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8375                              NumeratorScaled, Mul, Flags);
8376 
8377   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8378                              Fma2, Fma1, Mul, Fma2, Flags);
8379 
8380   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8381                              NumeratorScaled, Fma3, Flags);
8382 
8383   if (!HasFP32Denormals) {
8384     SDNode *DisableDenorm;
8385     if (Subtarget->hasDenormModeInst()) {
8386       const SDValue DisableDenormValue =
8387           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8388 
8389       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8390                                   Fma4.getValue(1), DisableDenormValue,
8391                                   Fma4.getValue(2)).getNode();
8392     } else {
8393       const SDValue DisableDenormValue =
8394           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8395 
8396       DisableDenorm = DAG.getMachineNode(
8397           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8398           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8399     }
8400 
8401     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8402                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8403     DAG.setRoot(OutputChain);
8404   }
8405 
8406   SDValue Scale = NumeratorScaled.getValue(1);
8407   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8408                              {Fma4, Fma1, Fma3, Scale}, Flags);
8409 
8410   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8411 }
8412 
8413 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8414   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8415     return FastLowered;
8416 
8417   SDLoc SL(Op);
8418   SDValue X = Op.getOperand(0);
8419   SDValue Y = Op.getOperand(1);
8420 
8421   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8422 
8423   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8424 
8425   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8426 
8427   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8428 
8429   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8430 
8431   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8432 
8433   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8434 
8435   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8436 
8437   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8438 
8439   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8440   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8441 
8442   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8443                              NegDivScale0, Mul, DivScale1);
8444 
8445   SDValue Scale;
8446 
8447   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8448     // Workaround a hardware bug on SI where the condition output from div_scale
8449     // is not usable.
8450 
8451     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8452 
8453     // Figure out if the scale to use for div_fmas.
8454     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8455     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8456     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8457     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8458 
8459     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8460     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8461 
8462     SDValue Scale0Hi
8463       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8464     SDValue Scale1Hi
8465       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8466 
8467     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8468     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8469     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8470   } else {
8471     Scale = DivScale1.getValue(1);
8472   }
8473 
8474   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8475                              Fma4, Fma3, Mul, Scale);
8476 
8477   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8478 }
8479 
8480 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8481   EVT VT = Op.getValueType();
8482 
8483   if (VT == MVT::f32)
8484     return LowerFDIV32(Op, DAG);
8485 
8486   if (VT == MVT::f64)
8487     return LowerFDIV64(Op, DAG);
8488 
8489   if (VT == MVT::f16)
8490     return LowerFDIV16(Op, DAG);
8491 
8492   llvm_unreachable("Unexpected type for fdiv");
8493 }
8494 
8495 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8496   SDLoc DL(Op);
8497   StoreSDNode *Store = cast<StoreSDNode>(Op);
8498   EVT VT = Store->getMemoryVT();
8499 
8500   if (VT == MVT::i1) {
8501     return DAG.getTruncStore(Store->getChain(), DL,
8502        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8503        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8504   }
8505 
8506   assert(VT.isVector() &&
8507          Store->getValue().getValueType().getScalarType() == MVT::i32);
8508 
8509   unsigned AS = Store->getAddressSpace();
8510   if (Subtarget->hasLDSMisalignedBug() &&
8511       AS == AMDGPUAS::FLAT_ADDRESS &&
8512       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8513     return SplitVectorStore(Op, DAG);
8514   }
8515 
8516   MachineFunction &MF = DAG.getMachineFunction();
8517   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8518   // If there is a possibilty that flat instruction access scratch memory
8519   // then we need to use the same legalization rules we use for private.
8520   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8521       !Subtarget->hasMultiDwordFlatScratchAddressing())
8522     AS = MFI->hasFlatScratchInit() ?
8523          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8524 
8525   unsigned NumElements = VT.getVectorNumElements();
8526   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8527       AS == AMDGPUAS::FLAT_ADDRESS) {
8528     if (NumElements > 4)
8529       return SplitVectorStore(Op, DAG);
8530     // v3 stores not supported on SI.
8531     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8532       return SplitVectorStore(Op, DAG);
8533 
8534     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8535                                         VT, *Store->getMemOperand()))
8536       return expandUnalignedStore(Store, DAG);
8537 
8538     return SDValue();
8539   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8540     switch (Subtarget->getMaxPrivateElementSize()) {
8541     case 4:
8542       return scalarizeVectorStore(Store, DAG);
8543     case 8:
8544       if (NumElements > 2)
8545         return SplitVectorStore(Op, DAG);
8546       return SDValue();
8547     case 16:
8548       if (NumElements > 4 ||
8549           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8550         return SplitVectorStore(Op, DAG);
8551       return SDValue();
8552     default:
8553       llvm_unreachable("unsupported private_element_size");
8554     }
8555   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8556     // Use ds_write_b128 or ds_write_b96 when possible.
8557     if (Subtarget->hasDS96AndDS128() &&
8558         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8559          (VT.getStoreSize() == 12)) &&
8560         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8561                                            Store->getAlign()))
8562       return SDValue();
8563 
8564     if (NumElements > 2)
8565       return SplitVectorStore(Op, DAG);
8566 
8567     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8568     // address is negative, then the instruction is incorrectly treated as
8569     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8570     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8571     // store later in the SILoadStoreOptimizer.
8572     if (!Subtarget->hasUsableDSOffset() &&
8573         NumElements == 2 && VT.getStoreSize() == 8 &&
8574         Store->getAlignment() < 8) {
8575       return SplitVectorStore(Op, DAG);
8576     }
8577 
8578     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8579                                         VT, *Store->getMemOperand())) {
8580       if (VT.isVector())
8581         return SplitVectorStore(Op, DAG);
8582       return expandUnalignedStore(Store, DAG);
8583     }
8584 
8585     return SDValue();
8586   } else {
8587     llvm_unreachable("unhandled address space");
8588   }
8589 }
8590 
8591 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8592   SDLoc DL(Op);
8593   EVT VT = Op.getValueType();
8594   SDValue Arg = Op.getOperand(0);
8595   SDValue TrigVal;
8596 
8597   // Propagate fast-math flags so that the multiply we introduce can be folded
8598   // if Arg is already the result of a multiply by constant.
8599   auto Flags = Op->getFlags();
8600 
8601   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8602 
8603   if (Subtarget->hasTrigReducedRange()) {
8604     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8605     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8606   } else {
8607     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8608   }
8609 
8610   switch (Op.getOpcode()) {
8611   case ISD::FCOS:
8612     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8613   case ISD::FSIN:
8614     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8615   default:
8616     llvm_unreachable("Wrong trig opcode");
8617   }
8618 }
8619 
8620 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8621   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8622   assert(AtomicNode->isCompareAndSwap());
8623   unsigned AS = AtomicNode->getAddressSpace();
8624 
8625   // No custom lowering required for local address space
8626   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8627     return Op;
8628 
8629   // Non-local address space requires custom lowering for atomic compare
8630   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8631   SDLoc DL(Op);
8632   SDValue ChainIn = Op.getOperand(0);
8633   SDValue Addr = Op.getOperand(1);
8634   SDValue Old = Op.getOperand(2);
8635   SDValue New = Op.getOperand(3);
8636   EVT VT = Op.getValueType();
8637   MVT SimpleVT = VT.getSimpleVT();
8638   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8639 
8640   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8641   SDValue Ops[] = { ChainIn, Addr, NewOld };
8642 
8643   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8644                                  Ops, VT, AtomicNode->getMemOperand());
8645 }
8646 
8647 //===----------------------------------------------------------------------===//
8648 // Custom DAG optimizations
8649 //===----------------------------------------------------------------------===//
8650 
8651 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8652                                                      DAGCombinerInfo &DCI) const {
8653   EVT VT = N->getValueType(0);
8654   EVT ScalarVT = VT.getScalarType();
8655   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8656     return SDValue();
8657 
8658   SelectionDAG &DAG = DCI.DAG;
8659   SDLoc DL(N);
8660 
8661   SDValue Src = N->getOperand(0);
8662   EVT SrcVT = Src.getValueType();
8663 
8664   // TODO: We could try to match extracting the higher bytes, which would be
8665   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8666   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8667   // about in practice.
8668   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8669     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8670       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8671       DCI.AddToWorklist(Cvt.getNode());
8672 
8673       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8674       if (ScalarVT != MVT::f32) {
8675         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8676                           DAG.getTargetConstant(0, DL, MVT::i32));
8677       }
8678       return Cvt;
8679     }
8680   }
8681 
8682   return SDValue();
8683 }
8684 
8685 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8686 
8687 // This is a variant of
8688 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8689 //
8690 // The normal DAG combiner will do this, but only if the add has one use since
8691 // that would increase the number of instructions.
8692 //
8693 // This prevents us from seeing a constant offset that can be folded into a
8694 // memory instruction's addressing mode. If we know the resulting add offset of
8695 // a pointer can be folded into an addressing offset, we can replace the pointer
8696 // operand with the add of new constant offset. This eliminates one of the uses,
8697 // and may allow the remaining use to also be simplified.
8698 //
8699 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8700                                                unsigned AddrSpace,
8701                                                EVT MemVT,
8702                                                DAGCombinerInfo &DCI) const {
8703   SDValue N0 = N->getOperand(0);
8704   SDValue N1 = N->getOperand(1);
8705 
8706   // We only do this to handle cases where it's profitable when there are
8707   // multiple uses of the add, so defer to the standard combine.
8708   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8709       N0->hasOneUse())
8710     return SDValue();
8711 
8712   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8713   if (!CN1)
8714     return SDValue();
8715 
8716   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8717   if (!CAdd)
8718     return SDValue();
8719 
8720   // If the resulting offset is too large, we can't fold it into the addressing
8721   // mode offset.
8722   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8723   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8724 
8725   AddrMode AM;
8726   AM.HasBaseReg = true;
8727   AM.BaseOffs = Offset.getSExtValue();
8728   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8729     return SDValue();
8730 
8731   SelectionDAG &DAG = DCI.DAG;
8732   SDLoc SL(N);
8733   EVT VT = N->getValueType(0);
8734 
8735   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8736   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8737 
8738   SDNodeFlags Flags;
8739   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8740                           (N0.getOpcode() == ISD::OR ||
8741                            N0->getFlags().hasNoUnsignedWrap()));
8742 
8743   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8744 }
8745 
8746 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8747 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8748 /// specific intrinsic, but they all place the pointer operand first.
8749 static unsigned getBasePtrIndex(const MemSDNode *N) {
8750   switch (N->getOpcode()) {
8751   case ISD::STORE:
8752   case ISD::INTRINSIC_W_CHAIN:
8753   case ISD::INTRINSIC_VOID:
8754     return 2;
8755   default:
8756     return 1;
8757   }
8758 }
8759 
8760 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8761                                                   DAGCombinerInfo &DCI) const {
8762   SelectionDAG &DAG = DCI.DAG;
8763   SDLoc SL(N);
8764 
8765   unsigned PtrIdx = getBasePtrIndex(N);
8766   SDValue Ptr = N->getOperand(PtrIdx);
8767 
8768   // TODO: We could also do this for multiplies.
8769   if (Ptr.getOpcode() == ISD::SHL) {
8770     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8771                                           N->getMemoryVT(), DCI);
8772     if (NewPtr) {
8773       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8774 
8775       NewOps[PtrIdx] = NewPtr;
8776       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8777     }
8778   }
8779 
8780   return SDValue();
8781 }
8782 
8783 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8784   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8785          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8786          (Opc == ISD::XOR && Val == 0);
8787 }
8788 
8789 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8790 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8791 // integer combine opportunities since most 64-bit operations are decomposed
8792 // this way.  TODO: We won't want this for SALU especially if it is an inline
8793 // immediate.
8794 SDValue SITargetLowering::splitBinaryBitConstantOp(
8795   DAGCombinerInfo &DCI,
8796   const SDLoc &SL,
8797   unsigned Opc, SDValue LHS,
8798   const ConstantSDNode *CRHS) const {
8799   uint64_t Val = CRHS->getZExtValue();
8800   uint32_t ValLo = Lo_32(Val);
8801   uint32_t ValHi = Hi_32(Val);
8802   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8803 
8804     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8805          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8806         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8807     // If we need to materialize a 64-bit immediate, it will be split up later
8808     // anyway. Avoid creating the harder to understand 64-bit immediate
8809     // materialization.
8810     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8811   }
8812 
8813   return SDValue();
8814 }
8815 
8816 // Returns true if argument is a boolean value which is not serialized into
8817 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8818 static bool isBoolSGPR(SDValue V) {
8819   if (V.getValueType() != MVT::i1)
8820     return false;
8821   switch (V.getOpcode()) {
8822   default: break;
8823   case ISD::SETCC:
8824   case ISD::AND:
8825   case ISD::OR:
8826   case ISD::XOR:
8827   case AMDGPUISD::FP_CLASS:
8828     return true;
8829   }
8830   return false;
8831 }
8832 
8833 // If a constant has all zeroes or all ones within each byte return it.
8834 // Otherwise return 0.
8835 static uint32_t getConstantPermuteMask(uint32_t C) {
8836   // 0xff for any zero byte in the mask
8837   uint32_t ZeroByteMask = 0;
8838   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8839   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8840   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8841   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8842   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8843   if ((NonZeroByteMask & C) != NonZeroByteMask)
8844     return 0; // Partial bytes selected.
8845   return C;
8846 }
8847 
8848 // Check if a node selects whole bytes from its operand 0 starting at a byte
8849 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8850 // or -1 if not succeeded.
8851 // Note byte select encoding:
8852 // value 0-3 selects corresponding source byte;
8853 // value 0xc selects zero;
8854 // value 0xff selects 0xff.
8855 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8856   assert(V.getValueSizeInBits() == 32);
8857 
8858   if (V.getNumOperands() != 2)
8859     return ~0;
8860 
8861   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8862   if (!N1)
8863     return ~0;
8864 
8865   uint32_t C = N1->getZExtValue();
8866 
8867   switch (V.getOpcode()) {
8868   default:
8869     break;
8870   case ISD::AND:
8871     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8872       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8873     }
8874     break;
8875 
8876   case ISD::OR:
8877     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8878       return (0x03020100 & ~ConstMask) | ConstMask;
8879     }
8880     break;
8881 
8882   case ISD::SHL:
8883     if (C % 8)
8884       return ~0;
8885 
8886     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8887 
8888   case ISD::SRL:
8889     if (C % 8)
8890       return ~0;
8891 
8892     return uint32_t(0x0c0c0c0c03020100ull >> C);
8893   }
8894 
8895   return ~0;
8896 }
8897 
8898 SDValue SITargetLowering::performAndCombine(SDNode *N,
8899                                             DAGCombinerInfo &DCI) const {
8900   if (DCI.isBeforeLegalize())
8901     return SDValue();
8902 
8903   SelectionDAG &DAG = DCI.DAG;
8904   EVT VT = N->getValueType(0);
8905   SDValue LHS = N->getOperand(0);
8906   SDValue RHS = N->getOperand(1);
8907 
8908 
8909   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8910   if (VT == MVT::i64 && CRHS) {
8911     if (SDValue Split
8912         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8913       return Split;
8914   }
8915 
8916   if (CRHS && VT == MVT::i32) {
8917     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8918     // nb = number of trailing zeroes in mask
8919     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8920     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8921     uint64_t Mask = CRHS->getZExtValue();
8922     unsigned Bits = countPopulation(Mask);
8923     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8924         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8925       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8926         unsigned Shift = CShift->getZExtValue();
8927         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8928         unsigned Offset = NB + Shift;
8929         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8930           SDLoc SL(N);
8931           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8932                                     LHS->getOperand(0),
8933                                     DAG.getConstant(Offset, SL, MVT::i32),
8934                                     DAG.getConstant(Bits, SL, MVT::i32));
8935           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8936           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8937                                     DAG.getValueType(NarrowVT));
8938           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8939                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8940           return Shl;
8941         }
8942       }
8943     }
8944 
8945     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8946     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8947         isa<ConstantSDNode>(LHS.getOperand(2))) {
8948       uint32_t Sel = getConstantPermuteMask(Mask);
8949       if (!Sel)
8950         return SDValue();
8951 
8952       // Select 0xc for all zero bytes
8953       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8954       SDLoc DL(N);
8955       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8956                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8957     }
8958   }
8959 
8960   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8961   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8962   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8963     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8964     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8965 
8966     SDValue X = LHS.getOperand(0);
8967     SDValue Y = RHS.getOperand(0);
8968     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8969       return SDValue();
8970 
8971     if (LCC == ISD::SETO) {
8972       if (X != LHS.getOperand(1))
8973         return SDValue();
8974 
8975       if (RCC == ISD::SETUNE) {
8976         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8977         if (!C1 || !C1->isInfinity() || C1->isNegative())
8978           return SDValue();
8979 
8980         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8981                               SIInstrFlags::N_SUBNORMAL |
8982                               SIInstrFlags::N_ZERO |
8983                               SIInstrFlags::P_ZERO |
8984                               SIInstrFlags::P_SUBNORMAL |
8985                               SIInstrFlags::P_NORMAL;
8986 
8987         static_assert(((~(SIInstrFlags::S_NAN |
8988                           SIInstrFlags::Q_NAN |
8989                           SIInstrFlags::N_INFINITY |
8990                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8991                       "mask not equal");
8992 
8993         SDLoc DL(N);
8994         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8995                            X, DAG.getConstant(Mask, DL, MVT::i32));
8996       }
8997     }
8998   }
8999 
9000   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9001     std::swap(LHS, RHS);
9002 
9003   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9004       RHS.hasOneUse()) {
9005     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9006     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9007     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9008     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9009     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9010         (RHS.getOperand(0) == LHS.getOperand(0) &&
9011          LHS.getOperand(0) == LHS.getOperand(1))) {
9012       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9013       unsigned NewMask = LCC == ISD::SETO ?
9014         Mask->getZExtValue() & ~OrdMask :
9015         Mask->getZExtValue() & OrdMask;
9016 
9017       SDLoc DL(N);
9018       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9019                          DAG.getConstant(NewMask, DL, MVT::i32));
9020     }
9021   }
9022 
9023   if (VT == MVT::i32 &&
9024       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9025     // and x, (sext cc from i1) => select cc, x, 0
9026     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9027       std::swap(LHS, RHS);
9028     if (isBoolSGPR(RHS.getOperand(0)))
9029       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9030                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9031   }
9032 
9033   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9035   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9036       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9037     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9038     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9039     if (LHSMask != ~0u && RHSMask != ~0u) {
9040       // Canonicalize the expression in an attempt to have fewer unique masks
9041       // and therefore fewer registers used to hold the masks.
9042       if (LHSMask > RHSMask) {
9043         std::swap(LHSMask, RHSMask);
9044         std::swap(LHS, RHS);
9045       }
9046 
9047       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9048       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9049       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9050       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9051 
9052       // Check of we need to combine values from two sources within a byte.
9053       if (!(LHSUsedLanes & RHSUsedLanes) &&
9054           // If we select high and lower word keep it for SDWA.
9055           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9056           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9057         // Each byte in each mask is either selector mask 0-3, or has higher
9058         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9059         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9060         // mask which is not 0xff wins. By anding both masks we have a correct
9061         // result except that 0x0c shall be corrected to give 0x0c only.
9062         uint32_t Mask = LHSMask & RHSMask;
9063         for (unsigned I = 0; I < 32; I += 8) {
9064           uint32_t ByteSel = 0xff << I;
9065           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9066             Mask &= (0x0c << I) & 0xffffffff;
9067         }
9068 
9069         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9070         // or 0x0c.
9071         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9072         SDLoc DL(N);
9073 
9074         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9075                            LHS.getOperand(0), RHS.getOperand(0),
9076                            DAG.getConstant(Sel, DL, MVT::i32));
9077       }
9078     }
9079   }
9080 
9081   return SDValue();
9082 }
9083 
9084 SDValue SITargetLowering::performOrCombine(SDNode *N,
9085                                            DAGCombinerInfo &DCI) const {
9086   SelectionDAG &DAG = DCI.DAG;
9087   SDValue LHS = N->getOperand(0);
9088   SDValue RHS = N->getOperand(1);
9089 
9090   EVT VT = N->getValueType(0);
9091   if (VT == MVT::i1) {
9092     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9093     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9094         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9095       SDValue Src = LHS.getOperand(0);
9096       if (Src != RHS.getOperand(0))
9097         return SDValue();
9098 
9099       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9100       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9101       if (!CLHS || !CRHS)
9102         return SDValue();
9103 
9104       // Only 10 bits are used.
9105       static const uint32_t MaxMask = 0x3ff;
9106 
9107       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9108       SDLoc DL(N);
9109       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9110                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9111     }
9112 
9113     return SDValue();
9114   }
9115 
9116   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9117   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9118       LHS.getOpcode() == AMDGPUISD::PERM &&
9119       isa<ConstantSDNode>(LHS.getOperand(2))) {
9120     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9121     if (!Sel)
9122       return SDValue();
9123 
9124     Sel |= LHS.getConstantOperandVal(2);
9125     SDLoc DL(N);
9126     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9127                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9128   }
9129 
9130   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9131   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9132   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9133       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9134     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9135     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9136     if (LHSMask != ~0u && RHSMask != ~0u) {
9137       // Canonicalize the expression in an attempt to have fewer unique masks
9138       // and therefore fewer registers used to hold the masks.
9139       if (LHSMask > RHSMask) {
9140         std::swap(LHSMask, RHSMask);
9141         std::swap(LHS, RHS);
9142       }
9143 
9144       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9145       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9146       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9147       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9148 
9149       // Check of we need to combine values from two sources within a byte.
9150       if (!(LHSUsedLanes & RHSUsedLanes) &&
9151           // If we select high and lower word keep it for SDWA.
9152           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9153           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9154         // Kill zero bytes selected by other mask. Zero value is 0xc.
9155         LHSMask &= ~RHSUsedLanes;
9156         RHSMask &= ~LHSUsedLanes;
9157         // Add 4 to each active LHS lane
9158         LHSMask |= LHSUsedLanes & 0x04040404;
9159         // Combine masks
9160         uint32_t Sel = LHSMask | RHSMask;
9161         SDLoc DL(N);
9162 
9163         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9164                            LHS.getOperand(0), RHS.getOperand(0),
9165                            DAG.getConstant(Sel, DL, MVT::i32));
9166       }
9167     }
9168   }
9169 
9170   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9171     return SDValue();
9172 
9173   // TODO: This could be a generic combine with a predicate for extracting the
9174   // high half of an integer being free.
9175 
9176   // (or i64:x, (zero_extend i32:y)) ->
9177   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9178   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9179       RHS.getOpcode() != ISD::ZERO_EXTEND)
9180     std::swap(LHS, RHS);
9181 
9182   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9183     SDValue ExtSrc = RHS.getOperand(0);
9184     EVT SrcVT = ExtSrc.getValueType();
9185     if (SrcVT == MVT::i32) {
9186       SDLoc SL(N);
9187       SDValue LowLHS, HiBits;
9188       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9189       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9190 
9191       DCI.AddToWorklist(LowOr.getNode());
9192       DCI.AddToWorklist(HiBits.getNode());
9193 
9194       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9195                                 LowOr, HiBits);
9196       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9197     }
9198   }
9199 
9200   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9201   if (CRHS) {
9202     if (SDValue Split
9203           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9204       return Split;
9205   }
9206 
9207   return SDValue();
9208 }
9209 
9210 SDValue SITargetLowering::performXorCombine(SDNode *N,
9211                                             DAGCombinerInfo &DCI) const {
9212   EVT VT = N->getValueType(0);
9213   if (VT != MVT::i64)
9214     return SDValue();
9215 
9216   SDValue LHS = N->getOperand(0);
9217   SDValue RHS = N->getOperand(1);
9218 
9219   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9220   if (CRHS) {
9221     if (SDValue Split
9222           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9223       return Split;
9224   }
9225 
9226   return SDValue();
9227 }
9228 
9229 // Instructions that will be lowered with a final instruction that zeros the
9230 // high result bits.
9231 // XXX - probably only need to list legal operations.
9232 static bool fp16SrcZerosHighBits(unsigned Opc) {
9233   switch (Opc) {
9234   case ISD::FADD:
9235   case ISD::FSUB:
9236   case ISD::FMUL:
9237   case ISD::FDIV:
9238   case ISD::FREM:
9239   case ISD::FMA:
9240   case ISD::FMAD:
9241   case ISD::FCANONICALIZE:
9242   case ISD::FP_ROUND:
9243   case ISD::UINT_TO_FP:
9244   case ISD::SINT_TO_FP:
9245   case ISD::FABS:
9246     // Fabs is lowered to a bit operation, but it's an and which will clear the
9247     // high bits anyway.
9248   case ISD::FSQRT:
9249   case ISD::FSIN:
9250   case ISD::FCOS:
9251   case ISD::FPOWI:
9252   case ISD::FPOW:
9253   case ISD::FLOG:
9254   case ISD::FLOG2:
9255   case ISD::FLOG10:
9256   case ISD::FEXP:
9257   case ISD::FEXP2:
9258   case ISD::FCEIL:
9259   case ISD::FTRUNC:
9260   case ISD::FRINT:
9261   case ISD::FNEARBYINT:
9262   case ISD::FROUND:
9263   case ISD::FFLOOR:
9264   case ISD::FMINNUM:
9265   case ISD::FMAXNUM:
9266   case AMDGPUISD::FRACT:
9267   case AMDGPUISD::CLAMP:
9268   case AMDGPUISD::COS_HW:
9269   case AMDGPUISD::SIN_HW:
9270   case AMDGPUISD::FMIN3:
9271   case AMDGPUISD::FMAX3:
9272   case AMDGPUISD::FMED3:
9273   case AMDGPUISD::FMAD_FTZ:
9274   case AMDGPUISD::RCP:
9275   case AMDGPUISD::RSQ:
9276   case AMDGPUISD::RCP_IFLAG:
9277   case AMDGPUISD::LDEXP:
9278     return true;
9279   default:
9280     // fcopysign, select and others may be lowered to 32-bit bit operations
9281     // which don't zero the high bits.
9282     return false;
9283   }
9284 }
9285 
9286 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9287                                                    DAGCombinerInfo &DCI) const {
9288   if (!Subtarget->has16BitInsts() ||
9289       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9290     return SDValue();
9291 
9292   EVT VT = N->getValueType(0);
9293   if (VT != MVT::i32)
9294     return SDValue();
9295 
9296   SDValue Src = N->getOperand(0);
9297   if (Src.getValueType() != MVT::i16)
9298     return SDValue();
9299 
9300   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9301   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9302   if (Src.getOpcode() == ISD::BITCAST) {
9303     SDValue BCSrc = Src.getOperand(0);
9304     if (BCSrc.getValueType() == MVT::f16 &&
9305         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9306       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9307   }
9308 
9309   return SDValue();
9310 }
9311 
9312 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9313                                                         DAGCombinerInfo &DCI)
9314                                                         const {
9315   SDValue Src = N->getOperand(0);
9316   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9317 
9318   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9319       VTSign->getVT() == MVT::i8) ||
9320       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9321       VTSign->getVT() == MVT::i16)) &&
9322       Src.hasOneUse()) {
9323     auto *M = cast<MemSDNode>(Src);
9324     SDValue Ops[] = {
9325       Src.getOperand(0), // Chain
9326       Src.getOperand(1), // rsrc
9327       Src.getOperand(2), // vindex
9328       Src.getOperand(3), // voffset
9329       Src.getOperand(4), // soffset
9330       Src.getOperand(5), // offset
9331       Src.getOperand(6),
9332       Src.getOperand(7)
9333     };
9334     // replace with BUFFER_LOAD_BYTE/SHORT
9335     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9336                                          Src.getOperand(0).getValueType());
9337     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9338                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9339     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9340                                                           ResList,
9341                                                           Ops, M->getMemoryVT(),
9342                                                           M->getMemOperand());
9343     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9344                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9345   }
9346   return SDValue();
9347 }
9348 
9349 SDValue SITargetLowering::performClassCombine(SDNode *N,
9350                                               DAGCombinerInfo &DCI) const {
9351   SelectionDAG &DAG = DCI.DAG;
9352   SDValue Mask = N->getOperand(1);
9353 
9354   // fp_class x, 0 -> false
9355   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9356     if (CMask->isNullValue())
9357       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9358   }
9359 
9360   if (N->getOperand(0).isUndef())
9361     return DAG.getUNDEF(MVT::i1);
9362 
9363   return SDValue();
9364 }
9365 
9366 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9367                                             DAGCombinerInfo &DCI) const {
9368   EVT VT = N->getValueType(0);
9369   SDValue N0 = N->getOperand(0);
9370 
9371   if (N0.isUndef())
9372     return N0;
9373 
9374   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9375                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9376     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9377                            N->getFlags());
9378   }
9379 
9380   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9381     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9382                            N0.getOperand(0), N->getFlags());
9383   }
9384 
9385   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9386 }
9387 
9388 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9389                                        unsigned MaxDepth) const {
9390   unsigned Opcode = Op.getOpcode();
9391   if (Opcode == ISD::FCANONICALIZE)
9392     return true;
9393 
9394   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9395     auto F = CFP->getValueAPF();
9396     if (F.isNaN() && F.isSignaling())
9397       return false;
9398     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9399   }
9400 
9401   // If source is a result of another standard FP operation it is already in
9402   // canonical form.
9403   if (MaxDepth == 0)
9404     return false;
9405 
9406   switch (Opcode) {
9407   // These will flush denorms if required.
9408   case ISD::FADD:
9409   case ISD::FSUB:
9410   case ISD::FMUL:
9411   case ISD::FCEIL:
9412   case ISD::FFLOOR:
9413   case ISD::FMA:
9414   case ISD::FMAD:
9415   case ISD::FSQRT:
9416   case ISD::FDIV:
9417   case ISD::FREM:
9418   case ISD::FP_ROUND:
9419   case ISD::FP_EXTEND:
9420   case AMDGPUISD::FMUL_LEGACY:
9421   case AMDGPUISD::FMAD_FTZ:
9422   case AMDGPUISD::RCP:
9423   case AMDGPUISD::RSQ:
9424   case AMDGPUISD::RSQ_CLAMP:
9425   case AMDGPUISD::RCP_LEGACY:
9426   case AMDGPUISD::RCP_IFLAG:
9427   case AMDGPUISD::DIV_SCALE:
9428   case AMDGPUISD::DIV_FMAS:
9429   case AMDGPUISD::DIV_FIXUP:
9430   case AMDGPUISD::FRACT:
9431   case AMDGPUISD::LDEXP:
9432   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9433   case AMDGPUISD::CVT_F32_UBYTE0:
9434   case AMDGPUISD::CVT_F32_UBYTE1:
9435   case AMDGPUISD::CVT_F32_UBYTE2:
9436   case AMDGPUISD::CVT_F32_UBYTE3:
9437     return true;
9438 
9439   // It can/will be lowered or combined as a bit operation.
9440   // Need to check their input recursively to handle.
9441   case ISD::FNEG:
9442   case ISD::FABS:
9443   case ISD::FCOPYSIGN:
9444     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9445 
9446   case ISD::FSIN:
9447   case ISD::FCOS:
9448   case ISD::FSINCOS:
9449     return Op.getValueType().getScalarType() != MVT::f16;
9450 
9451   case ISD::FMINNUM:
9452   case ISD::FMAXNUM:
9453   case ISD::FMINNUM_IEEE:
9454   case ISD::FMAXNUM_IEEE:
9455   case AMDGPUISD::CLAMP:
9456   case AMDGPUISD::FMED3:
9457   case AMDGPUISD::FMAX3:
9458   case AMDGPUISD::FMIN3: {
9459     // FIXME: Shouldn't treat the generic operations different based these.
9460     // However, we aren't really required to flush the result from
9461     // minnum/maxnum..
9462 
9463     // snans will be quieted, so we only need to worry about denormals.
9464     if (Subtarget->supportsMinMaxDenormModes() ||
9465         denormalsEnabledForType(DAG, Op.getValueType()))
9466       return true;
9467 
9468     // Flushing may be required.
9469     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9470     // targets need to check their input recursively.
9471 
9472     // FIXME: Does this apply with clamp? It's implemented with max.
9473     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9474       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9475         return false;
9476     }
9477 
9478     return true;
9479   }
9480   case ISD::SELECT: {
9481     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9482            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9483   }
9484   case ISD::BUILD_VECTOR: {
9485     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9486       SDValue SrcOp = Op.getOperand(i);
9487       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9488         return false;
9489     }
9490 
9491     return true;
9492   }
9493   case ISD::EXTRACT_VECTOR_ELT:
9494   case ISD::EXTRACT_SUBVECTOR: {
9495     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9496   }
9497   case ISD::INSERT_VECTOR_ELT: {
9498     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9499            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9500   }
9501   case ISD::UNDEF:
9502     // Could be anything.
9503     return false;
9504 
9505   case ISD::BITCAST: {
9506     // Hack round the mess we make when legalizing extract_vector_elt
9507     SDValue Src = Op.getOperand(0);
9508     if (Src.getValueType() == MVT::i16 &&
9509         Src.getOpcode() == ISD::TRUNCATE) {
9510       SDValue TruncSrc = Src.getOperand(0);
9511       if (TruncSrc.getValueType() == MVT::i32 &&
9512           TruncSrc.getOpcode() == ISD::BITCAST &&
9513           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9514         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9515       }
9516     }
9517 
9518     return false;
9519   }
9520   case ISD::INTRINSIC_WO_CHAIN: {
9521     unsigned IntrinsicID
9522       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9523     // TODO: Handle more intrinsics
9524     switch (IntrinsicID) {
9525     case Intrinsic::amdgcn_cvt_pkrtz:
9526     case Intrinsic::amdgcn_cubeid:
9527     case Intrinsic::amdgcn_frexp_mant:
9528     case Intrinsic::amdgcn_fdot2:
9529     case Intrinsic::amdgcn_rcp:
9530     case Intrinsic::amdgcn_rsq:
9531     case Intrinsic::amdgcn_rsq_clamp:
9532     case Intrinsic::amdgcn_rcp_legacy:
9533     case Intrinsic::amdgcn_rsq_legacy:
9534     case Intrinsic::amdgcn_trig_preop:
9535       return true;
9536     default:
9537       break;
9538     }
9539 
9540     LLVM_FALLTHROUGH;
9541   }
9542   default:
9543     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9544            DAG.isKnownNeverSNaN(Op);
9545   }
9546 
9547   llvm_unreachable("invalid operation");
9548 }
9549 
9550 // Constant fold canonicalize.
9551 SDValue SITargetLowering::getCanonicalConstantFP(
9552   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9553   // Flush denormals to 0 if not enabled.
9554   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9555     return DAG.getConstantFP(0.0, SL, VT);
9556 
9557   if (C.isNaN()) {
9558     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9559     if (C.isSignaling()) {
9560       // Quiet a signaling NaN.
9561       // FIXME: Is this supposed to preserve payload bits?
9562       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9563     }
9564 
9565     // Make sure it is the canonical NaN bitpattern.
9566     //
9567     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9568     // immediate?
9569     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9570       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9571   }
9572 
9573   // Already canonical.
9574   return DAG.getConstantFP(C, SL, VT);
9575 }
9576 
9577 static bool vectorEltWillFoldAway(SDValue Op) {
9578   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9579 }
9580 
9581 SDValue SITargetLowering::performFCanonicalizeCombine(
9582   SDNode *N,
9583   DAGCombinerInfo &DCI) const {
9584   SelectionDAG &DAG = DCI.DAG;
9585   SDValue N0 = N->getOperand(0);
9586   EVT VT = N->getValueType(0);
9587 
9588   // fcanonicalize undef -> qnan
9589   if (N0.isUndef()) {
9590     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9591     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9592   }
9593 
9594   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9595     EVT VT = N->getValueType(0);
9596     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9597   }
9598 
9599   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9600   //                                                   (fcanonicalize k)
9601   //
9602   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9603 
9604   // TODO: This could be better with wider vectors that will be split to v2f16,
9605   // and to consider uses since there aren't that many packed operations.
9606   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9607       isTypeLegal(MVT::v2f16)) {
9608     SDLoc SL(N);
9609     SDValue NewElts[2];
9610     SDValue Lo = N0.getOperand(0);
9611     SDValue Hi = N0.getOperand(1);
9612     EVT EltVT = Lo.getValueType();
9613 
9614     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9615       for (unsigned I = 0; I != 2; ++I) {
9616         SDValue Op = N0.getOperand(I);
9617         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9618           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9619                                               CFP->getValueAPF());
9620         } else if (Op.isUndef()) {
9621           // Handled below based on what the other operand is.
9622           NewElts[I] = Op;
9623         } else {
9624           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9625         }
9626       }
9627 
9628       // If one half is undef, and one is constant, perfer a splat vector rather
9629       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9630       // cheaper to use and may be free with a packed operation.
9631       if (NewElts[0].isUndef()) {
9632         if (isa<ConstantFPSDNode>(NewElts[1]))
9633           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9634             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9635       }
9636 
9637       if (NewElts[1].isUndef()) {
9638         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9639           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9640       }
9641 
9642       return DAG.getBuildVector(VT, SL, NewElts);
9643     }
9644   }
9645 
9646   unsigned SrcOpc = N0.getOpcode();
9647 
9648   // If it's free to do so, push canonicalizes further up the source, which may
9649   // find a canonical source.
9650   //
9651   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9652   // sNaNs.
9653   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9654     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9655     if (CRHS && N0.hasOneUse()) {
9656       SDLoc SL(N);
9657       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9658                                    N0.getOperand(0));
9659       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9660       DCI.AddToWorklist(Canon0.getNode());
9661 
9662       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9663     }
9664   }
9665 
9666   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9667 }
9668 
9669 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9670   switch (Opc) {
9671   case ISD::FMAXNUM:
9672   case ISD::FMAXNUM_IEEE:
9673     return AMDGPUISD::FMAX3;
9674   case ISD::SMAX:
9675     return AMDGPUISD::SMAX3;
9676   case ISD::UMAX:
9677     return AMDGPUISD::UMAX3;
9678   case ISD::FMINNUM:
9679   case ISD::FMINNUM_IEEE:
9680     return AMDGPUISD::FMIN3;
9681   case ISD::SMIN:
9682     return AMDGPUISD::SMIN3;
9683   case ISD::UMIN:
9684     return AMDGPUISD::UMIN3;
9685   default:
9686     llvm_unreachable("Not a min/max opcode");
9687   }
9688 }
9689 
9690 SDValue SITargetLowering::performIntMed3ImmCombine(
9691   SelectionDAG &DAG, const SDLoc &SL,
9692   SDValue Op0, SDValue Op1, bool Signed) const {
9693   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9694   if (!K1)
9695     return SDValue();
9696 
9697   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9698   if (!K0)
9699     return SDValue();
9700 
9701   if (Signed) {
9702     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9703       return SDValue();
9704   } else {
9705     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9706       return SDValue();
9707   }
9708 
9709   EVT VT = K0->getValueType(0);
9710   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9711   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9712     return DAG.getNode(Med3Opc, SL, VT,
9713                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9714   }
9715 
9716   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9717   MVT NVT = MVT::i32;
9718   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9719 
9720   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9721   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9722   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9723 
9724   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9725   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9726 }
9727 
9728 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9729   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9730     return C;
9731 
9732   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9733     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9734       return C;
9735   }
9736 
9737   return nullptr;
9738 }
9739 
9740 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9741                                                   const SDLoc &SL,
9742                                                   SDValue Op0,
9743                                                   SDValue Op1) const {
9744   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9745   if (!K1)
9746     return SDValue();
9747 
9748   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9749   if (!K0)
9750     return SDValue();
9751 
9752   // Ordered >= (although NaN inputs should have folded away by now).
9753   if (K0->getValueAPF() > K1->getValueAPF())
9754     return SDValue();
9755 
9756   const MachineFunction &MF = DAG.getMachineFunction();
9757   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9758 
9759   // TODO: Check IEEE bit enabled?
9760   EVT VT = Op0.getValueType();
9761   if (Info->getMode().DX10Clamp) {
9762     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9763     // hardware fmed3 behavior converting to a min.
9764     // FIXME: Should this be allowing -0.0?
9765     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9766       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9767   }
9768 
9769   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9770   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9771     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9772     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9773     // then give the other result, which is different from med3 with a NaN
9774     // input.
9775     SDValue Var = Op0.getOperand(0);
9776     if (!DAG.isKnownNeverSNaN(Var))
9777       return SDValue();
9778 
9779     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9780 
9781     if ((!K0->hasOneUse() ||
9782          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9783         (!K1->hasOneUse() ||
9784          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9785       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9786                          Var, SDValue(K0, 0), SDValue(K1, 0));
9787     }
9788   }
9789 
9790   return SDValue();
9791 }
9792 
9793 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9794                                                DAGCombinerInfo &DCI) const {
9795   SelectionDAG &DAG = DCI.DAG;
9796 
9797   EVT VT = N->getValueType(0);
9798   unsigned Opc = N->getOpcode();
9799   SDValue Op0 = N->getOperand(0);
9800   SDValue Op1 = N->getOperand(1);
9801 
9802   // Only do this if the inner op has one use since this will just increases
9803   // register pressure for no benefit.
9804 
9805   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9806       !VT.isVector() &&
9807       (VT == MVT::i32 || VT == MVT::f32 ||
9808        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9809     // max(max(a, b), c) -> max3(a, b, c)
9810     // min(min(a, b), c) -> min3(a, b, c)
9811     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9812       SDLoc DL(N);
9813       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9814                          DL,
9815                          N->getValueType(0),
9816                          Op0.getOperand(0),
9817                          Op0.getOperand(1),
9818                          Op1);
9819     }
9820 
9821     // Try commuted.
9822     // max(a, max(b, c)) -> max3(a, b, c)
9823     // min(a, min(b, c)) -> min3(a, b, c)
9824     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9825       SDLoc DL(N);
9826       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9827                          DL,
9828                          N->getValueType(0),
9829                          Op0,
9830                          Op1.getOperand(0),
9831                          Op1.getOperand(1));
9832     }
9833   }
9834 
9835   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9836   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9837     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9838       return Med3;
9839   }
9840 
9841   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9842     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9843       return Med3;
9844   }
9845 
9846   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9847   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9848        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9849        (Opc == AMDGPUISD::FMIN_LEGACY &&
9850         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9851       (VT == MVT::f32 || VT == MVT::f64 ||
9852        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9853        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9854       Op0.hasOneUse()) {
9855     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9856       return Res;
9857   }
9858 
9859   return SDValue();
9860 }
9861 
9862 static bool isClampZeroToOne(SDValue A, SDValue B) {
9863   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9864     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9865       // FIXME: Should this be allowing -0.0?
9866       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9867              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9868     }
9869   }
9870 
9871   return false;
9872 }
9873 
9874 // FIXME: Should only worry about snans for version with chain.
9875 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9876                                               DAGCombinerInfo &DCI) const {
9877   EVT VT = N->getValueType(0);
9878   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9879   // NaNs. With a NaN input, the order of the operands may change the result.
9880 
9881   SelectionDAG &DAG = DCI.DAG;
9882   SDLoc SL(N);
9883 
9884   SDValue Src0 = N->getOperand(0);
9885   SDValue Src1 = N->getOperand(1);
9886   SDValue Src2 = N->getOperand(2);
9887 
9888   if (isClampZeroToOne(Src0, Src1)) {
9889     // const_a, const_b, x -> clamp is safe in all cases including signaling
9890     // nans.
9891     // FIXME: Should this be allowing -0.0?
9892     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9893   }
9894 
9895   const MachineFunction &MF = DAG.getMachineFunction();
9896   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9897 
9898   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9899   // handling no dx10-clamp?
9900   if (Info->getMode().DX10Clamp) {
9901     // If NaNs is clamped to 0, we are free to reorder the inputs.
9902 
9903     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9904       std::swap(Src0, Src1);
9905 
9906     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9907       std::swap(Src1, Src2);
9908 
9909     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9910       std::swap(Src0, Src1);
9911 
9912     if (isClampZeroToOne(Src1, Src2))
9913       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9914   }
9915 
9916   return SDValue();
9917 }
9918 
9919 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9920                                                  DAGCombinerInfo &DCI) const {
9921   SDValue Src0 = N->getOperand(0);
9922   SDValue Src1 = N->getOperand(1);
9923   if (Src0.isUndef() && Src1.isUndef())
9924     return DCI.DAG.getUNDEF(N->getValueType(0));
9925   return SDValue();
9926 }
9927 
9928 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9929 // expanded into a set of cmp/select instructions.
9930 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9931                                                 unsigned NumElem,
9932                                                 bool IsDivergentIdx) {
9933   if (UseDivergentRegisterIndexing)
9934     return false;
9935 
9936   unsigned VecSize = EltSize * NumElem;
9937 
9938   // Sub-dword vectors of size 2 dword or less have better implementation.
9939   if (VecSize <= 64 && EltSize < 32)
9940     return false;
9941 
9942   // Always expand the rest of sub-dword instructions, otherwise it will be
9943   // lowered via memory.
9944   if (EltSize < 32)
9945     return true;
9946 
9947   // Always do this if var-idx is divergent, otherwise it will become a loop.
9948   if (IsDivergentIdx)
9949     return true;
9950 
9951   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9952   unsigned NumInsts = NumElem /* Number of compares */ +
9953                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9954   return NumInsts <= 16;
9955 }
9956 
9957 static bool shouldExpandVectorDynExt(SDNode *N) {
9958   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9959   if (isa<ConstantSDNode>(Idx))
9960     return false;
9961 
9962   SDValue Vec = N->getOperand(0);
9963   EVT VecVT = Vec.getValueType();
9964   EVT EltVT = VecVT.getVectorElementType();
9965   unsigned EltSize = EltVT.getSizeInBits();
9966   unsigned NumElem = VecVT.getVectorNumElements();
9967 
9968   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9969                                                     Idx->isDivergent());
9970 }
9971 
9972 SDValue SITargetLowering::performExtractVectorEltCombine(
9973   SDNode *N, DAGCombinerInfo &DCI) const {
9974   SDValue Vec = N->getOperand(0);
9975   SelectionDAG &DAG = DCI.DAG;
9976 
9977   EVT VecVT = Vec.getValueType();
9978   EVT EltVT = VecVT.getVectorElementType();
9979 
9980   if ((Vec.getOpcode() == ISD::FNEG ||
9981        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9982     SDLoc SL(N);
9983     EVT EltVT = N->getValueType(0);
9984     SDValue Idx = N->getOperand(1);
9985     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9986                               Vec.getOperand(0), Idx);
9987     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9988   }
9989 
9990   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9991   //    =>
9992   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9993   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9994   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9995   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9996     SDLoc SL(N);
9997     EVT EltVT = N->getValueType(0);
9998     SDValue Idx = N->getOperand(1);
9999     unsigned Opc = Vec.getOpcode();
10000 
10001     switch(Opc) {
10002     default:
10003       break;
10004       // TODO: Support other binary operations.
10005     case ISD::FADD:
10006     case ISD::FSUB:
10007     case ISD::FMUL:
10008     case ISD::ADD:
10009     case ISD::UMIN:
10010     case ISD::UMAX:
10011     case ISD::SMIN:
10012     case ISD::SMAX:
10013     case ISD::FMAXNUM:
10014     case ISD::FMINNUM:
10015     case ISD::FMAXNUM_IEEE:
10016     case ISD::FMINNUM_IEEE: {
10017       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10018                                  Vec.getOperand(0), Idx);
10019       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10020                                  Vec.getOperand(1), Idx);
10021 
10022       DCI.AddToWorklist(Elt0.getNode());
10023       DCI.AddToWorklist(Elt1.getNode());
10024       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10025     }
10026     }
10027   }
10028 
10029   unsigned VecSize = VecVT.getSizeInBits();
10030   unsigned EltSize = EltVT.getSizeInBits();
10031 
10032   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10033   if (::shouldExpandVectorDynExt(N)) {
10034     SDLoc SL(N);
10035     SDValue Idx = N->getOperand(1);
10036     SDValue V;
10037     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10038       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10039       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10040       if (I == 0)
10041         V = Elt;
10042       else
10043         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10044     }
10045     return V;
10046   }
10047 
10048   if (!DCI.isBeforeLegalize())
10049     return SDValue();
10050 
10051   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10052   // elements. This exposes more load reduction opportunities by replacing
10053   // multiple small extract_vector_elements with a single 32-bit extract.
10054   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10055   if (isa<MemSDNode>(Vec) &&
10056       EltSize <= 16 &&
10057       EltVT.isByteSized() &&
10058       VecSize > 32 &&
10059       VecSize % 32 == 0 &&
10060       Idx) {
10061     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10062 
10063     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10064     unsigned EltIdx = BitIndex / 32;
10065     unsigned LeftoverBitIdx = BitIndex % 32;
10066     SDLoc SL(N);
10067 
10068     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10069     DCI.AddToWorklist(Cast.getNode());
10070 
10071     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10072                               DAG.getConstant(EltIdx, SL, MVT::i32));
10073     DCI.AddToWorklist(Elt.getNode());
10074     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10075                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10076     DCI.AddToWorklist(Srl.getNode());
10077 
10078     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10079     DCI.AddToWorklist(Trunc.getNode());
10080     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10081   }
10082 
10083   return SDValue();
10084 }
10085 
10086 SDValue
10087 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10088                                                 DAGCombinerInfo &DCI) const {
10089   SDValue Vec = N->getOperand(0);
10090   SDValue Idx = N->getOperand(2);
10091   EVT VecVT = Vec.getValueType();
10092   EVT EltVT = VecVT.getVectorElementType();
10093 
10094   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10095   // => BUILD_VECTOR n x select (e, const-idx)
10096   if (!::shouldExpandVectorDynExt(N))
10097     return SDValue();
10098 
10099   SelectionDAG &DAG = DCI.DAG;
10100   SDLoc SL(N);
10101   SDValue Ins = N->getOperand(1);
10102   EVT IdxVT = Idx.getValueType();
10103 
10104   SmallVector<SDValue, 16> Ops;
10105   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10106     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10107     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10108     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10109     Ops.push_back(V);
10110   }
10111 
10112   return DAG.getBuildVector(VecVT, SL, Ops);
10113 }
10114 
10115 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10116                                           const SDNode *N0,
10117                                           const SDNode *N1) const {
10118   EVT VT = N0->getValueType(0);
10119 
10120   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10121   // support denormals ever.
10122   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10123        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10124         getSubtarget()->hasMadF16())) &&
10125        isOperationLegal(ISD::FMAD, VT))
10126     return ISD::FMAD;
10127 
10128   const TargetOptions &Options = DAG.getTarget().Options;
10129   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10130        (N0->getFlags().hasAllowContract() &&
10131         N1->getFlags().hasAllowContract())) &&
10132       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10133     return ISD::FMA;
10134   }
10135 
10136   return 0;
10137 }
10138 
10139 // For a reassociatable opcode perform:
10140 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10141 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10142                                                SelectionDAG &DAG) const {
10143   EVT VT = N->getValueType(0);
10144   if (VT != MVT::i32 && VT != MVT::i64)
10145     return SDValue();
10146 
10147   unsigned Opc = N->getOpcode();
10148   SDValue Op0 = N->getOperand(0);
10149   SDValue Op1 = N->getOperand(1);
10150 
10151   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10152     return SDValue();
10153 
10154   if (Op0->isDivergent())
10155     std::swap(Op0, Op1);
10156 
10157   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10158     return SDValue();
10159 
10160   SDValue Op2 = Op1.getOperand(1);
10161   Op1 = Op1.getOperand(0);
10162   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10163     return SDValue();
10164 
10165   if (Op1->isDivergent())
10166     std::swap(Op1, Op2);
10167 
10168   // If either operand is constant this will conflict with
10169   // DAGCombiner::ReassociateOps().
10170   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10171       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10172     return SDValue();
10173 
10174   SDLoc SL(N);
10175   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10176   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10177 }
10178 
10179 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10180                            EVT VT,
10181                            SDValue N0, SDValue N1, SDValue N2,
10182                            bool Signed) {
10183   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10184   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10185   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10186   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10187 }
10188 
10189 SDValue SITargetLowering::performAddCombine(SDNode *N,
10190                                             DAGCombinerInfo &DCI) const {
10191   SelectionDAG &DAG = DCI.DAG;
10192   EVT VT = N->getValueType(0);
10193   SDLoc SL(N);
10194   SDValue LHS = N->getOperand(0);
10195   SDValue RHS = N->getOperand(1);
10196 
10197   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10198       && Subtarget->hasMad64_32() &&
10199       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10200       VT.getScalarSizeInBits() <= 64) {
10201     if (LHS.getOpcode() != ISD::MUL)
10202       std::swap(LHS, RHS);
10203 
10204     SDValue MulLHS = LHS.getOperand(0);
10205     SDValue MulRHS = LHS.getOperand(1);
10206     SDValue AddRHS = RHS;
10207 
10208     // TODO: Maybe restrict if SGPR inputs.
10209     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10210         numBitsUnsigned(MulRHS, DAG) <= 32) {
10211       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10212       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10213       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10214       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10215     }
10216 
10217     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10218       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10219       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10220       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10221       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10222     }
10223 
10224     return SDValue();
10225   }
10226 
10227   if (SDValue V = reassociateScalarOps(N, DAG)) {
10228     return V;
10229   }
10230 
10231   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10232     return SDValue();
10233 
10234   // add x, zext (setcc) => addcarry x, 0, setcc
10235   // add x, sext (setcc) => subcarry x, 0, setcc
10236   unsigned Opc = LHS.getOpcode();
10237   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10238       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10239     std::swap(RHS, LHS);
10240 
10241   Opc = RHS.getOpcode();
10242   switch (Opc) {
10243   default: break;
10244   case ISD::ZERO_EXTEND:
10245   case ISD::SIGN_EXTEND:
10246   case ISD::ANY_EXTEND: {
10247     auto Cond = RHS.getOperand(0);
10248     // If this won't be a real VOPC output, we would still need to insert an
10249     // extra instruction anyway.
10250     if (!isBoolSGPR(Cond))
10251       break;
10252     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10253     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10254     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10255     return DAG.getNode(Opc, SL, VTList, Args);
10256   }
10257   case ISD::ADDCARRY: {
10258     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10259     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10260     if (!C || C->getZExtValue() != 0) break;
10261     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10262     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10263   }
10264   }
10265   return SDValue();
10266 }
10267 
10268 SDValue SITargetLowering::performSubCombine(SDNode *N,
10269                                             DAGCombinerInfo &DCI) const {
10270   SelectionDAG &DAG = DCI.DAG;
10271   EVT VT = N->getValueType(0);
10272 
10273   if (VT != MVT::i32)
10274     return SDValue();
10275 
10276   SDLoc SL(N);
10277   SDValue LHS = N->getOperand(0);
10278   SDValue RHS = N->getOperand(1);
10279 
10280   // sub x, zext (setcc) => subcarry x, 0, setcc
10281   // sub x, sext (setcc) => addcarry x, 0, setcc
10282   unsigned Opc = RHS.getOpcode();
10283   switch (Opc) {
10284   default: break;
10285   case ISD::ZERO_EXTEND:
10286   case ISD::SIGN_EXTEND:
10287   case ISD::ANY_EXTEND: {
10288     auto Cond = RHS.getOperand(0);
10289     // If this won't be a real VOPC output, we would still need to insert an
10290     // extra instruction anyway.
10291     if (!isBoolSGPR(Cond))
10292       break;
10293     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10294     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10295     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10296     return DAG.getNode(Opc, SL, VTList, Args);
10297   }
10298   }
10299 
10300   if (LHS.getOpcode() == ISD::SUBCARRY) {
10301     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10302     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10303     if (!C || !C->isNullValue())
10304       return SDValue();
10305     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10306     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10307   }
10308   return SDValue();
10309 }
10310 
10311 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10312   DAGCombinerInfo &DCI) const {
10313 
10314   if (N->getValueType(0) != MVT::i32)
10315     return SDValue();
10316 
10317   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10318   if (!C || C->getZExtValue() != 0)
10319     return SDValue();
10320 
10321   SelectionDAG &DAG = DCI.DAG;
10322   SDValue LHS = N->getOperand(0);
10323 
10324   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10325   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10326   unsigned LHSOpc = LHS.getOpcode();
10327   unsigned Opc = N->getOpcode();
10328   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10329       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10330     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10331     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10332   }
10333   return SDValue();
10334 }
10335 
10336 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10337                                              DAGCombinerInfo &DCI) const {
10338   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10339     return SDValue();
10340 
10341   SelectionDAG &DAG = DCI.DAG;
10342   EVT VT = N->getValueType(0);
10343 
10344   SDLoc SL(N);
10345   SDValue LHS = N->getOperand(0);
10346   SDValue RHS = N->getOperand(1);
10347 
10348   // These should really be instruction patterns, but writing patterns with
10349   // source modiifiers is a pain.
10350 
10351   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10352   if (LHS.getOpcode() == ISD::FADD) {
10353     SDValue A = LHS.getOperand(0);
10354     if (A == LHS.getOperand(1)) {
10355       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10356       if (FusedOp != 0) {
10357         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10358         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10359       }
10360     }
10361   }
10362 
10363   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10364   if (RHS.getOpcode() == ISD::FADD) {
10365     SDValue A = RHS.getOperand(0);
10366     if (A == RHS.getOperand(1)) {
10367       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10368       if (FusedOp != 0) {
10369         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10370         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10371       }
10372     }
10373   }
10374 
10375   return SDValue();
10376 }
10377 
10378 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10379                                              DAGCombinerInfo &DCI) const {
10380   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10381     return SDValue();
10382 
10383   SelectionDAG &DAG = DCI.DAG;
10384   SDLoc SL(N);
10385   EVT VT = N->getValueType(0);
10386   assert(!VT.isVector());
10387 
10388   // Try to get the fneg to fold into the source modifier. This undoes generic
10389   // DAG combines and folds them into the mad.
10390   //
10391   // Only do this if we are not trying to support denormals. v_mad_f32 does
10392   // not support denormals ever.
10393   SDValue LHS = N->getOperand(0);
10394   SDValue RHS = N->getOperand(1);
10395   if (LHS.getOpcode() == ISD::FADD) {
10396     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10397     SDValue A = LHS.getOperand(0);
10398     if (A == LHS.getOperand(1)) {
10399       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10400       if (FusedOp != 0){
10401         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10402         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10403 
10404         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10405       }
10406     }
10407   }
10408 
10409   if (RHS.getOpcode() == ISD::FADD) {
10410     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10411 
10412     SDValue A = RHS.getOperand(0);
10413     if (A == RHS.getOperand(1)) {
10414       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10415       if (FusedOp != 0){
10416         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10417         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10418       }
10419     }
10420   }
10421 
10422   return SDValue();
10423 }
10424 
10425 SDValue SITargetLowering::performFMACombine(SDNode *N,
10426                                             DAGCombinerInfo &DCI) const {
10427   SelectionDAG &DAG = DCI.DAG;
10428   EVT VT = N->getValueType(0);
10429   SDLoc SL(N);
10430 
10431   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10432     return SDValue();
10433 
10434   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10435   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10436   SDValue Op1 = N->getOperand(0);
10437   SDValue Op2 = N->getOperand(1);
10438   SDValue FMA = N->getOperand(2);
10439 
10440   if (FMA.getOpcode() != ISD::FMA ||
10441       Op1.getOpcode() != ISD::FP_EXTEND ||
10442       Op2.getOpcode() != ISD::FP_EXTEND)
10443     return SDValue();
10444 
10445   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10446   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10447   // is sufficient to allow generaing fdot2.
10448   const TargetOptions &Options = DAG.getTarget().Options;
10449   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10450       (N->getFlags().hasAllowContract() &&
10451        FMA->getFlags().hasAllowContract())) {
10452     Op1 = Op1.getOperand(0);
10453     Op2 = Op2.getOperand(0);
10454     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10455         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10456       return SDValue();
10457 
10458     SDValue Vec1 = Op1.getOperand(0);
10459     SDValue Idx1 = Op1.getOperand(1);
10460     SDValue Vec2 = Op2.getOperand(0);
10461 
10462     SDValue FMAOp1 = FMA.getOperand(0);
10463     SDValue FMAOp2 = FMA.getOperand(1);
10464     SDValue FMAAcc = FMA.getOperand(2);
10465 
10466     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10467         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10468       return SDValue();
10469 
10470     FMAOp1 = FMAOp1.getOperand(0);
10471     FMAOp2 = FMAOp2.getOperand(0);
10472     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10473         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10474       return SDValue();
10475 
10476     SDValue Vec3 = FMAOp1.getOperand(0);
10477     SDValue Vec4 = FMAOp2.getOperand(0);
10478     SDValue Idx2 = FMAOp1.getOperand(1);
10479 
10480     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10481         // Idx1 and Idx2 cannot be the same.
10482         Idx1 == Idx2)
10483       return SDValue();
10484 
10485     if (Vec1 == Vec2 || Vec3 == Vec4)
10486       return SDValue();
10487 
10488     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10489       return SDValue();
10490 
10491     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10492         (Vec1 == Vec4 && Vec2 == Vec3)) {
10493       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10494                          DAG.getTargetConstant(0, SL, MVT::i1));
10495     }
10496   }
10497   return SDValue();
10498 }
10499 
10500 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10501                                               DAGCombinerInfo &DCI) const {
10502   SelectionDAG &DAG = DCI.DAG;
10503   SDLoc SL(N);
10504 
10505   SDValue LHS = N->getOperand(0);
10506   SDValue RHS = N->getOperand(1);
10507   EVT VT = LHS.getValueType();
10508   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10509 
10510   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10511   if (!CRHS) {
10512     CRHS = dyn_cast<ConstantSDNode>(LHS);
10513     if (CRHS) {
10514       std::swap(LHS, RHS);
10515       CC = getSetCCSwappedOperands(CC);
10516     }
10517   }
10518 
10519   if (CRHS) {
10520     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10521         isBoolSGPR(LHS.getOperand(0))) {
10522       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10523       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10524       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10525       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10526       if ((CRHS->isAllOnesValue() &&
10527            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10528           (CRHS->isNullValue() &&
10529            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10530         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10531                            DAG.getConstant(-1, SL, MVT::i1));
10532       if ((CRHS->isAllOnesValue() &&
10533            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10534           (CRHS->isNullValue() &&
10535            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10536         return LHS.getOperand(0);
10537     }
10538 
10539     uint64_t CRHSVal = CRHS->getZExtValue();
10540     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10541         LHS.getOpcode() == ISD::SELECT &&
10542         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10543         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10544         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10545         isBoolSGPR(LHS.getOperand(0))) {
10546       // Given CT != FT:
10547       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10548       // setcc (select cc, CT, CF), CF, ne => cc
10549       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10550       // setcc (select cc, CT, CF), CT, eq => cc
10551       uint64_t CT = LHS.getConstantOperandVal(1);
10552       uint64_t CF = LHS.getConstantOperandVal(2);
10553 
10554       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10555           (CT == CRHSVal && CC == ISD::SETNE))
10556         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10557                            DAG.getConstant(-1, SL, MVT::i1));
10558       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10559           (CT == CRHSVal && CC == ISD::SETEQ))
10560         return LHS.getOperand(0);
10561     }
10562   }
10563 
10564   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10565                                            VT != MVT::f16))
10566     return SDValue();
10567 
10568   // Match isinf/isfinite pattern
10569   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10570   // (fcmp one (fabs x), inf) -> (fp_class x,
10571   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10572   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10573     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10574     if (!CRHS)
10575       return SDValue();
10576 
10577     const APFloat &APF = CRHS->getValueAPF();
10578     if (APF.isInfinity() && !APF.isNegative()) {
10579       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10580                                  SIInstrFlags::N_INFINITY;
10581       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10582                                     SIInstrFlags::P_ZERO |
10583                                     SIInstrFlags::N_NORMAL |
10584                                     SIInstrFlags::P_NORMAL |
10585                                     SIInstrFlags::N_SUBNORMAL |
10586                                     SIInstrFlags::P_SUBNORMAL;
10587       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10588       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10589                          DAG.getConstant(Mask, SL, MVT::i32));
10590     }
10591   }
10592 
10593   return SDValue();
10594 }
10595 
10596 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10597                                                      DAGCombinerInfo &DCI) const {
10598   SelectionDAG &DAG = DCI.DAG;
10599   SDLoc SL(N);
10600   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10601 
10602   SDValue Src = N->getOperand(0);
10603   SDValue Shift = N->getOperand(0);
10604 
10605   // TODO: Extend type shouldn't matter (assuming legal types).
10606   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10607     Shift = Shift.getOperand(0);
10608 
10609   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10610     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10611     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10612     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10613     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10614     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10615     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10616       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10617                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10618 
10619       unsigned ShiftOffset = 8 * Offset;
10620       if (Shift.getOpcode() == ISD::SHL)
10621         ShiftOffset -= C->getZExtValue();
10622       else
10623         ShiftOffset += C->getZExtValue();
10624 
10625       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10626         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10627                            MVT::f32, Shift);
10628       }
10629     }
10630   }
10631 
10632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10633   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10634   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10635     // We simplified Src. If this node is not dead, visit it again so it is
10636     // folded properly.
10637     if (N->getOpcode() != ISD::DELETED_NODE)
10638       DCI.AddToWorklist(N);
10639     return SDValue(N, 0);
10640   }
10641 
10642   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10643   if (SDValue DemandedSrc =
10644           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10645     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10646 
10647   return SDValue();
10648 }
10649 
10650 SDValue SITargetLowering::performClampCombine(SDNode *N,
10651                                               DAGCombinerInfo &DCI) const {
10652   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10653   if (!CSrc)
10654     return SDValue();
10655 
10656   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10657   const APFloat &F = CSrc->getValueAPF();
10658   APFloat Zero = APFloat::getZero(F.getSemantics());
10659   if (F < Zero ||
10660       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10661     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10662   }
10663 
10664   APFloat One(F.getSemantics(), "1.0");
10665   if (F > One)
10666     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10667 
10668   return SDValue(CSrc, 0);
10669 }
10670 
10671 
10672 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10673                                             DAGCombinerInfo &DCI) const {
10674   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10675     return SDValue();
10676   switch (N->getOpcode()) {
10677   case ISD::ADD:
10678     return performAddCombine(N, DCI);
10679   case ISD::SUB:
10680     return performSubCombine(N, DCI);
10681   case ISD::ADDCARRY:
10682   case ISD::SUBCARRY:
10683     return performAddCarrySubCarryCombine(N, DCI);
10684   case ISD::FADD:
10685     return performFAddCombine(N, DCI);
10686   case ISD::FSUB:
10687     return performFSubCombine(N, DCI);
10688   case ISD::SETCC:
10689     return performSetCCCombine(N, DCI);
10690   case ISD::FMAXNUM:
10691   case ISD::FMINNUM:
10692   case ISD::FMAXNUM_IEEE:
10693   case ISD::FMINNUM_IEEE:
10694   case ISD::SMAX:
10695   case ISD::SMIN:
10696   case ISD::UMAX:
10697   case ISD::UMIN:
10698   case AMDGPUISD::FMIN_LEGACY:
10699   case AMDGPUISD::FMAX_LEGACY:
10700     return performMinMaxCombine(N, DCI);
10701   case ISD::FMA:
10702     return performFMACombine(N, DCI);
10703   case ISD::AND:
10704     return performAndCombine(N, DCI);
10705   case ISD::OR:
10706     return performOrCombine(N, DCI);
10707   case ISD::XOR:
10708     return performXorCombine(N, DCI);
10709   case ISD::ZERO_EXTEND:
10710     return performZeroExtendCombine(N, DCI);
10711   case ISD::SIGN_EXTEND_INREG:
10712     return performSignExtendInRegCombine(N , DCI);
10713   case AMDGPUISD::FP_CLASS:
10714     return performClassCombine(N, DCI);
10715   case ISD::FCANONICALIZE:
10716     return performFCanonicalizeCombine(N, DCI);
10717   case AMDGPUISD::RCP:
10718     return performRcpCombine(N, DCI);
10719   case AMDGPUISD::FRACT:
10720   case AMDGPUISD::RSQ:
10721   case AMDGPUISD::RCP_LEGACY:
10722   case AMDGPUISD::RCP_IFLAG:
10723   case AMDGPUISD::RSQ_CLAMP:
10724   case AMDGPUISD::LDEXP: {
10725     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10726     SDValue Src = N->getOperand(0);
10727     if (Src.isUndef())
10728       return Src;
10729     break;
10730   }
10731   case ISD::SINT_TO_FP:
10732   case ISD::UINT_TO_FP:
10733     return performUCharToFloatCombine(N, DCI);
10734   case AMDGPUISD::CVT_F32_UBYTE0:
10735   case AMDGPUISD::CVT_F32_UBYTE1:
10736   case AMDGPUISD::CVT_F32_UBYTE2:
10737   case AMDGPUISD::CVT_F32_UBYTE3:
10738     return performCvtF32UByteNCombine(N, DCI);
10739   case AMDGPUISD::FMED3:
10740     return performFMed3Combine(N, DCI);
10741   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10742     return performCvtPkRTZCombine(N, DCI);
10743   case AMDGPUISD::CLAMP:
10744     return performClampCombine(N, DCI);
10745   case ISD::SCALAR_TO_VECTOR: {
10746     SelectionDAG &DAG = DCI.DAG;
10747     EVT VT = N->getValueType(0);
10748 
10749     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10750     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10751       SDLoc SL(N);
10752       SDValue Src = N->getOperand(0);
10753       EVT EltVT = Src.getValueType();
10754       if (EltVT == MVT::f16)
10755         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10756 
10757       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10758       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10759     }
10760 
10761     break;
10762   }
10763   case ISD::EXTRACT_VECTOR_ELT:
10764     return performExtractVectorEltCombine(N, DCI);
10765   case ISD::INSERT_VECTOR_ELT:
10766     return performInsertVectorEltCombine(N, DCI);
10767   case ISD::LOAD: {
10768     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10769       return Widended;
10770     LLVM_FALLTHROUGH;
10771   }
10772   default: {
10773     if (!DCI.isBeforeLegalize()) {
10774       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10775         return performMemSDNodeCombine(MemNode, DCI);
10776     }
10777 
10778     break;
10779   }
10780   }
10781 
10782   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10783 }
10784 
10785 /// Helper function for adjustWritemask
10786 static unsigned SubIdx2Lane(unsigned Idx) {
10787   switch (Idx) {
10788   default: return ~0u;
10789   case AMDGPU::sub0: return 0;
10790   case AMDGPU::sub1: return 1;
10791   case AMDGPU::sub2: return 2;
10792   case AMDGPU::sub3: return 3;
10793   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10794   }
10795 }
10796 
10797 /// Adjust the writemask of MIMG instructions
10798 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10799                                           SelectionDAG &DAG) const {
10800   unsigned Opcode = Node->getMachineOpcode();
10801 
10802   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10803   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10804   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10805     return Node; // not implemented for D16
10806 
10807   SDNode *Users[5] = { nullptr };
10808   unsigned Lane = 0;
10809   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10810   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10811   unsigned NewDmask = 0;
10812   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10813   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10814   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10815                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10816   unsigned TFCLane = 0;
10817   bool HasChain = Node->getNumValues() > 1;
10818 
10819   if (OldDmask == 0) {
10820     // These are folded out, but on the chance it happens don't assert.
10821     return Node;
10822   }
10823 
10824   unsigned OldBitsSet = countPopulation(OldDmask);
10825   // Work out which is the TFE/LWE lane if that is enabled.
10826   if (UsesTFC) {
10827     TFCLane = OldBitsSet;
10828   }
10829 
10830   // Try to figure out the used register components
10831   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10832        I != E; ++I) {
10833 
10834     // Don't look at users of the chain.
10835     if (I.getUse().getResNo() != 0)
10836       continue;
10837 
10838     // Abort if we can't understand the usage
10839     if (!I->isMachineOpcode() ||
10840         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10841       return Node;
10842 
10843     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10844     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10845     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10846     // set, etc.
10847     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10848     if (Lane == ~0u)
10849       return Node;
10850 
10851     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10852     if (UsesTFC && Lane == TFCLane) {
10853       Users[Lane] = *I;
10854     } else {
10855       // Set which texture component corresponds to the lane.
10856       unsigned Comp;
10857       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10858         Comp = countTrailingZeros(Dmask);
10859         Dmask &= ~(1 << Comp);
10860       }
10861 
10862       // Abort if we have more than one user per component.
10863       if (Users[Lane])
10864         return Node;
10865 
10866       Users[Lane] = *I;
10867       NewDmask |= 1 << Comp;
10868     }
10869   }
10870 
10871   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10872   bool NoChannels = !NewDmask;
10873   if (NoChannels) {
10874     if (!UsesTFC) {
10875       // No uses of the result and not using TFC. Then do nothing.
10876       return Node;
10877     }
10878     // If the original dmask has one channel - then nothing to do
10879     if (OldBitsSet == 1)
10880       return Node;
10881     // Use an arbitrary dmask - required for the instruction to work
10882     NewDmask = 1;
10883   }
10884   // Abort if there's no change
10885   if (NewDmask == OldDmask)
10886     return Node;
10887 
10888   unsigned BitsSet = countPopulation(NewDmask);
10889 
10890   // Check for TFE or LWE - increase the number of channels by one to account
10891   // for the extra return value
10892   // This will need adjustment for D16 if this is also included in
10893   // adjustWriteMask (this function) but at present D16 are excluded.
10894   unsigned NewChannels = BitsSet + UsesTFC;
10895 
10896   int NewOpcode =
10897       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10898   assert(NewOpcode != -1 &&
10899          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10900          "failed to find equivalent MIMG op");
10901 
10902   // Adjust the writemask in the node
10903   SmallVector<SDValue, 12> Ops;
10904   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10905   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10906   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10907 
10908   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10909 
10910   MVT ResultVT = NewChannels == 1 ?
10911     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10912                            NewChannels == 5 ? 8 : NewChannels);
10913   SDVTList NewVTList = HasChain ?
10914     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10915 
10916 
10917   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10918                                               NewVTList, Ops);
10919 
10920   if (HasChain) {
10921     // Update chain.
10922     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10923     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10924   }
10925 
10926   if (NewChannels == 1) {
10927     assert(Node->hasNUsesOfValue(1, 0));
10928     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10929                                       SDLoc(Node), Users[Lane]->getValueType(0),
10930                                       SDValue(NewNode, 0));
10931     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10932     return nullptr;
10933   }
10934 
10935   // Update the users of the node with the new indices
10936   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10937     SDNode *User = Users[i];
10938     if (!User) {
10939       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10940       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10941       if (i || !NoChannels)
10942         continue;
10943     } else {
10944       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10945       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10946     }
10947 
10948     switch (Idx) {
10949     default: break;
10950     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10951     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10952     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10953     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10954     }
10955   }
10956 
10957   DAG.RemoveDeadNode(Node);
10958   return nullptr;
10959 }
10960 
10961 static bool isFrameIndexOp(SDValue Op) {
10962   if (Op.getOpcode() == ISD::AssertZext)
10963     Op = Op.getOperand(0);
10964 
10965   return isa<FrameIndexSDNode>(Op);
10966 }
10967 
10968 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10969 /// with frame index operands.
10970 /// LLVM assumes that inputs are to these instructions are registers.
10971 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10972                                                         SelectionDAG &DAG) const {
10973   if (Node->getOpcode() == ISD::CopyToReg) {
10974     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10975     SDValue SrcVal = Node->getOperand(2);
10976 
10977     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10978     // to try understanding copies to physical registers.
10979     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
10980       SDLoc SL(Node);
10981       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10982       SDValue VReg = DAG.getRegister(
10983         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10984 
10985       SDNode *Glued = Node->getGluedNode();
10986       SDValue ToVReg
10987         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10988                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10989       SDValue ToResultReg
10990         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10991                            VReg, ToVReg.getValue(1));
10992       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10993       DAG.RemoveDeadNode(Node);
10994       return ToResultReg.getNode();
10995     }
10996   }
10997 
10998   SmallVector<SDValue, 8> Ops;
10999   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11000     if (!isFrameIndexOp(Node->getOperand(i))) {
11001       Ops.push_back(Node->getOperand(i));
11002       continue;
11003     }
11004 
11005     SDLoc DL(Node);
11006     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11007                                      Node->getOperand(i).getValueType(),
11008                                      Node->getOperand(i)), 0));
11009   }
11010 
11011   return DAG.UpdateNodeOperands(Node, Ops);
11012 }
11013 
11014 /// Fold the instructions after selecting them.
11015 /// Returns null if users were already updated.
11016 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11017                                           SelectionDAG &DAG) const {
11018   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11019   unsigned Opcode = Node->getMachineOpcode();
11020 
11021   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11022       !TII->isGather4(Opcode) &&
11023       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11024     return adjustWritemask(Node, DAG);
11025   }
11026 
11027   if (Opcode == AMDGPU::INSERT_SUBREG ||
11028       Opcode == AMDGPU::REG_SEQUENCE) {
11029     legalizeTargetIndependentNode(Node, DAG);
11030     return Node;
11031   }
11032 
11033   switch (Opcode) {
11034   case AMDGPU::V_DIV_SCALE_F32_e64:
11035   case AMDGPU::V_DIV_SCALE_F64_e64: {
11036     // Satisfy the operand register constraint when one of the inputs is
11037     // undefined. Ordinarily each undef value will have its own implicit_def of
11038     // a vreg, so force these to use a single register.
11039     SDValue Src0 = Node->getOperand(1);
11040     SDValue Src1 = Node->getOperand(3);
11041     SDValue Src2 = Node->getOperand(5);
11042 
11043     if ((Src0.isMachineOpcode() &&
11044          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11045         (Src0 == Src1 || Src0 == Src2))
11046       break;
11047 
11048     MVT VT = Src0.getValueType().getSimpleVT();
11049     const TargetRegisterClass *RC =
11050         getRegClassFor(VT, Src0.getNode()->isDivergent());
11051 
11052     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11053     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11054 
11055     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11056                                       UndefReg, Src0, SDValue());
11057 
11058     // src0 must be the same register as src1 or src2, even if the value is
11059     // undefined, so make sure we don't violate this constraint.
11060     if (Src0.isMachineOpcode() &&
11061         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11062       if (Src1.isMachineOpcode() &&
11063           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11064         Src0 = Src1;
11065       else if (Src2.isMachineOpcode() &&
11066                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11067         Src0 = Src2;
11068       else {
11069         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11070         Src0 = UndefReg;
11071         Src1 = UndefReg;
11072       }
11073     } else
11074       break;
11075 
11076     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11077     Ops[1] = Src0;
11078     Ops[3] = Src1;
11079     Ops[5] = Src2;
11080     Ops.push_back(ImpDef.getValue(1));
11081     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11082   }
11083   default:
11084     break;
11085   }
11086 
11087   return Node;
11088 }
11089 
11090 /// Assign the register class depending on the number of
11091 /// bits set in the writemask
11092 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11093                                                      SDNode *Node) const {
11094   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11095 
11096   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11097 
11098   if (TII->isVOP3(MI.getOpcode())) {
11099     // Make sure constant bus requirements are respected.
11100     TII->legalizeOperandsVOP3(MRI, MI);
11101 
11102     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11103     // This saves a chain-copy of registers and better ballance register
11104     // use between vgpr and agpr as agpr tuples tend to be big.
11105     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11106       unsigned Opc = MI.getOpcode();
11107       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11108       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11109                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11110         if (I == -1)
11111           break;
11112         MachineOperand &Op = MI.getOperand(I);
11113         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11114              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11115             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11116           continue;
11117         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11118         if (!Src || !Src->isCopy() ||
11119             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11120           continue;
11121         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11122         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11123         // All uses of agpr64 and agpr32 can also accept vgpr except for
11124         // v_accvgpr_read, but we do not produce agpr reads during selection,
11125         // so no use checks are needed.
11126         MRI.setRegClass(Op.getReg(), NewRC);
11127       }
11128     }
11129 
11130     return;
11131   }
11132 
11133   // Replace unused atomics with the no return version.
11134   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11135   if (NoRetAtomicOp != -1) {
11136     if (!Node->hasAnyUseOfValue(0)) {
11137       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11138                                                AMDGPU::OpName::glc1);
11139       if (Glc1Idx != -1)
11140         MI.RemoveOperand(Glc1Idx);
11141       MI.RemoveOperand(0);
11142       MI.setDesc(TII->get(NoRetAtomicOp));
11143       return;
11144     }
11145 
11146     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11147     // instruction, because the return type of these instructions is a vec2 of
11148     // the memory type, so it can be tied to the input operand.
11149     // This means these instructions always have a use, so we need to add a
11150     // special case to check if the atomic has only one extract_subreg use,
11151     // which itself has no uses.
11152     if ((Node->hasNUsesOfValue(1, 0) &&
11153          Node->use_begin()->isMachineOpcode() &&
11154          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11155          !Node->use_begin()->hasAnyUseOfValue(0))) {
11156       Register Def = MI.getOperand(0).getReg();
11157 
11158       // Change this into a noret atomic.
11159       MI.setDesc(TII->get(NoRetAtomicOp));
11160       MI.RemoveOperand(0);
11161 
11162       // If we only remove the def operand from the atomic instruction, the
11163       // extract_subreg will be left with a use of a vreg without a def.
11164       // So we need to insert an implicit_def to avoid machine verifier
11165       // errors.
11166       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11167               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11168     }
11169     return;
11170   }
11171 }
11172 
11173 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11174                               uint64_t Val) {
11175   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11176   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11177 }
11178 
11179 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11180                                                 const SDLoc &DL,
11181                                                 SDValue Ptr) const {
11182   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11183 
11184   // Build the half of the subregister with the constants before building the
11185   // full 128-bit register. If we are building multiple resource descriptors,
11186   // this will allow CSEing of the 2-component register.
11187   const SDValue Ops0[] = {
11188     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11189     buildSMovImm32(DAG, DL, 0),
11190     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11191     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11192     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11193   };
11194 
11195   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11196                                                 MVT::v2i32, Ops0), 0);
11197 
11198   // Combine the constants and the pointer.
11199   const SDValue Ops1[] = {
11200     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11201     Ptr,
11202     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11203     SubRegHi,
11204     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11205   };
11206 
11207   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11208 }
11209 
11210 /// Return a resource descriptor with the 'Add TID' bit enabled
11211 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11212 ///        of the resource descriptor) to create an offset, which is added to
11213 ///        the resource pointer.
11214 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11215                                            SDValue Ptr, uint32_t RsrcDword1,
11216                                            uint64_t RsrcDword2And3) const {
11217   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11218   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11219   if (RsrcDword1) {
11220     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11221                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11222                     0);
11223   }
11224 
11225   SDValue DataLo = buildSMovImm32(DAG, DL,
11226                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11227   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11228 
11229   const SDValue Ops[] = {
11230     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11231     PtrLo,
11232     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11233     PtrHi,
11234     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11235     DataLo,
11236     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11237     DataHi,
11238     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11239   };
11240 
11241   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11242 }
11243 
11244 //===----------------------------------------------------------------------===//
11245 //                         SI Inline Assembly Support
11246 //===----------------------------------------------------------------------===//
11247 
11248 std::pair<unsigned, const TargetRegisterClass *>
11249 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11250                                                StringRef Constraint,
11251                                                MVT VT) const {
11252   const TargetRegisterClass *RC = nullptr;
11253   if (Constraint.size() == 1) {
11254     const unsigned BitWidth = VT.getSizeInBits();
11255     switch (Constraint[0]) {
11256     default:
11257       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11258     case 's':
11259     case 'r':
11260       switch (BitWidth) {
11261       case 16:
11262         RC = &AMDGPU::SReg_32RegClass;
11263         break;
11264       case 64:
11265         RC = &AMDGPU::SGPR_64RegClass;
11266         break;
11267       default:
11268         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11269         if (!RC)
11270           return std::make_pair(0U, nullptr);
11271         break;
11272       }
11273       break;
11274     case 'v':
11275       switch (BitWidth) {
11276       case 16:
11277         RC = &AMDGPU::VGPR_32RegClass;
11278         break;
11279       default:
11280         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11281         if (!RC)
11282           return std::make_pair(0U, nullptr);
11283         break;
11284       }
11285       break;
11286     case 'a':
11287       if (!Subtarget->hasMAIInsts())
11288         break;
11289       switch (BitWidth) {
11290       case 16:
11291         RC = &AMDGPU::AGPR_32RegClass;
11292         break;
11293       default:
11294         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11295         if (!RC)
11296           return std::make_pair(0U, nullptr);
11297         break;
11298       }
11299       break;
11300     }
11301     // We actually support i128, i16 and f16 as inline parameters
11302     // even if they are not reported as legal
11303     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11304                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11305       return std::make_pair(0U, RC);
11306   }
11307 
11308   if (Constraint.size() > 1) {
11309     if (Constraint[1] == 'v') {
11310       RC = &AMDGPU::VGPR_32RegClass;
11311     } else if (Constraint[1] == 's') {
11312       RC = &AMDGPU::SGPR_32RegClass;
11313     } else if (Constraint[1] == 'a') {
11314       RC = &AMDGPU::AGPR_32RegClass;
11315     }
11316 
11317     if (RC) {
11318       uint32_t Idx;
11319       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11320       if (!Failed && Idx < RC->getNumRegs())
11321         return std::make_pair(RC->getRegister(Idx), RC);
11322     }
11323   }
11324 
11325   // FIXME: Returns VS_32 for physical SGPR constraints
11326   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11327 }
11328 
11329 static bool isImmConstraint(StringRef Constraint) {
11330   if (Constraint.size() == 1) {
11331     switch (Constraint[0]) {
11332     default: break;
11333     case 'I':
11334     case 'J':
11335     case 'A':
11336     case 'B':
11337     case 'C':
11338       return true;
11339     }
11340   } else if (Constraint == "DA" ||
11341              Constraint == "DB") {
11342     return true;
11343   }
11344   return false;
11345 }
11346 
11347 SITargetLowering::ConstraintType
11348 SITargetLowering::getConstraintType(StringRef Constraint) const {
11349   if (Constraint.size() == 1) {
11350     switch (Constraint[0]) {
11351     default: break;
11352     case 's':
11353     case 'v':
11354     case 'a':
11355       return C_RegisterClass;
11356     }
11357   }
11358   if (isImmConstraint(Constraint)) {
11359     return C_Other;
11360   }
11361   return TargetLowering::getConstraintType(Constraint);
11362 }
11363 
11364 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11365   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11366     Val = Val & maskTrailingOnes<uint64_t>(Size);
11367   }
11368   return Val;
11369 }
11370 
11371 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11372                                                     std::string &Constraint,
11373                                                     std::vector<SDValue> &Ops,
11374                                                     SelectionDAG &DAG) const {
11375   if (isImmConstraint(Constraint)) {
11376     uint64_t Val;
11377     if (getAsmOperandConstVal(Op, Val) &&
11378         checkAsmConstraintVal(Op, Constraint, Val)) {
11379       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11380       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11381     }
11382   } else {
11383     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11384   }
11385 }
11386 
11387 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11388   unsigned Size = Op.getScalarValueSizeInBits();
11389   if (Size > 64)
11390     return false;
11391 
11392   if (Size == 16 && !Subtarget->has16BitInsts())
11393     return false;
11394 
11395   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11396     Val = C->getSExtValue();
11397     return true;
11398   }
11399   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11400     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11401     return true;
11402   }
11403   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11404     if (Size != 16 || Op.getNumOperands() != 2)
11405       return false;
11406     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11407       return false;
11408     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11409       Val = C->getSExtValue();
11410       return true;
11411     }
11412     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11413       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11414       return true;
11415     }
11416   }
11417 
11418   return false;
11419 }
11420 
11421 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11422                                              const std::string &Constraint,
11423                                              uint64_t Val) const {
11424   if (Constraint.size() == 1) {
11425     switch (Constraint[0]) {
11426     case 'I':
11427       return AMDGPU::isInlinableIntLiteral(Val);
11428     case 'J':
11429       return isInt<16>(Val);
11430     case 'A':
11431       return checkAsmConstraintValA(Op, Val);
11432     case 'B':
11433       return isInt<32>(Val);
11434     case 'C':
11435       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11436              AMDGPU::isInlinableIntLiteral(Val);
11437     default:
11438       break;
11439     }
11440   } else if (Constraint.size() == 2) {
11441     if (Constraint == "DA") {
11442       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11443       int64_t LoBits = static_cast<int32_t>(Val);
11444       return checkAsmConstraintValA(Op, HiBits, 32) &&
11445              checkAsmConstraintValA(Op, LoBits, 32);
11446     }
11447     if (Constraint == "DB") {
11448       return true;
11449     }
11450   }
11451   llvm_unreachable("Invalid asm constraint");
11452 }
11453 
11454 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11455                                               uint64_t Val,
11456                                               unsigned MaxSize) const {
11457   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11458   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11459   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11460       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11461       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11462     return true;
11463   }
11464   return false;
11465 }
11466 
11467 // Figure out which registers should be reserved for stack access. Only after
11468 // the function is legalized do we know all of the non-spill stack objects or if
11469 // calls are present.
11470 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11471   MachineRegisterInfo &MRI = MF.getRegInfo();
11472   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11473   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11474   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11475 
11476   if (Info->isEntryFunction()) {
11477     // Callable functions have fixed registers used for stack access.
11478     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11479   }
11480 
11481   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11482                              Info->getStackPtrOffsetReg()));
11483   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11484     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11485 
11486   // We need to worry about replacing the default register with itself in case
11487   // of MIR testcases missing the MFI.
11488   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11489     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11490 
11491   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11492     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11493 
11494   Info->limitOccupancy(MF);
11495 
11496   if (ST.isWave32() && !MF.empty()) {
11497     const SIInstrInfo *TII = ST.getInstrInfo();
11498     for (auto &MBB : MF) {
11499       for (auto &MI : MBB) {
11500         TII->fixImplicitOperands(MI);
11501       }
11502     }
11503   }
11504 
11505   TargetLoweringBase::finalizeLowering(MF);
11506 
11507   // Allocate a VGPR for future SGPR Spill if
11508   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11509   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11510   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11511       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction() &&
11512       MF.getFrameInfo().hasStackObjects())
11513     Info->reserveVGPRforSGPRSpills(MF);
11514 }
11515 
11516 void SITargetLowering::computeKnownBitsForFrameIndex(
11517   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11518   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11519 
11520   // Set the high bits to zero based on the maximum allowed scratch size per
11521   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11522   // calculation won't overflow, so assume the sign bit is never set.
11523   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11524 }
11525 
11526 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11527                                    KnownBits &Known, unsigned Dim) {
11528   unsigned MaxValue =
11529       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11530   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11531 }
11532 
11533 void SITargetLowering::computeKnownBitsForTargetInstr(
11534     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11535     const MachineRegisterInfo &MRI, unsigned Depth) const {
11536   const MachineInstr *MI = MRI.getVRegDef(R);
11537   switch (MI->getOpcode()) {
11538   case AMDGPU::G_INTRINSIC: {
11539     switch (MI->getIntrinsicID()) {
11540     case Intrinsic::amdgcn_workitem_id_x:
11541       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11542       break;
11543     case Intrinsic::amdgcn_workitem_id_y:
11544       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11545       break;
11546     case Intrinsic::amdgcn_workitem_id_z:
11547       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11548       break;
11549     case Intrinsic::amdgcn_mbcnt_lo:
11550     case Intrinsic::amdgcn_mbcnt_hi: {
11551       // These return at most the wavefront size - 1.
11552       unsigned Size = MRI.getType(R).getSizeInBits();
11553       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11554       break;
11555     }
11556     case Intrinsic::amdgcn_groupstaticsize: {
11557       // We can report everything over the maximum size as 0. We can't report
11558       // based on the actual size because we don't know if it's accurate or not
11559       // at any given point.
11560       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11561       break;
11562     }
11563     }
11564     break;
11565   }
11566   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11567     Known.Zero.setHighBits(24);
11568     break;
11569   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11570     Known.Zero.setHighBits(16);
11571     break;
11572   }
11573 }
11574 
11575 Align SITargetLowering::computeKnownAlignForTargetInstr(
11576   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11577   unsigned Depth) const {
11578   const MachineInstr *MI = MRI.getVRegDef(R);
11579   switch (MI->getOpcode()) {
11580   case AMDGPU::G_INTRINSIC:
11581   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11582     // FIXME: Can this move to generic code? What about the case where the call
11583     // site specifies a lower alignment?
11584     Intrinsic::ID IID = MI->getIntrinsicID();
11585     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11586     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11587     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11588       return *RetAlign;
11589     return Align(1);
11590   }
11591   default:
11592     return Align(1);
11593   }
11594 }
11595 
11596 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11597   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11598   const Align CacheLineAlign = Align(64);
11599 
11600   // Pre-GFX10 target did not benefit from loop alignment
11601   if (!ML || DisableLoopAlignment ||
11602       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11603       getSubtarget()->hasInstFwdPrefetchBug())
11604     return PrefAlign;
11605 
11606   // On GFX10 I$ is 4 x 64 bytes cache lines.
11607   // By default prefetcher keeps one cache line behind and reads two ahead.
11608   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11609   // behind and one ahead.
11610   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11611   // If loop fits 64 bytes it always spans no more than two cache lines and
11612   // does not need an alignment.
11613   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11614   // Else if loop is less or equal 192 bytes we need two lines behind.
11615 
11616   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11617   const MachineBasicBlock *Header = ML->getHeader();
11618   if (Header->getAlignment() != PrefAlign)
11619     return Header->getAlignment(); // Already processed.
11620 
11621   unsigned LoopSize = 0;
11622   for (const MachineBasicBlock *MBB : ML->blocks()) {
11623     // If inner loop block is aligned assume in average half of the alignment
11624     // size to be added as nops.
11625     if (MBB != Header)
11626       LoopSize += MBB->getAlignment().value() / 2;
11627 
11628     for (const MachineInstr &MI : *MBB) {
11629       LoopSize += TII->getInstSizeInBytes(MI);
11630       if (LoopSize > 192)
11631         return PrefAlign;
11632     }
11633   }
11634 
11635   if (LoopSize <= 64)
11636     return PrefAlign;
11637 
11638   if (LoopSize <= 128)
11639     return CacheLineAlign;
11640 
11641   // If any of parent loops is surrounded by prefetch instructions do not
11642   // insert new for inner loop, which would reset parent's settings.
11643   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11644     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11645       auto I = Exit->getFirstNonDebugInstr();
11646       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11647         return CacheLineAlign;
11648     }
11649   }
11650 
11651   MachineBasicBlock *Pre = ML->getLoopPreheader();
11652   MachineBasicBlock *Exit = ML->getExitBlock();
11653 
11654   if (Pre && Exit) {
11655     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11656             TII->get(AMDGPU::S_INST_PREFETCH))
11657       .addImm(1); // prefetch 2 lines behind PC
11658 
11659     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11660             TII->get(AMDGPU::S_INST_PREFETCH))
11661       .addImm(2); // prefetch 1 line behind PC
11662   }
11663 
11664   return CacheLineAlign;
11665 }
11666 
11667 LLVM_ATTRIBUTE_UNUSED
11668 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11669   assert(N->getOpcode() == ISD::CopyFromReg);
11670   do {
11671     // Follow the chain until we find an INLINEASM node.
11672     N = N->getOperand(0).getNode();
11673     if (N->getOpcode() == ISD::INLINEASM ||
11674         N->getOpcode() == ISD::INLINEASM_BR)
11675       return true;
11676   } while (N->getOpcode() == ISD::CopyFromReg);
11677   return false;
11678 }
11679 
11680 bool SITargetLowering::isSDNodeSourceOfDivergence(
11681     const SDNode *N, FunctionLoweringInfo *FLI,
11682     LegacyDivergenceAnalysis *KDA) const {
11683   switch (N->getOpcode()) {
11684   case ISD::CopyFromReg: {
11685     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11686     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11687     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11688     Register Reg = R->getReg();
11689 
11690     // FIXME: Why does this need to consider isLiveIn?
11691     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11692       return !TRI->isSGPRReg(MRI, Reg);
11693 
11694     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11695       return KDA->isDivergent(V);
11696 
11697     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11698     return !TRI->isSGPRReg(MRI, Reg);
11699   }
11700   case ISD::LOAD: {
11701     const LoadSDNode *L = cast<LoadSDNode>(N);
11702     unsigned AS = L->getAddressSpace();
11703     // A flat load may access private memory.
11704     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11705   }
11706   case ISD::CALLSEQ_END:
11707     return true;
11708   case ISD::INTRINSIC_WO_CHAIN:
11709     return AMDGPU::isIntrinsicSourceOfDivergence(
11710         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11711   case ISD::INTRINSIC_W_CHAIN:
11712     return AMDGPU::isIntrinsicSourceOfDivergence(
11713         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11714   }
11715   return false;
11716 }
11717 
11718 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11719                                                EVT VT) const {
11720   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11721   case MVT::f32:
11722     return hasFP32Denormals(DAG.getMachineFunction());
11723   case MVT::f64:
11724   case MVT::f16:
11725     return hasFP64FP16Denormals(DAG.getMachineFunction());
11726   default:
11727     return false;
11728   }
11729 }
11730 
11731 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11732                                                     const SelectionDAG &DAG,
11733                                                     bool SNaN,
11734                                                     unsigned Depth) const {
11735   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11736     const MachineFunction &MF = DAG.getMachineFunction();
11737     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11738 
11739     if (Info->getMode().DX10Clamp)
11740       return true; // Clamped to 0.
11741     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11742   }
11743 
11744   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11745                                                             SNaN, Depth);
11746 }
11747 
11748 // Global FP atomic instructions have a hardcoded FP mode and do not support
11749 // FP32 denormals, and only support v2f16 denormals.
11750 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11751   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11752   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11753   if (&Flt == &APFloat::IEEEsingle())
11754     return DenormMode == DenormalMode::getPreserveSign();
11755   return DenormMode == DenormalMode::getIEEE();
11756 }
11757 
11758 TargetLowering::AtomicExpansionKind
11759 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11760   switch (RMW->getOperation()) {
11761   case AtomicRMWInst::FAdd: {
11762     Type *Ty = RMW->getType();
11763 
11764     // We don't have a way to support 16-bit atomics now, so just leave them
11765     // as-is.
11766     if (Ty->isHalfTy())
11767       return AtomicExpansionKind::None;
11768 
11769     if (!Ty->isFloatTy())
11770       return AtomicExpansionKind::CmpXChg;
11771 
11772     // TODO: Do have these for flat. Older targets also had them for buffers.
11773     unsigned AS = RMW->getPointerAddressSpace();
11774 
11775     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11776       if (!fpModeMatchesGlobalFPAtomicMode(RMW) ||
11777           RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics")
11778               .getValueAsString() != "true")
11779         return AtomicExpansionKind::CmpXChg;
11780 
11781       return RMW->use_empty() ? AtomicExpansionKind::None :
11782                                 AtomicExpansionKind::CmpXChg;
11783     }
11784 
11785     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11786     // to round-to-nearest-even.
11787     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11788       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11789   }
11790   default:
11791     break;
11792   }
11793 
11794   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11795 }
11796 
11797 const TargetRegisterClass *
11798 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11799   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11800   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11801   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11802     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11803                                                : &AMDGPU::SReg_32RegClass;
11804   if (!TRI->isSGPRClass(RC) && !isDivergent)
11805     return TRI->getEquivalentSGPRClass(RC);
11806   else if (TRI->isSGPRClass(RC) && isDivergent)
11807     return TRI->getEquivalentVGPRClass(RC);
11808 
11809   return RC;
11810 }
11811 
11812 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11813 // uniform values (as produced by the mask results of control flow intrinsics)
11814 // used outside of divergent blocks. The phi users need to also be treated as
11815 // always uniform.
11816 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11817                       unsigned WaveSize) {
11818   // FIXME: We asssume we never cast the mask results of a control flow
11819   // intrinsic.
11820   // Early exit if the type won't be consistent as a compile time hack.
11821   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11822   if (!IT || IT->getBitWidth() != WaveSize)
11823     return false;
11824 
11825   if (!isa<Instruction>(V))
11826     return false;
11827   if (!Visited.insert(V).second)
11828     return false;
11829   bool Result = false;
11830   for (auto U : V->users()) {
11831     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11832       if (V == U->getOperand(1)) {
11833         switch (Intrinsic->getIntrinsicID()) {
11834         default:
11835           Result = false;
11836           break;
11837         case Intrinsic::amdgcn_if_break:
11838         case Intrinsic::amdgcn_if:
11839         case Intrinsic::amdgcn_else:
11840           Result = true;
11841           break;
11842         }
11843       }
11844       if (V == U->getOperand(0)) {
11845         switch (Intrinsic->getIntrinsicID()) {
11846         default:
11847           Result = false;
11848           break;
11849         case Intrinsic::amdgcn_end_cf:
11850         case Intrinsic::amdgcn_loop:
11851           Result = true;
11852           break;
11853         }
11854       }
11855     } else {
11856       Result = hasCFUser(U, Visited, WaveSize);
11857     }
11858     if (Result)
11859       break;
11860   }
11861   return Result;
11862 }
11863 
11864 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11865                                                const Value *V) const {
11866   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11867     if (CI->isInlineAsm()) {
11868       // FIXME: This cannot give a correct answer. This should only trigger in
11869       // the case where inline asm returns mixed SGPR and VGPR results, used
11870       // outside the defining block. We don't have a specific result to
11871       // consider, so this assumes if any value is SGPR, the overall register
11872       // also needs to be SGPR.
11873       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11874       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11875           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11876       for (auto &TC : TargetConstraints) {
11877         if (TC.Type == InlineAsm::isOutput) {
11878           ComputeConstraintToUse(TC, SDValue());
11879           unsigned AssignedReg;
11880           const TargetRegisterClass *RC;
11881           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11882               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11883           if (RC) {
11884             MachineRegisterInfo &MRI = MF.getRegInfo();
11885             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11886               return true;
11887             else if (SIRI->isSGPRClass(RC))
11888               return true;
11889           }
11890         }
11891       }
11892     }
11893   }
11894   SmallPtrSet<const Value *, 16> Visited;
11895   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11896 }
11897 
11898 std::pair<int, MVT>
11899 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11900                                           Type *Ty) const {
11901   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11902   auto Size = DL.getTypeSizeInBits(Ty);
11903   // Maximum load or store can handle 8 dwords for scalar and 4 for
11904   // vector ALU. Let's assume anything above 8 dwords is expensive
11905   // even if legal.
11906   if (Size <= 256)
11907     return Cost;
11908 
11909   Cost.first = (Size + 255) / 256;
11910   return Cost;
11911 }
11912