xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp (revision fcaf7f8644a9988098ac6be2165bce3ea4786e91)
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/FloatingPointMode.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/IntrinsicsAMDGPU.h"
35 #include "llvm/IR/IntrinsicsR600.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "si-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 static cl::opt<bool> DisableLoopAlignment(
46   "amdgpu-disable-loop-alignment",
47   cl::desc("Do not align and prefetch loops"),
48   cl::init(false));
49 
50 static cl::opt<bool> UseDivergentRegisterIndexing(
51   "amdgpu-use-divergent-register-indexing",
52   cl::Hidden,
53   cl::desc("Use indirect register addressing for divergent indexes"),
54   cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
57   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
58   return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
62   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
63   return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70       return AMDGPU::SGPR0 + Reg;
71     }
72   }
73   llvm_unreachable("Cannot allocate sgpr");
74 }
75 
76 SITargetLowering::SITargetLowering(const TargetMachine &TM,
77                                    const GCNSubtarget &STI)
78     : AMDGPUTargetLowering(TM, STI),
79       Subtarget(&STI) {
80   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88   const SIRegisterInfo *TRI = STI.getRegisterInfo();
89   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91   addRegisterClass(MVT::f64, V64RegClass);
92   addRegisterClass(MVT::v2f32, V64RegClass);
93 
94   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130   if (Subtarget->has16BitInsts()) {
131     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134     // Unless there are also VOP3P operations, not operations are really legal.
135     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
140     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
141     addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
142     addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
143   }
144 
145   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
146   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
147 
148   computeRegisterProperties(Subtarget->getRegisterInfo());
149 
150   // The boolean content concept here is too inflexible. Compares only ever
151   // really produce a 1-bit result. Any copy/extend from these will turn into a
152   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
153   // it's what most targets use.
154   setBooleanContents(ZeroOrOneBooleanContent);
155   setBooleanVectorContents(ZeroOrOneBooleanContent);
156 
157   // We need to custom lower vector stores from local memory
158   setOperationAction(ISD::LOAD,
159                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
160                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
161                       MVT::v32i32},
162                      Custom);
163 
164   setOperationAction(ISD::STORE,
165                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
166                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
167                       MVT::v32i32},
168                      Custom);
169 
170   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
171   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
172   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
173   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
174   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
175   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
176   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
177   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
178   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
179   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
180   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
181   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
182   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
183   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
184   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
185   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
186 
187   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
188   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
189   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
192   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
193   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
194 
195   setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
196 
197   setOperationAction(ISD::SELECT, MVT::i1, Promote);
198   setOperationAction(ISD::SELECT, MVT::i64, Custom);
199   setOperationAction(ISD::SELECT, MVT::f64, Promote);
200   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
201 
202   setOperationAction(ISD::SELECT_CC,
203                      {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
204 
205   setOperationAction(ISD::SETCC, MVT::i1, Promote);
206   setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
207   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
208 
209   setOperationAction(ISD::TRUNCATE,
210                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
211                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32},
212                      Expand);
213   setOperationAction(ISD::FP_ROUND,
214                      {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
215                       MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32},
216                      Expand);
217 
218   setOperationAction(ISD::SIGN_EXTEND_INREG,
219                      {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
220                       MVT::v3i16, MVT::v4i16, MVT::Other},
221                      Custom);
222 
223   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
224   setOperationAction(ISD::BR_CC,
225                      {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
226 
227   setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
228 
229   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal);
230 
231   setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
232                      Expand);
233 
234 #if 0
235   setOperationAction({ISD::ADDCARRY, 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 :
241        {MVT::v8i32,  MVT::v8f32,  MVT::v16i32, MVT::v16f32, MVT::v2i64,
242         MVT::v2f64,  MVT::v4i16,  MVT::v4f16,  MVT::v3i64,  MVT::v3f64,
243         MVT::v6i32,  MVT::v6f32,  MVT::v4i64,  MVT::v4f64,  MVT::v8i64,
244         MVT::v8f64,  MVT::v8i16,  MVT::v8f16,  MVT::v16i16, MVT::v16f16,
245         MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32}) {
246     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
247       switch (Op) {
248       case ISD::LOAD:
249       case ISD::STORE:
250       case ISD::BUILD_VECTOR:
251       case ISD::BITCAST:
252       case ISD::EXTRACT_VECTOR_ELT:
253       case ISD::INSERT_VECTOR_ELT:
254       case ISD::EXTRACT_SUBVECTOR:
255       case ISD::SCALAR_TO_VECTOR:
256         break;
257       case ISD::INSERT_SUBVECTOR:
258       case ISD::CONCAT_VECTORS:
259         setOperationAction(Op, VT, Custom);
260         break;
261       default:
262         setOperationAction(Op, VT, Expand);
263         break;
264       }
265     }
266   }
267 
268   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
269 
270   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
271   // is expanded to avoid having two separate loops in case the index is a VGPR.
272 
273   // Most operations are naturally 32-bit vector operations. We only support
274   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
275   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
276     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
277     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
278 
279     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
280     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
281 
282     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
283     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
284 
285     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
286     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
287   }
288 
289   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
290     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
291     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
292 
293     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
294     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
295 
296     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
297     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
298 
299     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
300     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
301   }
302 
303   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
304     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
305     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
306 
307     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
308     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
309 
310     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
312 
313     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
314     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
315   }
316 
317   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
318     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
319     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
320 
321     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
322     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
323 
324     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
326 
327     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
328     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
329   }
330 
331   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
332     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
333     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
334 
335     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
336     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
337 
338     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
339     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
340 
341     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
342     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
343   }
344 
345   setOperationAction(ISD::VECTOR_SHUFFLE,
346                      {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
347                      Expand);
348 
349   setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
350 
351   // Avoid stack access for these.
352   // TODO: Generalize to more vector types.
353   setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
354                      {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
355                       MVT::v4i16, MVT::v4f16},
356                      Custom);
357 
358   // Deal with vec3 vector operations when widened to vec4.
359   setOperationAction(ISD::INSERT_SUBVECTOR,
360                      {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
361 
362   // Deal with vec5/6/7 vector operations when widened to vec8.
363   setOperationAction(ISD::INSERT_SUBVECTOR,
364                      {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
365                       MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32},
366                      Custom);
367 
368   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
369   // and output demarshalling
370   setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
371 
372   // We can't return success/failure, only the old value,
373   // let LLVM add the comparison
374   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
375                      Expand);
376 
377   if (Subtarget->hasFlatAddressSpace())
378     setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
379 
380   setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
381 
382   // FIXME: This should be narrowed to i32, but that only happens if i64 is
383   // illegal.
384   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
385   setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
386 
387   // On SI this is s_memtime and s_memrealtime on VI.
388   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
389   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
390 
391   if (Subtarget->has16BitInsts()) {
392     setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
393     setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
394   }
395 
396   if (Subtarget->hasMadMacF32Insts())
397     setOperationAction(ISD::FMAD, MVT::f32, Legal);
398 
399   if (!Subtarget->hasBFI())
400     // fcopysign can be done in a single instruction with BFI.
401     setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
402 
403   if (!Subtarget->hasBCNT(32))
404     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
405 
406   if (!Subtarget->hasBCNT(64))
407     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
408 
409   if (Subtarget->hasFFBH())
410     setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
411 
412   if (Subtarget->hasFFBL())
413     setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
414 
415   // We only really have 32-bit BFE instructions (and 16-bit on VI).
416   //
417   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
418   // effort to match them now. We want this to be false for i64 cases when the
419   // extraction isn't restricted to the upper or lower half. Ideally we would
420   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
421   // span the midpoint are probably relatively rare, so don't worry about them
422   // for now.
423   if (Subtarget->hasBFE())
424     setHasExtractBitsInsn(true);
425 
426   // Clamp modifier on add/sub
427   if (Subtarget->hasIntClamp())
428     setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
429 
430   if (Subtarget->hasAddNoCarry())
431     setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
432                        Legal);
433 
434   setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
435                      Custom);
436 
437   // These are really only legal for ieee_mode functions. We should be avoiding
438   // them for functions that don't have ieee_mode enabled, so just say they are
439   // legal.
440   setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
441                      {MVT::f32, MVT::f64}, Legal);
442 
443   if (Subtarget->haveRoundOpsF64())
444     setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal);
445   else
446     setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR},
447                        MVT::f64, Custom);
448 
449   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
450 
451   setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
452   setOperationAction(ISD::FDIV, MVT::f64, Custom);
453 
454   if (Subtarget->has16BitInsts()) {
455     setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
456                         ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
457                        MVT::i16, Legal);
458 
459     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
460 
461     setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
462                        MVT::i16, Expand);
463 
464     setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
465                         ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
466                         ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
467                         ISD::CTPOP},
468                        MVT::i16, Promote);
469 
470     setOperationAction(ISD::LOAD, MVT::i16, Custom);
471 
472     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
473 
474     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
475     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
476     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
477     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
478 
479     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
480 
481     // F16 - Constant Actions.
482     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
483 
484     // F16 - Load/Store Actions.
485     setOperationAction(ISD::LOAD, MVT::f16, Promote);
486     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
487     setOperationAction(ISD::STORE, MVT::f16, Promote);
488     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
489 
490     // F16 - VOP1 Actions.
491     setOperationAction(
492         {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
493         MVT::f16, Custom);
494 
495     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
496 
497     setOperationAction(
498         {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP},
499         MVT::f16, Promote);
500 
501     // F16 - VOP2 Actions.
502     setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand);
503 
504     setOperationAction(ISD::FDIV, MVT::f16, Custom);
505 
506     // F16 - VOP3 Actions.
507     setOperationAction(ISD::FMA, MVT::f16, Legal);
508     if (STI.hasMadF16())
509       setOperationAction(ISD::FMAD, MVT::f16, Legal);
510 
511     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
512                    MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
513       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
514         switch (Op) {
515         case ISD::LOAD:
516         case ISD::STORE:
517         case ISD::BUILD_VECTOR:
518         case ISD::BITCAST:
519         case ISD::EXTRACT_VECTOR_ELT:
520         case ISD::INSERT_VECTOR_ELT:
521         case ISD::INSERT_SUBVECTOR:
522         case ISD::EXTRACT_SUBVECTOR:
523         case ISD::SCALAR_TO_VECTOR:
524           break;
525         case ISD::CONCAT_VECTORS:
526           setOperationAction(Op, VT, Custom);
527           break;
528         default:
529           setOperationAction(Op, VT, Expand);
530           break;
531         }
532       }
533     }
534 
535     // v_perm_b32 can handle either of these.
536     setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
537     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
538 
539     // XXX - Do these do anything? Vector constants turn into build_vector.
540     setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
541 
542     setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
543 
544     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
545     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
546     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
547     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
548 
549     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
550     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
551     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
552     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
553 
554     setOperationAction(ISD::AND, MVT::v2i16, Promote);
555     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
556     setOperationAction(ISD::OR, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
558     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
559     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
560 
561     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
562     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
563     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
564     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
565 
566     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
568     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
569     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
570 
571     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
573     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
574     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
575 
576     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
577     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
578     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
579     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
580 
581     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
582     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
583     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
584     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
585 
586     setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
588     setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
590 
591     setOperationAction(ISD::STORE, MVT::v16i16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
593     setOperationAction(ISD::STORE, MVT::v16f16, Promote);
594     AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
595 
596     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
597                        MVT::v2i32, Expand);
598     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
599 
600     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
601                        MVT::v4i32, Expand);
602 
603     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
604                        MVT::v8i32, Expand);
605 
606     if (!Subtarget->hasVOP3PInsts())
607       setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
608 
609     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
610     // This isn't really legal, but this avoids the legalizer unrolling it (and
611     // allows matching fneg (fabs x) patterns)
612     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
613 
614     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
615     setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
616 
617     setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
618                        {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Custom);
619 
620     setOperationAction({ISD::FMINNUM, ISD::FMAXNUM},
621                        {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Expand);
622 
623     for (MVT Vec16 : {MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
624       setOperationAction(
625           {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
626           Vec16, Custom);
627       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
628     }
629   }
630 
631   if (Subtarget->hasVOP3PInsts()) {
632     setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
633                         ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
634                         ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
635                        MVT::v2i16, Legal);
636 
637     setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
638                         ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
639                        MVT::v2f16, Legal);
640 
641     setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
642                        Custom);
643 
644     setOperationAction(ISD::VECTOR_SHUFFLE,
645                        {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16,
646                         MVT::v16f16, MVT::v16i16},
647                        Custom);
648 
649     for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16})
650       // Split vector operations.
651       setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
652                           ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
653                           ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
654                           ISD::SSUBSAT},
655                          VT, Custom);
656 
657     for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16})
658       // Split vector operations.
659       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
660                          VT, Custom);
661 
662     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
663                        Custom);
664 
665     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
666     setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
667 
668     if (Subtarget->hasPackedFP32Ops()) {
669       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
670                          MVT::v2f32, Legal);
671       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
672                          {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
673                          Custom);
674     }
675   }
676 
677   setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
678 
679   if (Subtarget->has16BitInsts()) {
680     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
681     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
682     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
683     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
684   } else {
685     // Legalization hack.
686     setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
687 
688     setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
689   }
690 
691   setOperationAction(ISD::SELECT,
692                      {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
693                       MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16},
694                      Custom);
695 
696   setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
697 
698   if (Subtarget->hasMad64_32())
699     setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
700 
701   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
702                      {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
703                       MVT::v2i16, MVT::v2f16},
704                      Custom);
705 
706   setOperationAction(ISD::INTRINSIC_W_CHAIN,
707                      {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
708                       MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
709                       MVT::i16, MVT::i8},
710                      Custom);
711 
712   setOperationAction(ISD::INTRINSIC_VOID,
713                      {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
714                       MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
715                       MVT::i8},
716                      Custom);
717 
718   setTargetDAGCombine({ISD::ADD,
719                        ISD::ADDCARRY,
720                        ISD::SUB,
721                        ISD::SUBCARRY,
722                        ISD::FADD,
723                        ISD::FSUB,
724                        ISD::FMINNUM,
725                        ISD::FMAXNUM,
726                        ISD::FMINNUM_IEEE,
727                        ISD::FMAXNUM_IEEE,
728                        ISD::FMA,
729                        ISD::SMIN,
730                        ISD::SMAX,
731                        ISD::UMIN,
732                        ISD::UMAX,
733                        ISD::SETCC,
734                        ISD::AND,
735                        ISD::OR,
736                        ISD::XOR,
737                        ISD::SINT_TO_FP,
738                        ISD::UINT_TO_FP,
739                        ISD::FCANONICALIZE,
740                        ISD::SCALAR_TO_VECTOR,
741                        ISD::ZERO_EXTEND,
742                        ISD::SIGN_EXTEND_INREG,
743                        ISD::EXTRACT_VECTOR_ELT,
744                        ISD::INSERT_VECTOR_ELT});
745 
746   // All memory operations. Some folding on the pointer operand is done to help
747   // matching the constant offsets in the addressing modes.
748   setTargetDAGCombine({ISD::LOAD,
749                        ISD::STORE,
750                        ISD::ATOMIC_LOAD,
751                        ISD::ATOMIC_STORE,
752                        ISD::ATOMIC_CMP_SWAP,
753                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
754                        ISD::ATOMIC_SWAP,
755                        ISD::ATOMIC_LOAD_ADD,
756                        ISD::ATOMIC_LOAD_SUB,
757                        ISD::ATOMIC_LOAD_AND,
758                        ISD::ATOMIC_LOAD_OR,
759                        ISD::ATOMIC_LOAD_XOR,
760                        ISD::ATOMIC_LOAD_NAND,
761                        ISD::ATOMIC_LOAD_MIN,
762                        ISD::ATOMIC_LOAD_MAX,
763                        ISD::ATOMIC_LOAD_UMIN,
764                        ISD::ATOMIC_LOAD_UMAX,
765                        ISD::ATOMIC_LOAD_FADD,
766                        ISD::INTRINSIC_VOID,
767                        ISD::INTRINSIC_W_CHAIN});
768 
769   // FIXME: In other contexts we pretend this is a per-function property.
770   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
771 
772   setSchedulingPreference(Sched::RegPressure);
773 }
774 
775 const GCNSubtarget *SITargetLowering::getSubtarget() const {
776   return Subtarget;
777 }
778 
779 //===----------------------------------------------------------------------===//
780 // TargetLowering queries
781 //===----------------------------------------------------------------------===//
782 
783 // v_mad_mix* support a conversion from f16 to f32.
784 //
785 // There is only one special case when denormals are enabled we don't currently,
786 // where this is OK to use.
787 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
788                                        EVT DestVT, EVT SrcVT) const {
789   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
790           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
791     DestVT.getScalarType() == MVT::f32 &&
792     SrcVT.getScalarType() == MVT::f16 &&
793     // TODO: This probably only requires no input flushing?
794     !hasFP32Denormals(DAG.getMachineFunction());
795 }
796 
797 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
798                                        LLT DestTy, LLT SrcTy) const {
799   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
800           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
801          DestTy.getScalarSizeInBits() == 32 &&
802          SrcTy.getScalarSizeInBits() == 16 &&
803          // TODO: This probably only requires no input flushing?
804          !hasFP32Denormals(*MI.getMF());
805 }
806 
807 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
808   // SI has some legal vector types, but no legal vector operations. Say no
809   // shuffles are legal in order to prefer scalarizing some vector operations.
810   return false;
811 }
812 
813 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
814                                                     CallingConv::ID CC,
815                                                     EVT VT) const {
816   if (CC == CallingConv::AMDGPU_KERNEL)
817     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
818 
819   if (VT.isVector()) {
820     EVT ScalarVT = VT.getScalarType();
821     unsigned Size = ScalarVT.getSizeInBits();
822     if (Size == 16) {
823       if (Subtarget->has16BitInsts())
824         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
825       return VT.isInteger() ? MVT::i32 : MVT::f32;
826     }
827 
828     if (Size < 16)
829       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
830     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
831   }
832 
833   if (VT.getSizeInBits() > 32)
834     return MVT::i32;
835 
836   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
837 }
838 
839 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
840                                                          CallingConv::ID CC,
841                                                          EVT VT) const {
842   if (CC == CallingConv::AMDGPU_KERNEL)
843     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
844 
845   if (VT.isVector()) {
846     unsigned NumElts = VT.getVectorNumElements();
847     EVT ScalarVT = VT.getScalarType();
848     unsigned Size = ScalarVT.getSizeInBits();
849 
850     // FIXME: Should probably promote 8-bit vectors to i16.
851     if (Size == 16 && Subtarget->has16BitInsts())
852       return (NumElts + 1) / 2;
853 
854     if (Size <= 32)
855       return NumElts;
856 
857     if (Size > 32)
858       return NumElts * ((Size + 31) / 32);
859   } else if (VT.getSizeInBits() > 32)
860     return (VT.getSizeInBits() + 31) / 32;
861 
862   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
863 }
864 
865 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
866   LLVMContext &Context, CallingConv::ID CC,
867   EVT VT, EVT &IntermediateVT,
868   unsigned &NumIntermediates, MVT &RegisterVT) const {
869   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
870     unsigned NumElts = VT.getVectorNumElements();
871     EVT ScalarVT = VT.getScalarType();
872     unsigned Size = ScalarVT.getSizeInBits();
873     // FIXME: We should fix the ABI to be the same on targets without 16-bit
874     // support, but unless we can properly handle 3-vectors, it will be still be
875     // inconsistent.
876     if (Size == 16 && Subtarget->has16BitInsts()) {
877       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
878       IntermediateVT = RegisterVT;
879       NumIntermediates = (NumElts + 1) / 2;
880       return NumIntermediates;
881     }
882 
883     if (Size == 32) {
884       RegisterVT = ScalarVT.getSimpleVT();
885       IntermediateVT = RegisterVT;
886       NumIntermediates = NumElts;
887       return NumIntermediates;
888     }
889 
890     if (Size < 16 && Subtarget->has16BitInsts()) {
891       // FIXME: Should probably form v2i16 pieces
892       RegisterVT = MVT::i16;
893       IntermediateVT = ScalarVT;
894       NumIntermediates = NumElts;
895       return NumIntermediates;
896     }
897 
898 
899     if (Size != 16 && Size <= 32) {
900       RegisterVT = MVT::i32;
901       IntermediateVT = ScalarVT;
902       NumIntermediates = NumElts;
903       return NumIntermediates;
904     }
905 
906     if (Size > 32) {
907       RegisterVT = MVT::i32;
908       IntermediateVT = RegisterVT;
909       NumIntermediates = NumElts * ((Size + 31) / 32);
910       return NumIntermediates;
911     }
912   }
913 
914   return TargetLowering::getVectorTypeBreakdownForCallingConv(
915     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
916 }
917 
918 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
919   assert(DMaskLanes != 0);
920 
921   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
922     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
923     return EVT::getVectorVT(Ty->getContext(),
924                             EVT::getEVT(VT->getElementType()),
925                             NumElts);
926   }
927 
928   return EVT::getEVT(Ty);
929 }
930 
931 // Peek through TFE struct returns to only use the data size.
932 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
933   auto *ST = dyn_cast<StructType>(Ty);
934   if (!ST)
935     return memVTFromImageData(Ty, DMaskLanes);
936 
937   // Some intrinsics return an aggregate type - special case to work out the
938   // correct memVT.
939   //
940   // Only limited forms of aggregate type currently expected.
941   if (ST->getNumContainedTypes() != 2 ||
942       !ST->getContainedType(1)->isIntegerTy(32))
943     return EVT();
944   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
945 }
946 
947 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
948                                           const CallInst &CI,
949                                           MachineFunction &MF,
950                                           unsigned IntrID) const {
951   Info.flags = MachineMemOperand::MONone;
952   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
953     Info.flags |= MachineMemOperand::MOInvariant;
954 
955   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
956           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
957     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
958                                                   (Intrinsic::ID)IntrID);
959     if (Attr.hasFnAttr(Attribute::ReadNone))
960       return false;
961 
962     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
963 
964     const GCNTargetMachine &TM =
965         static_cast<const GCNTargetMachine &>(getTargetMachine());
966 
967     if (RsrcIntr->IsImage) {
968       Info.ptrVal = MFI->getImagePSV(TM);
969       Info.align.reset();
970     } else {
971       Info.ptrVal = MFI->getBufferPSV(TM);
972     }
973 
974     Info.flags |= MachineMemOperand::MODereferenceable;
975     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
976       unsigned DMaskLanes = 4;
977 
978       if (RsrcIntr->IsImage) {
979         const AMDGPU::ImageDimIntrinsicInfo *Intr
980           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
981         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
982           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
983 
984         if (!BaseOpcode->Gather4) {
985           // If this isn't a gather, we may have excess loaded elements in the
986           // IR type. Check the dmask for the real number of elements loaded.
987           unsigned DMask
988             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
989           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
990         }
991 
992         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
993       } else
994         Info.memVT = EVT::getEVT(CI.getType());
995 
996       // FIXME: What does alignment mean for an image?
997       Info.opc = ISD::INTRINSIC_W_CHAIN;
998       Info.flags |= MachineMemOperand::MOLoad;
999     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1000       Info.opc = ISD::INTRINSIC_VOID;
1001 
1002       Type *DataTy = CI.getArgOperand(0)->getType();
1003       if (RsrcIntr->IsImage) {
1004         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1005         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1006         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1007       } else
1008         Info.memVT = EVT::getEVT(DataTy);
1009 
1010       Info.flags |= MachineMemOperand::MOStore;
1011     } else {
1012       // Atomic
1013       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1014                                             ISD::INTRINSIC_W_CHAIN;
1015       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1016       Info.flags |= MachineMemOperand::MOLoad |
1017                     MachineMemOperand::MOStore |
1018                     MachineMemOperand::MODereferenceable;
1019 
1020       // XXX - Should this be volatile without known ordering?
1021       Info.flags |= MachineMemOperand::MOVolatile;
1022 
1023       switch (IntrID) {
1024       default:
1025         break;
1026       case Intrinsic::amdgcn_raw_buffer_load_lds:
1027       case Intrinsic::amdgcn_struct_buffer_load_lds: {
1028         unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1029         Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1030         return true;
1031       }
1032       }
1033     }
1034     return true;
1035   }
1036 
1037   switch (IntrID) {
1038   case Intrinsic::amdgcn_atomic_inc:
1039   case Intrinsic::amdgcn_atomic_dec:
1040   case Intrinsic::amdgcn_ds_ordered_add:
1041   case Intrinsic::amdgcn_ds_ordered_swap:
1042   case Intrinsic::amdgcn_ds_fadd:
1043   case Intrinsic::amdgcn_ds_fmin:
1044   case Intrinsic::amdgcn_ds_fmax: {
1045     Info.opc = ISD::INTRINSIC_W_CHAIN;
1046     Info.memVT = MVT::getVT(CI.getType());
1047     Info.ptrVal = CI.getOperand(0);
1048     Info.align.reset();
1049     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1050 
1051     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1052     if (!Vol->isZero())
1053       Info.flags |= MachineMemOperand::MOVolatile;
1054 
1055     return true;
1056   }
1057   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1058     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1059 
1060     const GCNTargetMachine &TM =
1061         static_cast<const GCNTargetMachine &>(getTargetMachine());
1062 
1063     Info.opc = ISD::INTRINSIC_W_CHAIN;
1064     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1065     Info.ptrVal = MFI->getBufferPSV(TM);
1066     Info.align.reset();
1067     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1068 
1069     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1070     if (!Vol || !Vol->isZero())
1071       Info.flags |= MachineMemOperand::MOVolatile;
1072 
1073     return true;
1074   }
1075   case Intrinsic::amdgcn_ds_append:
1076   case Intrinsic::amdgcn_ds_consume: {
1077     Info.opc = ISD::INTRINSIC_W_CHAIN;
1078     Info.memVT = MVT::getVT(CI.getType());
1079     Info.ptrVal = CI.getOperand(0);
1080     Info.align.reset();
1081     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1082 
1083     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1084     if (!Vol->isZero())
1085       Info.flags |= MachineMemOperand::MOVolatile;
1086 
1087     return true;
1088   }
1089   case Intrinsic::amdgcn_global_atomic_csub: {
1090     Info.opc = ISD::INTRINSIC_W_CHAIN;
1091     Info.memVT = MVT::getVT(CI.getType());
1092     Info.ptrVal = CI.getOperand(0);
1093     Info.align.reset();
1094     Info.flags |= MachineMemOperand::MOLoad |
1095                   MachineMemOperand::MOStore |
1096                   MachineMemOperand::MOVolatile;
1097     return true;
1098   }
1099   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1100     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1101     Info.opc = ISD::INTRINSIC_W_CHAIN;
1102     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1103 
1104     const GCNTargetMachine &TM =
1105         static_cast<const GCNTargetMachine &>(getTargetMachine());
1106 
1107     Info.ptrVal = MFI->getImagePSV(TM);
1108     Info.align.reset();
1109     Info.flags |= MachineMemOperand::MOLoad |
1110                   MachineMemOperand::MODereferenceable;
1111     return true;
1112   }
1113   case Intrinsic::amdgcn_global_atomic_fadd:
1114   case Intrinsic::amdgcn_global_atomic_fmin:
1115   case Intrinsic::amdgcn_global_atomic_fmax:
1116   case Intrinsic::amdgcn_flat_atomic_fadd:
1117   case Intrinsic::amdgcn_flat_atomic_fmin:
1118   case Intrinsic::amdgcn_flat_atomic_fmax:
1119   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1120   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1121     Info.opc = ISD::INTRINSIC_W_CHAIN;
1122     Info.memVT = MVT::getVT(CI.getType());
1123     Info.ptrVal = CI.getOperand(0);
1124     Info.align.reset();
1125     Info.flags |= MachineMemOperand::MOLoad |
1126                   MachineMemOperand::MOStore |
1127                   MachineMemOperand::MODereferenceable |
1128                   MachineMemOperand::MOVolatile;
1129     return true;
1130   }
1131   case Intrinsic::amdgcn_ds_gws_init:
1132   case Intrinsic::amdgcn_ds_gws_barrier:
1133   case Intrinsic::amdgcn_ds_gws_sema_v:
1134   case Intrinsic::amdgcn_ds_gws_sema_br:
1135   case Intrinsic::amdgcn_ds_gws_sema_p:
1136   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1137     Info.opc = ISD::INTRINSIC_VOID;
1138 
1139     const GCNTargetMachine &TM =
1140         static_cast<const GCNTargetMachine &>(getTargetMachine());
1141 
1142     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1143     Info.ptrVal = MFI->getGWSPSV(TM);
1144 
1145     // This is an abstract access, but we need to specify a type and size.
1146     Info.memVT = MVT::i32;
1147     Info.size = 4;
1148     Info.align = Align(4);
1149 
1150     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1151       Info.flags |= MachineMemOperand::MOLoad;
1152     else
1153       Info.flags |= MachineMemOperand::MOStore;
1154     return true;
1155   }
1156   case Intrinsic::amdgcn_global_load_lds: {
1157     Info.opc = ISD::INTRINSIC_VOID;
1158     unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1159     Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1160     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1161                   MachineMemOperand::MOVolatile;
1162     return true;
1163   }
1164   default:
1165     return false;
1166   }
1167 }
1168 
1169 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1170                                             SmallVectorImpl<Value*> &Ops,
1171                                             Type *&AccessTy) const {
1172   switch (II->getIntrinsicID()) {
1173   case Intrinsic::amdgcn_atomic_inc:
1174   case Intrinsic::amdgcn_atomic_dec:
1175   case Intrinsic::amdgcn_ds_ordered_add:
1176   case Intrinsic::amdgcn_ds_ordered_swap:
1177   case Intrinsic::amdgcn_ds_append:
1178   case Intrinsic::amdgcn_ds_consume:
1179   case Intrinsic::amdgcn_ds_fadd:
1180   case Intrinsic::amdgcn_ds_fmin:
1181   case Intrinsic::amdgcn_ds_fmax:
1182   case Intrinsic::amdgcn_global_atomic_fadd:
1183   case Intrinsic::amdgcn_flat_atomic_fadd:
1184   case Intrinsic::amdgcn_flat_atomic_fmin:
1185   case Intrinsic::amdgcn_flat_atomic_fmax:
1186   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1187   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1188   case Intrinsic::amdgcn_global_atomic_csub: {
1189     Value *Ptr = II->getArgOperand(0);
1190     AccessTy = II->getType();
1191     Ops.push_back(Ptr);
1192     return true;
1193   }
1194   default:
1195     return false;
1196   }
1197 }
1198 
1199 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1200   if (!Subtarget->hasFlatInstOffsets()) {
1201     // Flat instructions do not have offsets, and only have the register
1202     // address.
1203     return AM.BaseOffs == 0 && AM.Scale == 0;
1204   }
1205 
1206   return AM.Scale == 0 &&
1207          (AM.BaseOffs == 0 ||
1208           Subtarget->getInstrInfo()->isLegalFLATOffset(
1209               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1210 }
1211 
1212 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1213   if (Subtarget->hasFlatGlobalInsts())
1214     return AM.Scale == 0 &&
1215            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1216                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1217                                     SIInstrFlags::FlatGlobal));
1218 
1219   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1220       // Assume the we will use FLAT for all global memory accesses
1221       // on VI.
1222       // FIXME: This assumption is currently wrong.  On VI we still use
1223       // MUBUF instructions for the r + i addressing mode.  As currently
1224       // implemented, the MUBUF instructions only work on buffer < 4GB.
1225       // It may be possible to support > 4GB buffers with MUBUF instructions,
1226       // by setting the stride value in the resource descriptor which would
1227       // increase the size limit to (stride * 4GB).  However, this is risky,
1228       // because it has never been validated.
1229     return isLegalFlatAddressingMode(AM);
1230   }
1231 
1232   return isLegalMUBUFAddressingMode(AM);
1233 }
1234 
1235 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1236   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1237   // additionally can do r + r + i with addr64. 32-bit has more addressing
1238   // mode options. Depending on the resource constant, it can also do
1239   // (i64 r0) + (i32 r1) * (i14 i).
1240   //
1241   // Private arrays end up using a scratch buffer most of the time, so also
1242   // assume those use MUBUF instructions. Scratch loads / stores are currently
1243   // implemented as mubuf instructions with offen bit set, so slightly
1244   // different than the normal addr64.
1245   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1246     return false;
1247 
1248   // FIXME: Since we can split immediate into soffset and immediate offset,
1249   // would it make sense to allow any immediate?
1250 
1251   switch (AM.Scale) {
1252   case 0: // r + i or just i, depending on HasBaseReg.
1253     return true;
1254   case 1:
1255     return true; // We have r + r or r + i.
1256   case 2:
1257     if (AM.HasBaseReg) {
1258       // Reject 2 * r + r.
1259       return false;
1260     }
1261 
1262     // Allow 2 * r as r + r
1263     // Or  2 * r + i is allowed as r + r + i.
1264     return true;
1265   default: // Don't allow n * r
1266     return false;
1267   }
1268 }
1269 
1270 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1271                                              const AddrMode &AM, Type *Ty,
1272                                              unsigned AS, Instruction *I) const {
1273   // No global is ever allowed as a base.
1274   if (AM.BaseGV)
1275     return false;
1276 
1277   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1278     return isLegalGlobalAddressingMode(AM);
1279 
1280   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1281       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1282       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1283     // If the offset isn't a multiple of 4, it probably isn't going to be
1284     // correctly aligned.
1285     // FIXME: Can we get the real alignment here?
1286     if (AM.BaseOffs % 4 != 0)
1287       return isLegalMUBUFAddressingMode(AM);
1288 
1289     // There are no SMRD extloads, so if we have to do a small type access we
1290     // will use a MUBUF load.
1291     // FIXME?: We also need to do this if unaligned, but we don't know the
1292     // alignment here.
1293     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1294       return isLegalGlobalAddressingMode(AM);
1295 
1296     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1297       // SMRD instructions have an 8-bit, dword offset on SI.
1298       if (!isUInt<8>(AM.BaseOffs / 4))
1299         return false;
1300     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1301       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1302       // in 8-bits, it can use a smaller encoding.
1303       if (!isUInt<32>(AM.BaseOffs / 4))
1304         return false;
1305     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1306       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1307       if (!isUInt<20>(AM.BaseOffs))
1308         return false;
1309     } else
1310       llvm_unreachable("unhandled generation");
1311 
1312     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1313       return true;
1314 
1315     if (AM.Scale == 1 && AM.HasBaseReg)
1316       return true;
1317 
1318     return false;
1319 
1320   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1321     return isLegalMUBUFAddressingMode(AM);
1322   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1323              AS == AMDGPUAS::REGION_ADDRESS) {
1324     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1325     // field.
1326     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1327     // an 8-bit dword offset but we don't know the alignment here.
1328     if (!isUInt<16>(AM.BaseOffs))
1329       return false;
1330 
1331     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1332       return true;
1333 
1334     if (AM.Scale == 1 && AM.HasBaseReg)
1335       return true;
1336 
1337     return false;
1338   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1339              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1340     // For an unknown address space, this usually means that this is for some
1341     // reason being used for pure arithmetic, and not based on some addressing
1342     // computation. We don't have instructions that compute pointers with any
1343     // addressing modes, so treat them as having no offset like flat
1344     // instructions.
1345     return isLegalFlatAddressingMode(AM);
1346   }
1347 
1348   // Assume a user alias of global for unknown address spaces.
1349   return isLegalGlobalAddressingMode(AM);
1350 }
1351 
1352 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1353                                         const MachineFunction &MF) const {
1354   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1355     return (MemVT.getSizeInBits() <= 4 * 32);
1356   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1357     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1358     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1359   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1360     return (MemVT.getSizeInBits() <= 2 * 32);
1361   }
1362   return true;
1363 }
1364 
1365 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1366     unsigned Size, unsigned AddrSpace, Align Alignment,
1367     MachineMemOperand::Flags Flags, bool *IsFast) const {
1368   if (IsFast)
1369     *IsFast = false;
1370 
1371   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1372       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1373     // Check if alignment requirements for ds_read/write instructions are
1374     // disabled.
1375     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1376       return false;
1377 
1378     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1379     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1380         Alignment < RequiredAlignment)
1381       return false;
1382 
1383     // Either, the alignment requirements are "enabled", or there is an
1384     // unaligned LDS access related hardware bug though alignment requirements
1385     // are "disabled". In either case, we need to check for proper alignment
1386     // requirements.
1387     //
1388     switch (Size) {
1389     case 64:
1390       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1391       // address is negative, then the instruction is incorrectly treated as
1392       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1393       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1394       // load later in the SILoadStoreOptimizer.
1395       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1396         return false;
1397 
1398       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1399       // can do a 4 byte aligned, 8 byte access in a single operation using
1400       // ds_read2/write2_b32 with adjacent offsets.
1401       RequiredAlignment = Align(4);
1402 
1403       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1404         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1405         // ds_write2_b32 depending on the alignment. In either case with either
1406         // alignment there is no faster way of doing this.
1407         if (IsFast)
1408           *IsFast = true;
1409         return true;
1410       }
1411 
1412       break;
1413     case 96:
1414       if (!Subtarget->hasDS96AndDS128())
1415         return false;
1416 
1417       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1418       // gfx8 and older.
1419 
1420       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1421         // Naturally aligned access is fastest. However, also report it is Fast
1422         // if memory is aligned less than DWORD. A narrow load or store will be
1423         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1424         // be more of them, so overall we will pay less penalty issuing a single
1425         // instruction.
1426         if (IsFast)
1427           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1428         return true;
1429       }
1430 
1431       break;
1432     case 128:
1433       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1434         return false;
1435 
1436       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1437       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1438       // single operation using ds_read2/write2_b64.
1439       RequiredAlignment = Align(8);
1440 
1441       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1442         // Naturally aligned access is fastest. However, also report it is Fast
1443         // if memory is aligned less than DWORD. A narrow load or store will be
1444         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1445         // will be more of them, so overall we will pay less penalty issuing a
1446         // single instruction.
1447         if (IsFast)
1448           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1449         return true;
1450       }
1451 
1452       break;
1453     default:
1454       if (Size > 32)
1455         return false;
1456 
1457       break;
1458     }
1459 
1460     if (IsFast)
1461       *IsFast = Alignment >= RequiredAlignment;
1462 
1463     return Alignment >= RequiredAlignment ||
1464            Subtarget->hasUnalignedDSAccessEnabled();
1465   }
1466 
1467   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1468     bool AlignedBy4 = Alignment >= Align(4);
1469     if (IsFast)
1470       *IsFast = AlignedBy4;
1471 
1472     return AlignedBy4 ||
1473            Subtarget->enableFlatScratch() ||
1474            Subtarget->hasUnalignedScratchAccess();
1475   }
1476 
1477   // FIXME: We have to be conservative here and assume that flat operations
1478   // will access scratch.  If we had access to the IR function, then we
1479   // could determine if any private memory was used in the function.
1480   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1481       !Subtarget->hasUnalignedScratchAccess()) {
1482     bool AlignedBy4 = Alignment >= Align(4);
1483     if (IsFast)
1484       *IsFast = AlignedBy4;
1485 
1486     return AlignedBy4;
1487   }
1488 
1489   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1490     // If we have a uniform constant load, it still requires using a slow
1491     // buffer instruction if unaligned.
1492     if (IsFast) {
1493       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1494       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1495       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1496                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1497         Alignment >= Align(4) : Alignment != Align(2);
1498     }
1499 
1500     return true;
1501   }
1502 
1503   // Smaller than dword value must be aligned.
1504   if (Size < 32)
1505     return false;
1506 
1507   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1508   // byte-address are ignored, thus forcing Dword alignment.
1509   // This applies to private, global, and constant memory.
1510   if (IsFast)
1511     *IsFast = true;
1512 
1513   return Size >= 32 && Alignment >= Align(4);
1514 }
1515 
1516 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1517     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1518     bool *IsFast) const {
1519   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1520                                                   Alignment, Flags, IsFast);
1521 
1522   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1523       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1524        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1525     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1526     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1527     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1528     // which would be equally misaligned.
1529     // This is only used by the common passes, selection always calls the
1530     // allowsMisalignedMemoryAccessesImpl version.
1531     *IsFast = true;
1532   }
1533 
1534   return Allow;
1535 }
1536 
1537 EVT SITargetLowering::getOptimalMemOpType(
1538     const MemOp &Op, const AttributeList &FuncAttributes) const {
1539   // FIXME: Should account for address space here.
1540 
1541   // The default fallback uses the private pointer size as a guess for a type to
1542   // use. Make sure we switch these to 64-bit accesses.
1543 
1544   if (Op.size() >= 16 &&
1545       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1546     return MVT::v4i32;
1547 
1548   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1549     return MVT::v2i32;
1550 
1551   // Use the default.
1552   return MVT::Other;
1553 }
1554 
1555 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1556   const MemSDNode *MemNode = cast<MemSDNode>(N);
1557   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1558 }
1559 
1560 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1561   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1562          AS == AMDGPUAS::PRIVATE_ADDRESS;
1563 }
1564 
1565 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1566                                            unsigned DestAS) const {
1567   // Flat -> private/local is a simple truncate.
1568   // Flat -> global is no-op
1569   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1570     return true;
1571 
1572   const GCNTargetMachine &TM =
1573       static_cast<const GCNTargetMachine &>(getTargetMachine());
1574   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1575 }
1576 
1577 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1578   const MemSDNode *MemNode = cast<MemSDNode>(N);
1579 
1580   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1581 }
1582 
1583 TargetLoweringBase::LegalizeTypeAction
1584 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1585   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1586       VT.getScalarType().bitsLE(MVT::i16))
1587     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1588   return TargetLoweringBase::getPreferredVectorAction(VT);
1589 }
1590 
1591 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1592                                                          Type *Ty) const {
1593   // FIXME: Could be smarter if called for vector constants.
1594   return true;
1595 }
1596 
1597 bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
1598                                                unsigned Index) const {
1599   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
1600     return false;
1601 
1602   // TODO: Add more cases that are cheap.
1603   return Index == 0;
1604 }
1605 
1606 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1607   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1608     switch (Op) {
1609     case ISD::LOAD:
1610     case ISD::STORE:
1611 
1612     // These operations are done with 32-bit instructions anyway.
1613     case ISD::AND:
1614     case ISD::OR:
1615     case ISD::XOR:
1616     case ISD::SELECT:
1617       // TODO: Extensions?
1618       return true;
1619     default:
1620       return false;
1621     }
1622   }
1623 
1624   // SimplifySetCC uses this function to determine whether or not it should
1625   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1626   if (VT == MVT::i1 && Op == ISD::SETCC)
1627     return false;
1628 
1629   return TargetLowering::isTypeDesirableForOp(Op, VT);
1630 }
1631 
1632 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1633                                                    const SDLoc &SL,
1634                                                    SDValue Chain,
1635                                                    uint64_t Offset) const {
1636   const DataLayout &DL = DAG.getDataLayout();
1637   MachineFunction &MF = DAG.getMachineFunction();
1638   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1639 
1640   const ArgDescriptor *InputPtrReg;
1641   const TargetRegisterClass *RC;
1642   LLT ArgTy;
1643   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1644 
1645   std::tie(InputPtrReg, RC, ArgTy) =
1646       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1647 
1648   // We may not have the kernarg segment argument if we have no kernel
1649   // arguments.
1650   if (!InputPtrReg)
1651     return DAG.getConstant(0, SL, PtrVT);
1652 
1653   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1654   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1655     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1656 
1657   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1658 }
1659 
1660 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1661                                             const SDLoc &SL) const {
1662   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1663                                                FIRST_IMPLICIT);
1664   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1665 }
1666 
1667 SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1668                                          const SDLoc &SL) const {
1669 
1670   Function &F = DAG.getMachineFunction().getFunction();
1671   Optional<uint32_t> KnownSize =
1672       AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
1673   if (KnownSize.has_value())
1674     return DAG.getConstant(KnownSize.value(), SL, MVT::i32);
1675   return SDValue();
1676 }
1677 
1678 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1679                                          const SDLoc &SL, SDValue Val,
1680                                          bool Signed,
1681                                          const ISD::InputArg *Arg) const {
1682   // First, if it is a widened vector, narrow it.
1683   if (VT.isVector() &&
1684       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1685     EVT NarrowedVT =
1686         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1687                          VT.getVectorNumElements());
1688     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1689                       DAG.getConstant(0, SL, MVT::i32));
1690   }
1691 
1692   // Then convert the vector elements or scalar value.
1693   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1694       VT.bitsLT(MemVT)) {
1695     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1696     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1697   }
1698 
1699   if (MemVT.isFloatingPoint())
1700     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1701   else if (Signed)
1702     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1703   else
1704     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1705 
1706   return Val;
1707 }
1708 
1709 SDValue SITargetLowering::lowerKernargMemParameter(
1710     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1711     uint64_t Offset, Align Alignment, bool Signed,
1712     const ISD::InputArg *Arg) const {
1713   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1714 
1715   // Try to avoid using an extload by loading earlier than the argument address,
1716   // and extracting the relevant bits. The load should hopefully be merged with
1717   // the previous argument.
1718   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1719     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1720     int64_t AlignDownOffset = alignDown(Offset, 4);
1721     int64_t OffsetDiff = Offset - AlignDownOffset;
1722 
1723     EVT IntVT = MemVT.changeTypeToInteger();
1724 
1725     // TODO: If we passed in the base kernel offset we could have a better
1726     // alignment than 4, but we don't really need it.
1727     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1728     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1729                                MachineMemOperand::MODereferenceable |
1730                                    MachineMemOperand::MOInvariant);
1731 
1732     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1733     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1734 
1735     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1736     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1737     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1738 
1739 
1740     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1741   }
1742 
1743   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1744   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1745                              MachineMemOperand::MODereferenceable |
1746                                  MachineMemOperand::MOInvariant);
1747 
1748   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1749   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1750 }
1751 
1752 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1753                                               const SDLoc &SL, SDValue Chain,
1754                                               const ISD::InputArg &Arg) const {
1755   MachineFunction &MF = DAG.getMachineFunction();
1756   MachineFrameInfo &MFI = MF.getFrameInfo();
1757 
1758   if (Arg.Flags.isByVal()) {
1759     unsigned Size = Arg.Flags.getByValSize();
1760     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1761     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1762   }
1763 
1764   unsigned ArgOffset = VA.getLocMemOffset();
1765   unsigned ArgSize = VA.getValVT().getStoreSize();
1766 
1767   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1768 
1769   // Create load nodes to retrieve arguments from the stack.
1770   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1771   SDValue ArgValue;
1772 
1773   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1774   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1775   MVT MemVT = VA.getValVT();
1776 
1777   switch (VA.getLocInfo()) {
1778   default:
1779     break;
1780   case CCValAssign::BCvt:
1781     MemVT = VA.getLocVT();
1782     break;
1783   case CCValAssign::SExt:
1784     ExtType = ISD::SEXTLOAD;
1785     break;
1786   case CCValAssign::ZExt:
1787     ExtType = ISD::ZEXTLOAD;
1788     break;
1789   case CCValAssign::AExt:
1790     ExtType = ISD::EXTLOAD;
1791     break;
1792   }
1793 
1794   ArgValue = DAG.getExtLoad(
1795     ExtType, SL, VA.getLocVT(), Chain, FIN,
1796     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1797     MemVT);
1798   return ArgValue;
1799 }
1800 
1801 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1802   const SIMachineFunctionInfo &MFI,
1803   EVT VT,
1804   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1805   const ArgDescriptor *Reg;
1806   const TargetRegisterClass *RC;
1807   LLT Ty;
1808 
1809   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1810   if (!Reg) {
1811     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1812       // It's possible for a kernarg intrinsic call to appear in a kernel with
1813       // no allocated segment, in which case we do not add the user sgpr
1814       // argument, so just return null.
1815       return DAG.getConstant(0, SDLoc(), VT);
1816     }
1817 
1818     // It's undefined behavior if a function marked with the amdgpu-no-*
1819     // attributes uses the corresponding intrinsic.
1820     return DAG.getUNDEF(VT);
1821   }
1822 
1823   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1824 }
1825 
1826 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1827                                CallingConv::ID CallConv,
1828                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1829                                FunctionType *FType,
1830                                SIMachineFunctionInfo *Info) {
1831   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1832     const ISD::InputArg *Arg = &Ins[I];
1833 
1834     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1835            "vector type argument should have been split");
1836 
1837     // First check if it's a PS input addr.
1838     if (CallConv == CallingConv::AMDGPU_PS &&
1839         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1840       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1841 
1842       // Inconveniently only the first part of the split is marked as isSplit,
1843       // so skip to the end. We only want to increment PSInputNum once for the
1844       // entire split argument.
1845       if (Arg->Flags.isSplit()) {
1846         while (!Arg->Flags.isSplitEnd()) {
1847           assert((!Arg->VT.isVector() ||
1848                   Arg->VT.getScalarSizeInBits() == 16) &&
1849                  "unexpected vector split in ps argument type");
1850           if (!SkipArg)
1851             Splits.push_back(*Arg);
1852           Arg = &Ins[++I];
1853         }
1854       }
1855 
1856       if (SkipArg) {
1857         // We can safely skip PS inputs.
1858         Skipped.set(Arg->getOrigArgIndex());
1859         ++PSInputNum;
1860         continue;
1861       }
1862 
1863       Info->markPSInputAllocated(PSInputNum);
1864       if (Arg->Used)
1865         Info->markPSInputEnabled(PSInputNum);
1866 
1867       ++PSInputNum;
1868     }
1869 
1870     Splits.push_back(*Arg);
1871   }
1872 }
1873 
1874 // Allocate special inputs passed in VGPRs.
1875 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1876                                                       MachineFunction &MF,
1877                                                       const SIRegisterInfo &TRI,
1878                                                       SIMachineFunctionInfo &Info) const {
1879   const LLT S32 = LLT::scalar(32);
1880   MachineRegisterInfo &MRI = MF.getRegInfo();
1881 
1882   if (Info.hasWorkItemIDX()) {
1883     Register Reg = AMDGPU::VGPR0;
1884     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1885 
1886     CCInfo.AllocateReg(Reg);
1887     unsigned Mask = (Subtarget->hasPackedTID() &&
1888                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1889     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1890   }
1891 
1892   if (Info.hasWorkItemIDY()) {
1893     assert(Info.hasWorkItemIDX());
1894     if (Subtarget->hasPackedTID()) {
1895       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1896                                                         0x3ff << 10));
1897     } else {
1898       unsigned Reg = AMDGPU::VGPR1;
1899       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1900 
1901       CCInfo.AllocateReg(Reg);
1902       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1903     }
1904   }
1905 
1906   if (Info.hasWorkItemIDZ()) {
1907     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1908     if (Subtarget->hasPackedTID()) {
1909       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1910                                                         0x3ff << 20));
1911     } else {
1912       unsigned Reg = AMDGPU::VGPR2;
1913       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1914 
1915       CCInfo.AllocateReg(Reg);
1916       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1917     }
1918   }
1919 }
1920 
1921 // Try to allocate a VGPR at the end of the argument list, or if no argument
1922 // VGPRs are left allocating a stack slot.
1923 // If \p Mask is is given it indicates bitfield position in the register.
1924 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1925 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1926                                          ArgDescriptor Arg = ArgDescriptor()) {
1927   if (Arg.isSet())
1928     return ArgDescriptor::createArg(Arg, Mask);
1929 
1930   ArrayRef<MCPhysReg> ArgVGPRs
1931     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1932   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1933   if (RegIdx == ArgVGPRs.size()) {
1934     // Spill to stack required.
1935     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1936 
1937     return ArgDescriptor::createStack(Offset, Mask);
1938   }
1939 
1940   unsigned Reg = ArgVGPRs[RegIdx];
1941   Reg = CCInfo.AllocateReg(Reg);
1942   assert(Reg != AMDGPU::NoRegister);
1943 
1944   MachineFunction &MF = CCInfo.getMachineFunction();
1945   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1946   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1947   return ArgDescriptor::createRegister(Reg, Mask);
1948 }
1949 
1950 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1951                                              const TargetRegisterClass *RC,
1952                                              unsigned NumArgRegs) {
1953   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1954   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1955   if (RegIdx == ArgSGPRs.size())
1956     report_fatal_error("ran out of SGPRs for arguments");
1957 
1958   unsigned Reg = ArgSGPRs[RegIdx];
1959   Reg = CCInfo.AllocateReg(Reg);
1960   assert(Reg != AMDGPU::NoRegister);
1961 
1962   MachineFunction &MF = CCInfo.getMachineFunction();
1963   MF.addLiveIn(Reg, RC);
1964   return ArgDescriptor::createRegister(Reg);
1965 }
1966 
1967 // If this has a fixed position, we still should allocate the register in the
1968 // CCInfo state. Technically we could get away with this for values passed
1969 // outside of the normal argument range.
1970 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1971                                        const TargetRegisterClass *RC,
1972                                        MCRegister Reg) {
1973   Reg = CCInfo.AllocateReg(Reg);
1974   assert(Reg != AMDGPU::NoRegister);
1975   MachineFunction &MF = CCInfo.getMachineFunction();
1976   MF.addLiveIn(Reg, RC);
1977 }
1978 
1979 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1980   if (Arg) {
1981     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1982                                Arg.getRegister());
1983   } else
1984     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1985 }
1986 
1987 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1988   if (Arg) {
1989     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1990                                Arg.getRegister());
1991   } else
1992     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1993 }
1994 
1995 /// Allocate implicit function VGPR arguments at the end of allocated user
1996 /// arguments.
1997 void SITargetLowering::allocateSpecialInputVGPRs(
1998   CCState &CCInfo, MachineFunction &MF,
1999   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2000   const unsigned Mask = 0x3ff;
2001   ArgDescriptor Arg;
2002 
2003   if (Info.hasWorkItemIDX()) {
2004     Arg = allocateVGPR32Input(CCInfo, Mask);
2005     Info.setWorkItemIDX(Arg);
2006   }
2007 
2008   if (Info.hasWorkItemIDY()) {
2009     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2010     Info.setWorkItemIDY(Arg);
2011   }
2012 
2013   if (Info.hasWorkItemIDZ())
2014     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2015 }
2016 
2017 /// Allocate implicit function VGPR arguments in fixed registers.
2018 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2019   CCState &CCInfo, MachineFunction &MF,
2020   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2021   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2022   if (!Reg)
2023     report_fatal_error("failed to allocated VGPR for implicit arguments");
2024 
2025   const unsigned Mask = 0x3ff;
2026   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2027   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2028   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2029 }
2030 
2031 void SITargetLowering::allocateSpecialInputSGPRs(
2032   CCState &CCInfo,
2033   MachineFunction &MF,
2034   const SIRegisterInfo &TRI,
2035   SIMachineFunctionInfo &Info) const {
2036   auto &ArgInfo = Info.getArgInfo();
2037 
2038   // TODO: Unify handling with private memory pointers.
2039   if (Info.hasDispatchPtr())
2040     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2041 
2042   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2043     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2044 
2045   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2046   // constant offset from the kernarg segment.
2047   if (Info.hasImplicitArgPtr())
2048     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2049 
2050   if (Info.hasDispatchID())
2051     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2052 
2053   // flat_scratch_init is not applicable for non-kernel functions.
2054 
2055   if (Info.hasWorkGroupIDX())
2056     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2057 
2058   if (Info.hasWorkGroupIDY())
2059     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2060 
2061   if (Info.hasWorkGroupIDZ())
2062     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2063 
2064   if (Info.hasLDSKernelId())
2065     allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2066 }
2067 
2068 // Allocate special inputs passed in user SGPRs.
2069 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2070                                             MachineFunction &MF,
2071                                             const SIRegisterInfo &TRI,
2072                                             SIMachineFunctionInfo &Info) const {
2073   if (Info.hasImplicitBufferPtr()) {
2074     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2075     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2076     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2077   }
2078 
2079   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2080   if (Info.hasPrivateSegmentBuffer()) {
2081     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2082     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2083     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2084   }
2085 
2086   if (Info.hasDispatchPtr()) {
2087     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2088     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2089     CCInfo.AllocateReg(DispatchPtrReg);
2090   }
2091 
2092   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2093     Register QueuePtrReg = Info.addQueuePtr(TRI);
2094     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2095     CCInfo.AllocateReg(QueuePtrReg);
2096   }
2097 
2098   if (Info.hasKernargSegmentPtr()) {
2099     MachineRegisterInfo &MRI = MF.getRegInfo();
2100     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2101     CCInfo.AllocateReg(InputPtrReg);
2102 
2103     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2104     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2105   }
2106 
2107   if (Info.hasDispatchID()) {
2108     Register DispatchIDReg = Info.addDispatchID(TRI);
2109     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2110     CCInfo.AllocateReg(DispatchIDReg);
2111   }
2112 
2113   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2114     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2115     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2116     CCInfo.AllocateReg(FlatScratchInitReg);
2117   }
2118 
2119   if (Info.hasLDSKernelId()) {
2120     Register Reg = Info.addLDSKernelId();
2121     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2122     CCInfo.AllocateReg(Reg);
2123   }
2124 
2125   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2126   // these from the dispatch pointer.
2127 }
2128 
2129 // Allocate special input registers that are initialized per-wave.
2130 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2131                                            MachineFunction &MF,
2132                                            SIMachineFunctionInfo &Info,
2133                                            CallingConv::ID CallConv,
2134                                            bool IsShader) const {
2135   if (Subtarget->hasUserSGPRInit16Bug()) {
2136     // Pad up the used user SGPRs with dead inputs.
2137     unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2138 
2139     // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2140     // rely on it to reach 16 since if we end up having no stack usage, it will
2141     // not really be added.
2142     unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2143                                       Info.hasWorkGroupIDY() +
2144                                       Info.hasWorkGroupIDZ() +
2145                                       Info.hasWorkGroupInfo();
2146     for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2147       Register Reg = Info.addReservedUserSGPR();
2148       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2149       CCInfo.AllocateReg(Reg);
2150     }
2151   }
2152 
2153   if (Info.hasWorkGroupIDX()) {
2154     Register Reg = Info.addWorkGroupIDX();
2155     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2156     CCInfo.AllocateReg(Reg);
2157   }
2158 
2159   if (Info.hasWorkGroupIDY()) {
2160     Register Reg = Info.addWorkGroupIDY();
2161     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2162     CCInfo.AllocateReg(Reg);
2163   }
2164 
2165   if (Info.hasWorkGroupIDZ()) {
2166     Register Reg = Info.addWorkGroupIDZ();
2167     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2168     CCInfo.AllocateReg(Reg);
2169   }
2170 
2171   if (Info.hasWorkGroupInfo()) {
2172     Register Reg = Info.addWorkGroupInfo();
2173     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2174     CCInfo.AllocateReg(Reg);
2175   }
2176 
2177   if (Info.hasPrivateSegmentWaveByteOffset()) {
2178     // Scratch wave offset passed in system SGPR.
2179     unsigned PrivateSegmentWaveByteOffsetReg;
2180 
2181     if (IsShader) {
2182       PrivateSegmentWaveByteOffsetReg =
2183         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2184 
2185       // This is true if the scratch wave byte offset doesn't have a fixed
2186       // location.
2187       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2188         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2189         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2190       }
2191     } else
2192       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2193 
2194     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2195     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2196   }
2197 
2198   assert(!Subtarget->hasUserSGPRInit16Bug() || Info.getNumPreloadedSGPRs() >= 16);
2199 }
2200 
2201 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2202                                      MachineFunction &MF,
2203                                      const SIRegisterInfo &TRI,
2204                                      SIMachineFunctionInfo &Info) {
2205   // Now that we've figured out where the scratch register inputs are, see if
2206   // should reserve the arguments and use them directly.
2207   MachineFrameInfo &MFI = MF.getFrameInfo();
2208   bool HasStackObjects = MFI.hasStackObjects();
2209   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2210 
2211   // Record that we know we have non-spill stack objects so we don't need to
2212   // check all stack objects later.
2213   if (HasStackObjects)
2214     Info.setHasNonSpillStackObjects(true);
2215 
2216   // Everything live out of a block is spilled with fast regalloc, so it's
2217   // almost certain that spilling will be required.
2218   if (TM.getOptLevel() == CodeGenOpt::None)
2219     HasStackObjects = true;
2220 
2221   // For now assume stack access is needed in any callee functions, so we need
2222   // the scratch registers to pass in.
2223   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2224 
2225   if (!ST.enableFlatScratch()) {
2226     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2227       // If we have stack objects, we unquestionably need the private buffer
2228       // resource. For the Code Object V2 ABI, this will be the first 4 user
2229       // SGPR inputs. We can reserve those and use them directly.
2230 
2231       Register PrivateSegmentBufferReg =
2232           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2233       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2234     } else {
2235       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2236       // We tentatively reserve the last registers (skipping the last registers
2237       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2238       // we'll replace these with the ones immediately after those which were
2239       // really allocated. In the prologue copies will be inserted from the
2240       // argument to these reserved registers.
2241 
2242       // Without HSA, relocations are used for the scratch pointer and the
2243       // buffer resource setup is always inserted in the prologue. Scratch wave
2244       // offset is still in an input SGPR.
2245       Info.setScratchRSrcReg(ReservedBufferReg);
2246     }
2247   }
2248 
2249   MachineRegisterInfo &MRI = MF.getRegInfo();
2250 
2251   // For entry functions we have to set up the stack pointer if we use it,
2252   // whereas non-entry functions get this "for free". This means there is no
2253   // intrinsic advantage to using S32 over S34 in cases where we do not have
2254   // calls but do need a frame pointer (i.e. if we are requested to have one
2255   // because frame pointer elimination is disabled). To keep things simple we
2256   // only ever use S32 as the call ABI stack pointer, and so using it does not
2257   // imply we need a separate frame pointer.
2258   //
2259   // Try to use s32 as the SP, but move it if it would interfere with input
2260   // arguments. This won't work with calls though.
2261   //
2262   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2263   // registers.
2264   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2265     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2266   } else {
2267     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2268 
2269     if (MFI.hasCalls())
2270       report_fatal_error("call in graphics shader with too many input SGPRs");
2271 
2272     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2273       if (!MRI.isLiveIn(Reg)) {
2274         Info.setStackPtrOffsetReg(Reg);
2275         break;
2276       }
2277     }
2278 
2279     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2280       report_fatal_error("failed to find register for SP");
2281   }
2282 
2283   // hasFP should be accurate for entry functions even before the frame is
2284   // finalized, because it does not rely on the known stack size, only
2285   // properties like whether variable sized objects are present.
2286   if (ST.getFrameLowering()->hasFP(MF)) {
2287     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2288   }
2289 }
2290 
2291 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2292   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2293   return !Info->isEntryFunction();
2294 }
2295 
2296 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2297 
2298 }
2299 
2300 void SITargetLowering::insertCopiesSplitCSR(
2301   MachineBasicBlock *Entry,
2302   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2303   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2304 
2305   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2306   if (!IStart)
2307     return;
2308 
2309   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2310   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2311   MachineBasicBlock::iterator MBBI = Entry->begin();
2312   for (const MCPhysReg *I = IStart; *I; ++I) {
2313     const TargetRegisterClass *RC = nullptr;
2314     if (AMDGPU::SReg_64RegClass.contains(*I))
2315       RC = &AMDGPU::SGPR_64RegClass;
2316     else if (AMDGPU::SReg_32RegClass.contains(*I))
2317       RC = &AMDGPU::SGPR_32RegClass;
2318     else
2319       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2320 
2321     Register NewVR = MRI->createVirtualRegister(RC);
2322     // Create copy from CSR to a virtual register.
2323     Entry->addLiveIn(*I);
2324     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2325       .addReg(*I);
2326 
2327     // Insert the copy-back instructions right before the terminator.
2328     for (auto *Exit : Exits)
2329       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2330               TII->get(TargetOpcode::COPY), *I)
2331         .addReg(NewVR);
2332   }
2333 }
2334 
2335 SDValue SITargetLowering::LowerFormalArguments(
2336     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2337     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2338     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2339   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2340 
2341   MachineFunction &MF = DAG.getMachineFunction();
2342   const Function &Fn = MF.getFunction();
2343   FunctionType *FType = MF.getFunction().getFunctionType();
2344   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2345 
2346   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2347     DiagnosticInfoUnsupported NoGraphicsHSA(
2348         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2349     DAG.getContext()->diagnose(NoGraphicsHSA);
2350     return DAG.getEntryNode();
2351   }
2352 
2353   Info->allocateModuleLDSGlobal(Fn);
2354 
2355   SmallVector<ISD::InputArg, 16> Splits;
2356   SmallVector<CCValAssign, 16> ArgLocs;
2357   BitVector Skipped(Ins.size());
2358   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2359                  *DAG.getContext());
2360 
2361   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2362   bool IsKernel = AMDGPU::isKernel(CallConv);
2363   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2364 
2365   if (IsGraphics) {
2366     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2367            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2368            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2369            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2370            !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
2371            !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
2372   }
2373 
2374   if (CallConv == CallingConv::AMDGPU_PS) {
2375     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2376 
2377     // At least one interpolation mode must be enabled or else the GPU will
2378     // hang.
2379     //
2380     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2381     // set PSInputAddr, the user wants to enable some bits after the compilation
2382     // based on run-time states. Since we can't know what the final PSInputEna
2383     // will look like, so we shouldn't do anything here and the user should take
2384     // responsibility for the correct programming.
2385     //
2386     // Otherwise, the following restrictions apply:
2387     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2388     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2389     //   enabled too.
2390     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2391         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2392       CCInfo.AllocateReg(AMDGPU::VGPR0);
2393       CCInfo.AllocateReg(AMDGPU::VGPR1);
2394       Info->markPSInputAllocated(0);
2395       Info->markPSInputEnabled(0);
2396     }
2397     if (Subtarget->isAmdPalOS()) {
2398       // For isAmdPalOS, the user does not enable some bits after compilation
2399       // based on run-time states; the register values being generated here are
2400       // the final ones set in hardware. Therefore we need to apply the
2401       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2402       // a bit is set in PSInputAddr but not PSInputEnable is where the
2403       // frontend set up an input arg for a particular interpolation mode, but
2404       // nothing uses that input arg. Really we should have an earlier pass
2405       // that removes such an arg.)
2406       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2407       if ((PsInputBits & 0x7F) == 0 ||
2408           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2409         Info->markPSInputEnabled(
2410             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2411     }
2412   } else if (IsKernel) {
2413     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2414   } else {
2415     Splits.append(Ins.begin(), Ins.end());
2416   }
2417 
2418   if (IsEntryFunc) {
2419     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2420     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2421   } else if (!IsGraphics) {
2422     // For the fixed ABI, pass workitem IDs in the last argument register.
2423     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2424   }
2425 
2426   if (IsKernel) {
2427     analyzeFormalArgumentsCompute(CCInfo, Ins);
2428   } else {
2429     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2430     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2431   }
2432 
2433   SmallVector<SDValue, 16> Chains;
2434 
2435   // FIXME: This is the minimum kernel argument alignment. We should improve
2436   // this to the maximum alignment of the arguments.
2437   //
2438   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2439   // kern arg offset.
2440   const Align KernelArgBaseAlign = Align(16);
2441 
2442   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2443     const ISD::InputArg &Arg = Ins[i];
2444     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2445       InVals.push_back(DAG.getUNDEF(Arg.VT));
2446       continue;
2447     }
2448 
2449     CCValAssign &VA = ArgLocs[ArgIdx++];
2450     MVT VT = VA.getLocVT();
2451 
2452     if (IsEntryFunc && VA.isMemLoc()) {
2453       VT = Ins[i].VT;
2454       EVT MemVT = VA.getLocVT();
2455 
2456       const uint64_t Offset = VA.getLocMemOffset();
2457       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2458 
2459       if (Arg.Flags.isByRef()) {
2460         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2461 
2462         const GCNTargetMachine &TM =
2463             static_cast<const GCNTargetMachine &>(getTargetMachine());
2464         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2465                                     Arg.Flags.getPointerAddrSpace())) {
2466           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2467                                      Arg.Flags.getPointerAddrSpace());
2468         }
2469 
2470         InVals.push_back(Ptr);
2471         continue;
2472       }
2473 
2474       SDValue Arg = lowerKernargMemParameter(
2475         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2476       Chains.push_back(Arg.getValue(1));
2477 
2478       auto *ParamTy =
2479         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2480       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2481           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2482                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2483         // On SI local pointers are just offsets into LDS, so they are always
2484         // less than 16-bits.  On CI and newer they could potentially be
2485         // real pointers, so we can't guarantee their size.
2486         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2487                           DAG.getValueType(MVT::i16));
2488       }
2489 
2490       InVals.push_back(Arg);
2491       continue;
2492     } else if (!IsEntryFunc && VA.isMemLoc()) {
2493       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2494       InVals.push_back(Val);
2495       if (!Arg.Flags.isByVal())
2496         Chains.push_back(Val.getValue(1));
2497       continue;
2498     }
2499 
2500     assert(VA.isRegLoc() && "Parameter must be in a register!");
2501 
2502     Register Reg = VA.getLocReg();
2503     const TargetRegisterClass *RC = nullptr;
2504     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2505       RC = &AMDGPU::VGPR_32RegClass;
2506     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2507       RC = &AMDGPU::SGPR_32RegClass;
2508     else
2509       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2510     EVT ValVT = VA.getValVT();
2511 
2512     Reg = MF.addLiveIn(Reg, RC);
2513     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2514 
2515     if (Arg.Flags.isSRet()) {
2516       // The return object should be reasonably addressable.
2517 
2518       // FIXME: This helps when the return is a real sret. If it is a
2519       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2520       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2521       unsigned NumBits
2522         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2523       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2524         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2525     }
2526 
2527     // If this is an 8 or 16-bit value, it is really passed promoted
2528     // to 32 bits. Insert an assert[sz]ext to capture this, then
2529     // truncate to the right size.
2530     switch (VA.getLocInfo()) {
2531     case CCValAssign::Full:
2532       break;
2533     case CCValAssign::BCvt:
2534       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2535       break;
2536     case CCValAssign::SExt:
2537       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2538                         DAG.getValueType(ValVT));
2539       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2540       break;
2541     case CCValAssign::ZExt:
2542       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2543                         DAG.getValueType(ValVT));
2544       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2545       break;
2546     case CCValAssign::AExt:
2547       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2548       break;
2549     default:
2550       llvm_unreachable("Unknown loc info!");
2551     }
2552 
2553     InVals.push_back(Val);
2554   }
2555 
2556   // Start adding system SGPRs.
2557   if (IsEntryFunc) {
2558     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2559   } else {
2560     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2561     if (!IsGraphics)
2562       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2563   }
2564 
2565   auto &ArgUsageInfo =
2566     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2567   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2568 
2569   unsigned StackArgSize = CCInfo.getNextStackOffset();
2570   Info->setBytesInStackArgArea(StackArgSize);
2571 
2572   return Chains.empty() ? Chain :
2573     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2574 }
2575 
2576 // TODO: If return values can't fit in registers, we should return as many as
2577 // possible in registers before passing on stack.
2578 bool SITargetLowering::CanLowerReturn(
2579   CallingConv::ID CallConv,
2580   MachineFunction &MF, bool IsVarArg,
2581   const SmallVectorImpl<ISD::OutputArg> &Outs,
2582   LLVMContext &Context) const {
2583   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2584   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2585   // for shaders. Vector types should be explicitly handled by CC.
2586   if (AMDGPU::isEntryFunctionCC(CallConv))
2587     return true;
2588 
2589   SmallVector<CCValAssign, 16> RVLocs;
2590   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2591   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2592 }
2593 
2594 SDValue
2595 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2596                               bool isVarArg,
2597                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2598                               const SmallVectorImpl<SDValue> &OutVals,
2599                               const SDLoc &DL, SelectionDAG &DAG) const {
2600   MachineFunction &MF = DAG.getMachineFunction();
2601   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2602 
2603   if (AMDGPU::isKernel(CallConv)) {
2604     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2605                                              OutVals, DL, DAG);
2606   }
2607 
2608   bool IsShader = AMDGPU::isShader(CallConv);
2609 
2610   Info->setIfReturnsVoid(Outs.empty());
2611   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2612 
2613   // CCValAssign - represent the assignment of the return value to a location.
2614   SmallVector<CCValAssign, 48> RVLocs;
2615   SmallVector<ISD::OutputArg, 48> Splits;
2616 
2617   // CCState - Info about the registers and stack slots.
2618   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2619                  *DAG.getContext());
2620 
2621   // Analyze outgoing return values.
2622   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2623 
2624   SDValue Flag;
2625   SmallVector<SDValue, 48> RetOps;
2626   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2627 
2628   // Copy the result values into the output registers.
2629   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2630        ++I, ++RealRVLocIdx) {
2631     CCValAssign &VA = RVLocs[I];
2632     assert(VA.isRegLoc() && "Can only return in registers!");
2633     // TODO: Partially return in registers if return values don't fit.
2634     SDValue Arg = OutVals[RealRVLocIdx];
2635 
2636     // Copied from other backends.
2637     switch (VA.getLocInfo()) {
2638     case CCValAssign::Full:
2639       break;
2640     case CCValAssign::BCvt:
2641       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2642       break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2651       break;
2652     default:
2653       llvm_unreachable("Unknown loc info!");
2654     }
2655 
2656     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2657     Flag = Chain.getValue(1);
2658     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2659   }
2660 
2661   // FIXME: Does sret work properly?
2662   if (!Info->isEntryFunction()) {
2663     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2664     const MCPhysReg *I =
2665       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2666     if (I) {
2667       for (; *I; ++I) {
2668         if (AMDGPU::SReg_64RegClass.contains(*I))
2669           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2670         else if (AMDGPU::SReg_32RegClass.contains(*I))
2671           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2672         else
2673           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2674       }
2675     }
2676   }
2677 
2678   // Update chain and glue.
2679   RetOps[0] = Chain;
2680   if (Flag.getNode())
2681     RetOps.push_back(Flag);
2682 
2683   unsigned Opc = AMDGPUISD::ENDPGM;
2684   if (!IsWaveEnd)
2685     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2686   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2687 }
2688 
2689 SDValue SITargetLowering::LowerCallResult(
2690     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2691     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2692     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2693     SDValue ThisVal) const {
2694   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2695 
2696   // Assign locations to each value returned by this call.
2697   SmallVector<CCValAssign, 16> RVLocs;
2698   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2699                  *DAG.getContext());
2700   CCInfo.AnalyzeCallResult(Ins, RetCC);
2701 
2702   // Copy all of the result registers out of their specified physreg.
2703   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2704     CCValAssign VA = RVLocs[i];
2705     SDValue Val;
2706 
2707     if (VA.isRegLoc()) {
2708       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2709       Chain = Val.getValue(1);
2710       InFlag = Val.getValue(2);
2711     } else if (VA.isMemLoc()) {
2712       report_fatal_error("TODO: return values in memory");
2713     } else
2714       llvm_unreachable("unknown argument location type");
2715 
2716     switch (VA.getLocInfo()) {
2717     case CCValAssign::Full:
2718       break;
2719     case CCValAssign::BCvt:
2720       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2721       break;
2722     case CCValAssign::ZExt:
2723       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2724                         DAG.getValueType(VA.getValVT()));
2725       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2726       break;
2727     case CCValAssign::SExt:
2728       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2729                         DAG.getValueType(VA.getValVT()));
2730       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2731       break;
2732     case CCValAssign::AExt:
2733       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2734       break;
2735     default:
2736       llvm_unreachable("Unknown loc info!");
2737     }
2738 
2739     InVals.push_back(Val);
2740   }
2741 
2742   return Chain;
2743 }
2744 
2745 // Add code to pass special inputs required depending on used features separate
2746 // from the explicit user arguments present in the IR.
2747 void SITargetLowering::passSpecialInputs(
2748     CallLoweringInfo &CLI,
2749     CCState &CCInfo,
2750     const SIMachineFunctionInfo &Info,
2751     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2752     SmallVectorImpl<SDValue> &MemOpChains,
2753     SDValue Chain) const {
2754   // If we don't have a call site, this was a call inserted by
2755   // legalization. These can never use special inputs.
2756   if (!CLI.CB)
2757     return;
2758 
2759   SelectionDAG &DAG = CLI.DAG;
2760   const SDLoc &DL = CLI.DL;
2761   const Function &F = DAG.getMachineFunction().getFunction();
2762 
2763   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2764   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2765 
2766   const AMDGPUFunctionArgInfo *CalleeArgInfo
2767     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2768   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2769     auto &ArgUsageInfo =
2770       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2771     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2772   }
2773 
2774   // TODO: Unify with private memory register handling. This is complicated by
2775   // the fact that at least in kernels, the input argument is not necessarily
2776   // in the same location as the input.
2777   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2778                              StringLiteral> ImplicitAttrs[] = {
2779     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2780     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2781     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2782     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2783     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2784     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2785     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
2786     {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
2787   };
2788 
2789   for (auto Attr : ImplicitAttrs) {
2790     const ArgDescriptor *OutgoingArg;
2791     const TargetRegisterClass *ArgRC;
2792     LLT ArgTy;
2793 
2794     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2795 
2796     // If the callee does not use the attribute value, skip copying the value.
2797     if (CLI.CB->hasFnAttr(Attr.second))
2798       continue;
2799 
2800     std::tie(OutgoingArg, ArgRC, ArgTy) =
2801         CalleeArgInfo->getPreloadedValue(InputID);
2802     if (!OutgoingArg)
2803       continue;
2804 
2805     const ArgDescriptor *IncomingArg;
2806     const TargetRegisterClass *IncomingArgRC;
2807     LLT Ty;
2808     std::tie(IncomingArg, IncomingArgRC, Ty) =
2809         CallerArgInfo.getPreloadedValue(InputID);
2810     assert(IncomingArgRC == ArgRC);
2811 
2812     // All special arguments are ints for now.
2813     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2814     SDValue InputReg;
2815 
2816     if (IncomingArg) {
2817       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2818     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2819       // The implicit arg ptr is special because it doesn't have a corresponding
2820       // input for kernels, and is computed from the kernarg segment pointer.
2821       InputReg = getImplicitArgPtr(DAG, DL);
2822     } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
2823       Optional<uint32_t> Id = AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
2824       if (Id.has_value()) {
2825         InputReg = DAG.getConstant(Id.value(), DL, ArgVT);
2826       } else {
2827         InputReg = DAG.getUNDEF(ArgVT);
2828       }
2829     } else {
2830       // We may have proven the input wasn't needed, although the ABI is
2831       // requiring it. We just need to allocate the register appropriately.
2832       InputReg = DAG.getUNDEF(ArgVT);
2833     }
2834 
2835     if (OutgoingArg->isRegister()) {
2836       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2837       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2838         report_fatal_error("failed to allocate implicit input argument");
2839     } else {
2840       unsigned SpecialArgOffset =
2841           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2842       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2843                                               SpecialArgOffset);
2844       MemOpChains.push_back(ArgStore);
2845     }
2846   }
2847 
2848   // Pack workitem IDs into a single register or pass it as is if already
2849   // packed.
2850   const ArgDescriptor *OutgoingArg;
2851   const TargetRegisterClass *ArgRC;
2852   LLT Ty;
2853 
2854   std::tie(OutgoingArg, ArgRC, Ty) =
2855       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2856   if (!OutgoingArg)
2857     std::tie(OutgoingArg, ArgRC, Ty) =
2858         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2859   if (!OutgoingArg)
2860     std::tie(OutgoingArg, ArgRC, Ty) =
2861         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2862   if (!OutgoingArg)
2863     return;
2864 
2865   const ArgDescriptor *IncomingArgX = std::get<0>(
2866       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2867   const ArgDescriptor *IncomingArgY = std::get<0>(
2868       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2869   const ArgDescriptor *IncomingArgZ = std::get<0>(
2870       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2871 
2872   SDValue InputReg;
2873   SDLoc SL;
2874 
2875   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2876   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2877   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2878 
2879   // If incoming ids are not packed we need to pack them.
2880   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2881       NeedWorkItemIDX) {
2882     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2883       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2884     } else {
2885       InputReg = DAG.getConstant(0, DL, MVT::i32);
2886     }
2887   }
2888 
2889   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2890       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2891     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2892     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2893                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2894     InputReg = InputReg.getNode() ?
2895                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2896   }
2897 
2898   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2899       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2900     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2901     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2902                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2903     InputReg = InputReg.getNode() ?
2904                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2905   }
2906 
2907   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2908     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2909       // We're in a situation where the outgoing function requires the workitem
2910       // ID, but the calling function does not have it (e.g a graphics function
2911       // calling a C calling convention function). This is illegal, but we need
2912       // to produce something.
2913       InputReg = DAG.getUNDEF(MVT::i32);
2914     } else {
2915       // Workitem ids are already packed, any of present incoming arguments
2916       // will carry all required fields.
2917       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2918         IncomingArgX ? *IncomingArgX :
2919         IncomingArgY ? *IncomingArgY :
2920         *IncomingArgZ, ~0u);
2921       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2922     }
2923   }
2924 
2925   if (OutgoingArg->isRegister()) {
2926     if (InputReg)
2927       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2928 
2929     CCInfo.AllocateReg(OutgoingArg->getRegister());
2930   } else {
2931     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2932     if (InputReg) {
2933       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2934                                               SpecialArgOffset);
2935       MemOpChains.push_back(ArgStore);
2936     }
2937   }
2938 }
2939 
2940 static bool canGuaranteeTCO(CallingConv::ID CC) {
2941   return CC == CallingConv::Fast;
2942 }
2943 
2944 /// Return true if we might ever do TCO for calls with this calling convention.
2945 static bool mayTailCallThisCC(CallingConv::ID CC) {
2946   switch (CC) {
2947   case CallingConv::C:
2948   case CallingConv::AMDGPU_Gfx:
2949     return true;
2950   default:
2951     return canGuaranteeTCO(CC);
2952   }
2953 }
2954 
2955 bool SITargetLowering::isEligibleForTailCallOptimization(
2956     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2957     const SmallVectorImpl<ISD::OutputArg> &Outs,
2958     const SmallVectorImpl<SDValue> &OutVals,
2959     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2960   if (!mayTailCallThisCC(CalleeCC))
2961     return false;
2962 
2963   // For a divergent call target, we need to do a waterfall loop over the
2964   // possible callees which precludes us from using a simple jump.
2965   if (Callee->isDivergent())
2966     return false;
2967 
2968   MachineFunction &MF = DAG.getMachineFunction();
2969   const Function &CallerF = MF.getFunction();
2970   CallingConv::ID CallerCC = CallerF.getCallingConv();
2971   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2972   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2973 
2974   // Kernels aren't callable, and don't have a live in return address so it
2975   // doesn't make sense to do a tail call with entry functions.
2976   if (!CallerPreserved)
2977     return false;
2978 
2979   bool CCMatch = CallerCC == CalleeCC;
2980 
2981   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2982     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2983       return true;
2984     return false;
2985   }
2986 
2987   // TODO: Can we handle var args?
2988   if (IsVarArg)
2989     return false;
2990 
2991   for (const Argument &Arg : CallerF.args()) {
2992     if (Arg.hasByValAttr())
2993       return false;
2994   }
2995 
2996   LLVMContext &Ctx = *DAG.getContext();
2997 
2998   // Check that the call results are passed in the same way.
2999   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3000                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3001                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3002     return false;
3003 
3004   // The callee has to preserve all registers the caller needs to preserve.
3005   if (!CCMatch) {
3006     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3007     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3008       return false;
3009   }
3010 
3011   // Nothing more to check if the callee is taking no arguments.
3012   if (Outs.empty())
3013     return true;
3014 
3015   SmallVector<CCValAssign, 16> ArgLocs;
3016   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3017 
3018   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3019 
3020   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3021   // If the stack arguments for this call do not fit into our own save area then
3022   // the call cannot be made tail.
3023   // TODO: Is this really necessary?
3024   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3025     return false;
3026 
3027   const MachineRegisterInfo &MRI = MF.getRegInfo();
3028   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3029 }
3030 
3031 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3032   if (!CI->isTailCall())
3033     return false;
3034 
3035   const Function *ParentFn = CI->getParent()->getParent();
3036   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3037     return false;
3038   return true;
3039 }
3040 
3041 // The wave scratch offset register is used as the global base pointer.
3042 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3043                                     SmallVectorImpl<SDValue> &InVals) const {
3044   SelectionDAG &DAG = CLI.DAG;
3045   const SDLoc &DL = CLI.DL;
3046   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3047   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3048   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3049   SDValue Chain = CLI.Chain;
3050   SDValue Callee = CLI.Callee;
3051   bool &IsTailCall = CLI.IsTailCall;
3052   CallingConv::ID CallConv = CLI.CallConv;
3053   bool IsVarArg = CLI.IsVarArg;
3054   bool IsSibCall = false;
3055   bool IsThisReturn = false;
3056   MachineFunction &MF = DAG.getMachineFunction();
3057 
3058   if (Callee.isUndef() || isNullConstant(Callee)) {
3059     if (!CLI.IsTailCall) {
3060       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3061         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3062     }
3063 
3064     return Chain;
3065   }
3066 
3067   if (IsVarArg) {
3068     return lowerUnhandledCall(CLI, InVals,
3069                               "unsupported call to variadic function ");
3070   }
3071 
3072   if (!CLI.CB)
3073     report_fatal_error("unsupported libcall legalization");
3074 
3075   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3076     return lowerUnhandledCall(CLI, InVals,
3077                               "unsupported required tail call to function ");
3078   }
3079 
3080   if (AMDGPU::isShader(CallConv)) {
3081     // Note the issue is with the CC of the called function, not of the call
3082     // itself.
3083     return lowerUnhandledCall(CLI, InVals,
3084                               "unsupported call to a shader function ");
3085   }
3086 
3087   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3088       CallConv != CallingConv::AMDGPU_Gfx) {
3089     // Only allow calls with specific calling conventions.
3090     return lowerUnhandledCall(CLI, InVals,
3091                               "unsupported calling convention for call from "
3092                               "graphics shader of function ");
3093   }
3094 
3095   if (IsTailCall) {
3096     IsTailCall = isEligibleForTailCallOptimization(
3097       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3098     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3099       report_fatal_error("failed to perform tail call elimination on a call "
3100                          "site marked musttail");
3101     }
3102 
3103     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3104 
3105     // A sibling call is one where we're under the usual C ABI and not planning
3106     // to change that but can still do a tail call:
3107     if (!TailCallOpt && IsTailCall)
3108       IsSibCall = true;
3109 
3110     if (IsTailCall)
3111       ++NumTailCalls;
3112   }
3113 
3114   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3115   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3116   SmallVector<SDValue, 8> MemOpChains;
3117 
3118   // Analyze operands of the call, assigning locations to each operand.
3119   SmallVector<CCValAssign, 16> ArgLocs;
3120   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3121   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3122 
3123   if (CallConv != CallingConv::AMDGPU_Gfx) {
3124     // With a fixed ABI, allocate fixed registers before user arguments.
3125     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3126   }
3127 
3128   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3129 
3130   // Get a count of how many bytes are to be pushed on the stack.
3131   unsigned NumBytes = CCInfo.getNextStackOffset();
3132 
3133   if (IsSibCall) {
3134     // Since we're not changing the ABI to make this a tail call, the memory
3135     // operands are already available in the caller's incoming argument space.
3136     NumBytes = 0;
3137   }
3138 
3139   // FPDiff is the byte offset of the call's argument area from the callee's.
3140   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3141   // by this amount for a tail call. In a sibling call it must be 0 because the
3142   // caller will deallocate the entire stack and the callee still expects its
3143   // arguments to begin at SP+0. Completely unused for non-tail calls.
3144   int32_t FPDiff = 0;
3145   MachineFrameInfo &MFI = MF.getFrameInfo();
3146 
3147   // Adjust the stack pointer for the new arguments...
3148   // These operations are automatically eliminated by the prolog/epilog pass
3149   if (!IsSibCall) {
3150     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3151 
3152     if (!Subtarget->enableFlatScratch()) {
3153       SmallVector<SDValue, 4> CopyFromChains;
3154 
3155       // In the HSA case, this should be an identity copy.
3156       SDValue ScratchRSrcReg
3157         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3158       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3159       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3160       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3161     }
3162   }
3163 
3164   MVT PtrVT = MVT::i32;
3165 
3166   // Walk the register/memloc assignments, inserting copies/loads.
3167   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3168     CCValAssign &VA = ArgLocs[i];
3169     SDValue Arg = OutVals[i];
3170 
3171     // Promote the value if needed.
3172     switch (VA.getLocInfo()) {
3173     case CCValAssign::Full:
3174       break;
3175     case CCValAssign::BCvt:
3176       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3177       break;
3178     case CCValAssign::ZExt:
3179       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3180       break;
3181     case CCValAssign::SExt:
3182       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3183       break;
3184     case CCValAssign::AExt:
3185       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3186       break;
3187     case CCValAssign::FPExt:
3188       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3189       break;
3190     default:
3191       llvm_unreachable("Unknown loc info!");
3192     }
3193 
3194     if (VA.isRegLoc()) {
3195       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3196     } else {
3197       assert(VA.isMemLoc());
3198 
3199       SDValue DstAddr;
3200       MachinePointerInfo DstInfo;
3201 
3202       unsigned LocMemOffset = VA.getLocMemOffset();
3203       int32_t Offset = LocMemOffset;
3204 
3205       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3206       MaybeAlign Alignment;
3207 
3208       if (IsTailCall) {
3209         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3210         unsigned OpSize = Flags.isByVal() ?
3211           Flags.getByValSize() : VA.getValVT().getStoreSize();
3212 
3213         // FIXME: We can have better than the minimum byval required alignment.
3214         Alignment =
3215             Flags.isByVal()
3216                 ? Flags.getNonZeroByValAlign()
3217                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3218 
3219         Offset = Offset + FPDiff;
3220         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3221 
3222         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3223         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3224 
3225         // Make sure any stack arguments overlapping with where we're storing
3226         // are loaded before this eventual operation. Otherwise they'll be
3227         // clobbered.
3228 
3229         // FIXME: Why is this really necessary? This seems to just result in a
3230         // lot of code to copy the stack and write them back to the same
3231         // locations, which are supposed to be immutable?
3232         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3233       } else {
3234         // Stores to the argument stack area are relative to the stack pointer.
3235         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3236                                         MVT::i32);
3237         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3238         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3239         Alignment =
3240             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3241       }
3242 
3243       if (Outs[i].Flags.isByVal()) {
3244         SDValue SizeNode =
3245             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3246         SDValue Cpy =
3247             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3248                           Outs[i].Flags.getNonZeroByValAlign(),
3249                           /*isVol = */ false, /*AlwaysInline = */ true,
3250                           /*isTailCall = */ false, DstInfo,
3251                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3252 
3253         MemOpChains.push_back(Cpy);
3254       } else {
3255         SDValue Store =
3256             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3257         MemOpChains.push_back(Store);
3258       }
3259     }
3260   }
3261 
3262   if (!MemOpChains.empty())
3263     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3264 
3265   // Build a sequence of copy-to-reg nodes chained together with token chain
3266   // and flag operands which copy the outgoing args into the appropriate regs.
3267   SDValue InFlag;
3268   for (auto &RegToPass : RegsToPass) {
3269     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3270                              RegToPass.second, InFlag);
3271     InFlag = Chain.getValue(1);
3272   }
3273 
3274 
3275   // We don't usually want to end the call-sequence here because we would tidy
3276   // the frame up *after* the call, however in the ABI-changing tail-call case
3277   // we've carefully laid out the parameters so that when sp is reset they'll be
3278   // in the correct location.
3279   if (IsTailCall && !IsSibCall) {
3280     Chain = DAG.getCALLSEQ_END(Chain,
3281                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3282                                DAG.getTargetConstant(0, DL, MVT::i32),
3283                                InFlag, DL);
3284     InFlag = Chain.getValue(1);
3285   }
3286 
3287   std::vector<SDValue> Ops;
3288   Ops.push_back(Chain);
3289   Ops.push_back(Callee);
3290   // Add a redundant copy of the callee global which will not be legalized, as
3291   // we need direct access to the callee later.
3292   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3293     const GlobalValue *GV = GSD->getGlobal();
3294     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3295   } else {
3296     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3297   }
3298 
3299   if (IsTailCall) {
3300     // Each tail call may have to adjust the stack by a different amount, so
3301     // this information must travel along with the operation for eventual
3302     // consumption by emitEpilogue.
3303     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3304   }
3305 
3306   // Add argument registers to the end of the list so that they are known live
3307   // into the call.
3308   for (auto &RegToPass : RegsToPass) {
3309     Ops.push_back(DAG.getRegister(RegToPass.first,
3310                                   RegToPass.second.getValueType()));
3311   }
3312 
3313   // Add a register mask operand representing the call-preserved registers.
3314 
3315   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3316   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3317   assert(Mask && "Missing call preserved mask for calling convention");
3318   Ops.push_back(DAG.getRegisterMask(Mask));
3319 
3320   if (InFlag.getNode())
3321     Ops.push_back(InFlag);
3322 
3323   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3324 
3325   // If we're doing a tall call, use a TC_RETURN here rather than an
3326   // actual call instruction.
3327   if (IsTailCall) {
3328     MFI.setHasTailCall();
3329     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3330   }
3331 
3332   // Returns a chain and a flag for retval copy to use.
3333   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3334   Chain = Call.getValue(0);
3335   InFlag = Call.getValue(1);
3336 
3337   uint64_t CalleePopBytes = NumBytes;
3338   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3339                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3340                              InFlag, DL);
3341   if (!Ins.empty())
3342     InFlag = Chain.getValue(1);
3343 
3344   // Handle result values, copying them out of physregs into vregs that we
3345   // return.
3346   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3347                          InVals, IsThisReturn,
3348                          IsThisReturn ? OutVals[0] : SDValue());
3349 }
3350 
3351 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3352 // except for applying the wave size scale to the increment amount.
3353 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3354     SDValue Op, SelectionDAG &DAG) const {
3355   const MachineFunction &MF = DAG.getMachineFunction();
3356   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3357 
3358   SDLoc dl(Op);
3359   EVT VT = Op.getValueType();
3360   SDValue Tmp1 = Op;
3361   SDValue Tmp2 = Op.getValue(1);
3362   SDValue Tmp3 = Op.getOperand(2);
3363   SDValue Chain = Tmp1.getOperand(0);
3364 
3365   Register SPReg = Info->getStackPtrOffsetReg();
3366 
3367   // Chain the dynamic stack allocation so that it doesn't modify the stack
3368   // pointer when other instructions are using the stack.
3369   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3370 
3371   SDValue Size  = Tmp2.getOperand(1);
3372   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3373   Chain = SP.getValue(1);
3374   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3375   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3376   const TargetFrameLowering *TFL = ST.getFrameLowering();
3377   unsigned Opc =
3378     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3379     ISD::ADD : ISD::SUB;
3380 
3381   SDValue ScaledSize = DAG.getNode(
3382       ISD::SHL, dl, VT, Size,
3383       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3384 
3385   Align StackAlign = TFL->getStackAlign();
3386   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3387   if (Alignment && *Alignment > StackAlign) {
3388     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3389                        DAG.getConstant(-(uint64_t)Alignment->value()
3390                                            << ST.getWavefrontSizeLog2(),
3391                                        dl, VT));
3392   }
3393 
3394   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3395   Tmp2 = DAG.getCALLSEQ_END(
3396       Chain, DAG.getIntPtrConstant(0, dl, true),
3397       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3398 
3399   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3400 }
3401 
3402 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3403                                                   SelectionDAG &DAG) const {
3404   // We only handle constant sizes here to allow non-entry block, static sized
3405   // allocas. A truly dynamic value is more difficult to support because we
3406   // don't know if the size value is uniform or not. If the size isn't uniform,
3407   // we would need to do a wave reduction to get the maximum size to know how
3408   // much to increment the uniform stack pointer.
3409   SDValue Size = Op.getOperand(1);
3410   if (isa<ConstantSDNode>(Size))
3411       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3412 
3413   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3414 }
3415 
3416 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3417                                              const MachineFunction &MF) const {
3418   Register Reg = StringSwitch<Register>(RegName)
3419     .Case("m0", AMDGPU::M0)
3420     .Case("exec", AMDGPU::EXEC)
3421     .Case("exec_lo", AMDGPU::EXEC_LO)
3422     .Case("exec_hi", AMDGPU::EXEC_HI)
3423     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3424     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3425     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3426     .Default(Register());
3427 
3428   if (Reg == AMDGPU::NoRegister) {
3429     report_fatal_error(Twine("invalid register name \""
3430                              + StringRef(RegName)  + "\"."));
3431 
3432   }
3433 
3434   if (!Subtarget->hasFlatScrRegister() &&
3435        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3436     report_fatal_error(Twine("invalid register \""
3437                              + StringRef(RegName)  + "\" for subtarget."));
3438   }
3439 
3440   switch (Reg) {
3441   case AMDGPU::M0:
3442   case AMDGPU::EXEC_LO:
3443   case AMDGPU::EXEC_HI:
3444   case AMDGPU::FLAT_SCR_LO:
3445   case AMDGPU::FLAT_SCR_HI:
3446     if (VT.getSizeInBits() == 32)
3447       return Reg;
3448     break;
3449   case AMDGPU::EXEC:
3450   case AMDGPU::FLAT_SCR:
3451     if (VT.getSizeInBits() == 64)
3452       return Reg;
3453     break;
3454   default:
3455     llvm_unreachable("missing register type checking");
3456   }
3457 
3458   report_fatal_error(Twine("invalid type for register \""
3459                            + StringRef(RegName) + "\"."));
3460 }
3461 
3462 // If kill is not the last instruction, split the block so kill is always a
3463 // proper terminator.
3464 MachineBasicBlock *
3465 SITargetLowering::splitKillBlock(MachineInstr &MI,
3466                                  MachineBasicBlock *BB) const {
3467   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3468   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3469   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3470   return SplitBB;
3471 }
3472 
3473 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3474 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3475 // be the first instruction in the remainder block.
3476 //
3477 /// \returns { LoopBody, Remainder }
3478 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3479 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3480   MachineFunction *MF = MBB.getParent();
3481   MachineBasicBlock::iterator I(&MI);
3482 
3483   // To insert the loop we need to split the block. Move everything after this
3484   // point to a new block, and insert a new empty block between the two.
3485   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3486   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3487   MachineFunction::iterator MBBI(MBB);
3488   ++MBBI;
3489 
3490   MF->insert(MBBI, LoopBB);
3491   MF->insert(MBBI, RemainderBB);
3492 
3493   LoopBB->addSuccessor(LoopBB);
3494   LoopBB->addSuccessor(RemainderBB);
3495 
3496   // Move the rest of the block into a new block.
3497   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3498 
3499   if (InstInLoop) {
3500     auto Next = std::next(I);
3501 
3502     // Move instruction to loop body.
3503     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3504 
3505     // Move the rest of the block.
3506     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3507   } else {
3508     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3509   }
3510 
3511   MBB.addSuccessor(LoopBB);
3512 
3513   return std::make_pair(LoopBB, RemainderBB);
3514 }
3515 
3516 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3517 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3518   MachineBasicBlock *MBB = MI.getParent();
3519   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3520   auto I = MI.getIterator();
3521   auto E = std::next(I);
3522 
3523   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3524     .addImm(0);
3525 
3526   MIBundleBuilder Bundler(*MBB, I, E);
3527   finalizeBundle(*MBB, Bundler.begin());
3528 }
3529 
3530 MachineBasicBlock *
3531 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3532                                          MachineBasicBlock *BB) const {
3533   const DebugLoc &DL = MI.getDebugLoc();
3534 
3535   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3536 
3537   MachineBasicBlock *LoopBB;
3538   MachineBasicBlock *RemainderBB;
3539   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3540 
3541   // Apparently kill flags are only valid if the def is in the same block?
3542   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3543     Src->setIsKill(false);
3544 
3545   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3546 
3547   MachineBasicBlock::iterator I = LoopBB->end();
3548 
3549   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3550     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3551 
3552   // Clear TRAP_STS.MEM_VIOL
3553   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3554     .addImm(0)
3555     .addImm(EncodedReg);
3556 
3557   bundleInstWithWaitcnt(MI);
3558 
3559   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3560 
3561   // Load and check TRAP_STS.MEM_VIOL
3562   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3563     .addImm(EncodedReg);
3564 
3565   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3566   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3567     .addReg(Reg, RegState::Kill)
3568     .addImm(0);
3569   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3570     .addMBB(LoopBB);
3571 
3572   return RemainderBB;
3573 }
3574 
3575 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3576 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3577 // will only do one iteration. In the worst case, this will loop 64 times.
3578 //
3579 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3580 static MachineBasicBlock::iterator
3581 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3582                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3583                        const DebugLoc &DL, const MachineOperand &Idx,
3584                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3585                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3586                        Register &SGPRIdxReg) {
3587 
3588   MachineFunction *MF = OrigBB.getParent();
3589   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3590   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3591   MachineBasicBlock::iterator I = LoopBB.begin();
3592 
3593   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3594   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3595   Register NewExec = MRI.createVirtualRegister(BoolRC);
3596   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3597   Register CondReg = MRI.createVirtualRegister(BoolRC);
3598 
3599   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3600     .addReg(InitReg)
3601     .addMBB(&OrigBB)
3602     .addReg(ResultReg)
3603     .addMBB(&LoopBB);
3604 
3605   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3606     .addReg(InitSaveExecReg)
3607     .addMBB(&OrigBB)
3608     .addReg(NewExec)
3609     .addMBB(&LoopBB);
3610 
3611   // Read the next variant <- also loop target.
3612   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3613       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3614 
3615   // Compare the just read M0 value to all possible Idx values.
3616   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3617       .addReg(CurrentIdxReg)
3618       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3619 
3620   // Update EXEC, save the original EXEC value to VCC.
3621   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3622                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3623           NewExec)
3624     .addReg(CondReg, RegState::Kill);
3625 
3626   MRI.setSimpleHint(NewExec, CondReg);
3627 
3628   if (UseGPRIdxMode) {
3629     if (Offset == 0) {
3630       SGPRIdxReg = CurrentIdxReg;
3631     } else {
3632       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3633       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3634           .addReg(CurrentIdxReg, RegState::Kill)
3635           .addImm(Offset);
3636     }
3637   } else {
3638     // Move index from VCC into M0
3639     if (Offset == 0) {
3640       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3641         .addReg(CurrentIdxReg, RegState::Kill);
3642     } else {
3643       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3644         .addReg(CurrentIdxReg, RegState::Kill)
3645         .addImm(Offset);
3646     }
3647   }
3648 
3649   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3650   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3651   MachineInstr *InsertPt =
3652     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3653                                                   : AMDGPU::S_XOR_B64_term), Exec)
3654       .addReg(Exec)
3655       .addReg(NewExec);
3656 
3657   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3658   // s_cbranch_scc0?
3659 
3660   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3661   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3662     .addMBB(&LoopBB);
3663 
3664   return InsertPt->getIterator();
3665 }
3666 
3667 // This has slightly sub-optimal regalloc when the source vector is killed by
3668 // the read. The register allocator does not understand that the kill is
3669 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3670 // subregister from it, using 1 more VGPR than necessary. This was saved when
3671 // this was expanded after register allocation.
3672 static MachineBasicBlock::iterator
3673 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3674                unsigned InitResultReg, unsigned PhiReg, int Offset,
3675                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3676   MachineFunction *MF = MBB.getParent();
3677   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3678   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3679   MachineRegisterInfo &MRI = MF->getRegInfo();
3680   const DebugLoc &DL = MI.getDebugLoc();
3681   MachineBasicBlock::iterator I(&MI);
3682 
3683   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3684   Register DstReg = MI.getOperand(0).getReg();
3685   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3686   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3687   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3688   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3689 
3690   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3691 
3692   // Save the EXEC mask
3693   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3694     .addReg(Exec);
3695 
3696   MachineBasicBlock *LoopBB;
3697   MachineBasicBlock *RemainderBB;
3698   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3699 
3700   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3701 
3702   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3703                                       InitResultReg, DstReg, PhiReg, TmpExec,
3704                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3705 
3706   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3707   MachineFunction::iterator MBBI(LoopBB);
3708   ++MBBI;
3709   MF->insert(MBBI, LandingPad);
3710   LoopBB->removeSuccessor(RemainderBB);
3711   LandingPad->addSuccessor(RemainderBB);
3712   LoopBB->addSuccessor(LandingPad);
3713   MachineBasicBlock::iterator First = LandingPad->begin();
3714   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3715     .addReg(SaveExec);
3716 
3717   return InsPt;
3718 }
3719 
3720 // Returns subreg index, offset
3721 static std::pair<unsigned, int>
3722 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3723                             const TargetRegisterClass *SuperRC,
3724                             unsigned VecReg,
3725                             int Offset) {
3726   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3727 
3728   // Skip out of bounds offsets, or else we would end up using an undefined
3729   // register.
3730   if (Offset >= NumElts || Offset < 0)
3731     return std::make_pair(AMDGPU::sub0, Offset);
3732 
3733   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3734 }
3735 
3736 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3737                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3738                                  int Offset) {
3739   MachineBasicBlock *MBB = MI.getParent();
3740   const DebugLoc &DL = MI.getDebugLoc();
3741   MachineBasicBlock::iterator I(&MI);
3742 
3743   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3744 
3745   assert(Idx->getReg() != AMDGPU::NoRegister);
3746 
3747   if (Offset == 0) {
3748     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3749   } else {
3750     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3751         .add(*Idx)
3752         .addImm(Offset);
3753   }
3754 }
3755 
3756 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3757                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3758                                    int Offset) {
3759   MachineBasicBlock *MBB = MI.getParent();
3760   const DebugLoc &DL = MI.getDebugLoc();
3761   MachineBasicBlock::iterator I(&MI);
3762 
3763   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3764 
3765   if (Offset == 0)
3766     return Idx->getReg();
3767 
3768   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3769   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3770       .add(*Idx)
3771       .addImm(Offset);
3772   return Tmp;
3773 }
3774 
3775 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3776                                           MachineBasicBlock &MBB,
3777                                           const GCNSubtarget &ST) {
3778   const SIInstrInfo *TII = ST.getInstrInfo();
3779   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3780   MachineFunction *MF = MBB.getParent();
3781   MachineRegisterInfo &MRI = MF->getRegInfo();
3782 
3783   Register Dst = MI.getOperand(0).getReg();
3784   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3785   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3786   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3787 
3788   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3789   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3790 
3791   unsigned SubReg;
3792   std::tie(SubReg, Offset)
3793     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3794 
3795   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3796 
3797   // Check for a SGPR index.
3798   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3799     MachineBasicBlock::iterator I(&MI);
3800     const DebugLoc &DL = MI.getDebugLoc();
3801 
3802     if (UseGPRIdxMode) {
3803       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3804       // to avoid interfering with other uses, so probably requires a new
3805       // optimization pass.
3806       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3807 
3808       const MCInstrDesc &GPRIDXDesc =
3809           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3810       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3811           .addReg(SrcReg)
3812           .addReg(Idx)
3813           .addImm(SubReg);
3814     } else {
3815       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3816 
3817       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3818         .addReg(SrcReg, 0, SubReg)
3819         .addReg(SrcReg, RegState::Implicit);
3820     }
3821 
3822     MI.eraseFromParent();
3823 
3824     return &MBB;
3825   }
3826 
3827   // Control flow needs to be inserted if indexing with a VGPR.
3828   const DebugLoc &DL = MI.getDebugLoc();
3829   MachineBasicBlock::iterator I(&MI);
3830 
3831   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3832   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3833 
3834   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3835 
3836   Register SGPRIdxReg;
3837   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3838                               UseGPRIdxMode, SGPRIdxReg);
3839 
3840   MachineBasicBlock *LoopBB = InsPt->getParent();
3841 
3842   if (UseGPRIdxMode) {
3843     const MCInstrDesc &GPRIDXDesc =
3844         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3845 
3846     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3847         .addReg(SrcReg)
3848         .addReg(SGPRIdxReg)
3849         .addImm(SubReg);
3850   } else {
3851     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3852       .addReg(SrcReg, 0, SubReg)
3853       .addReg(SrcReg, RegState::Implicit);
3854   }
3855 
3856   MI.eraseFromParent();
3857 
3858   return LoopBB;
3859 }
3860 
3861 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3862                                           MachineBasicBlock &MBB,
3863                                           const GCNSubtarget &ST) {
3864   const SIInstrInfo *TII = ST.getInstrInfo();
3865   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3866   MachineFunction *MF = MBB.getParent();
3867   MachineRegisterInfo &MRI = MF->getRegInfo();
3868 
3869   Register Dst = MI.getOperand(0).getReg();
3870   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3871   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3872   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3873   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3874   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3875   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3876 
3877   // This can be an immediate, but will be folded later.
3878   assert(Val->getReg());
3879 
3880   unsigned SubReg;
3881   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3882                                                          SrcVec->getReg(),
3883                                                          Offset);
3884   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3885 
3886   if (Idx->getReg() == AMDGPU::NoRegister) {
3887     MachineBasicBlock::iterator I(&MI);
3888     const DebugLoc &DL = MI.getDebugLoc();
3889 
3890     assert(Offset == 0);
3891 
3892     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3893         .add(*SrcVec)
3894         .add(*Val)
3895         .addImm(SubReg);
3896 
3897     MI.eraseFromParent();
3898     return &MBB;
3899   }
3900 
3901   // Check for a SGPR index.
3902   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3903     MachineBasicBlock::iterator I(&MI);
3904     const DebugLoc &DL = MI.getDebugLoc();
3905 
3906     if (UseGPRIdxMode) {
3907       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3908 
3909       const MCInstrDesc &GPRIDXDesc =
3910           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3911       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3912           .addReg(SrcVec->getReg())
3913           .add(*Val)
3914           .addReg(Idx)
3915           .addImm(SubReg);
3916     } else {
3917       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3918 
3919       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3920           TRI.getRegSizeInBits(*VecRC), 32, false);
3921       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3922           .addReg(SrcVec->getReg())
3923           .add(*Val)
3924           .addImm(SubReg);
3925     }
3926     MI.eraseFromParent();
3927     return &MBB;
3928   }
3929 
3930   // Control flow needs to be inserted if indexing with a VGPR.
3931   if (Val->isReg())
3932     MRI.clearKillFlags(Val->getReg());
3933 
3934   const DebugLoc &DL = MI.getDebugLoc();
3935 
3936   Register PhiReg = MRI.createVirtualRegister(VecRC);
3937 
3938   Register SGPRIdxReg;
3939   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3940                               UseGPRIdxMode, SGPRIdxReg);
3941   MachineBasicBlock *LoopBB = InsPt->getParent();
3942 
3943   if (UseGPRIdxMode) {
3944     const MCInstrDesc &GPRIDXDesc =
3945         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3946 
3947     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3948         .addReg(PhiReg)
3949         .add(*Val)
3950         .addReg(SGPRIdxReg)
3951         .addImm(AMDGPU::sub0);
3952   } else {
3953     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3954         TRI.getRegSizeInBits(*VecRC), 32, false);
3955     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3956         .addReg(PhiReg)
3957         .add(*Val)
3958         .addImm(AMDGPU::sub0);
3959   }
3960 
3961   MI.eraseFromParent();
3962   return LoopBB;
3963 }
3964 
3965 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3966   MachineInstr &MI, MachineBasicBlock *BB) const {
3967 
3968   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3969   MachineFunction *MF = BB->getParent();
3970   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3971 
3972   switch (MI.getOpcode()) {
3973   case AMDGPU::S_UADDO_PSEUDO:
3974   case AMDGPU::S_USUBO_PSEUDO: {
3975     const DebugLoc &DL = MI.getDebugLoc();
3976     MachineOperand &Dest0 = MI.getOperand(0);
3977     MachineOperand &Dest1 = MI.getOperand(1);
3978     MachineOperand &Src0 = MI.getOperand(2);
3979     MachineOperand &Src1 = MI.getOperand(3);
3980 
3981     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3982                        ? AMDGPU::S_ADD_I32
3983                        : AMDGPU::S_SUB_I32;
3984     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3985 
3986     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3987         .addImm(1)
3988         .addImm(0);
3989 
3990     MI.eraseFromParent();
3991     return BB;
3992   }
3993   case AMDGPU::S_ADD_U64_PSEUDO:
3994   case AMDGPU::S_SUB_U64_PSEUDO: {
3995     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3996     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3997     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3998     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3999     const DebugLoc &DL = MI.getDebugLoc();
4000 
4001     MachineOperand &Dest = MI.getOperand(0);
4002     MachineOperand &Src0 = MI.getOperand(1);
4003     MachineOperand &Src1 = MI.getOperand(2);
4004 
4005     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4006     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4007 
4008     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4009         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4010     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4011         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4012 
4013     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4014         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4015     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4016         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4017 
4018     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4019 
4020     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4021     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4022     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4023     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4024     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4025         .addReg(DestSub0)
4026         .addImm(AMDGPU::sub0)
4027         .addReg(DestSub1)
4028         .addImm(AMDGPU::sub1);
4029     MI.eraseFromParent();
4030     return BB;
4031   }
4032   case AMDGPU::V_ADD_U64_PSEUDO:
4033   case AMDGPU::V_SUB_U64_PSEUDO: {
4034     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4035     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4036     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4037     const DebugLoc &DL = MI.getDebugLoc();
4038 
4039     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4040 
4041     MachineOperand &Dest = MI.getOperand(0);
4042     MachineOperand &Src0 = MI.getOperand(1);
4043     MachineOperand &Src1 = MI.getOperand(2);
4044 
4045     if (IsAdd && ST.hasLshlAddB64()) {
4046       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4047                          Dest.getReg())
4048                      .add(Src0)
4049                      .addImm(0)
4050                      .add(Src1);
4051       TII->legalizeOperands(*Add);
4052       MI.eraseFromParent();
4053       return BB;
4054     }
4055 
4056     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4057 
4058     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4059     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4060 
4061     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4062     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4063 
4064     const TargetRegisterClass *Src0RC = Src0.isReg()
4065                                             ? MRI.getRegClass(Src0.getReg())
4066                                             : &AMDGPU::VReg_64RegClass;
4067     const TargetRegisterClass *Src1RC = Src1.isReg()
4068                                             ? MRI.getRegClass(Src1.getReg())
4069                                             : &AMDGPU::VReg_64RegClass;
4070 
4071     const TargetRegisterClass *Src0SubRC =
4072         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4073     const TargetRegisterClass *Src1SubRC =
4074         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4075 
4076     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4077         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4078     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4079         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4080 
4081     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4082         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4083     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4085 
4086     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4087     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4088                                .addReg(CarryReg, RegState::Define)
4089                                .add(SrcReg0Sub0)
4090                                .add(SrcReg1Sub0)
4091                                .addImm(0); // clamp bit
4092 
4093     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4094     MachineInstr *HiHalf =
4095         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4096             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4097             .add(SrcReg0Sub1)
4098             .add(SrcReg1Sub1)
4099             .addReg(CarryReg, RegState::Kill)
4100             .addImm(0); // clamp bit
4101 
4102     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4103         .addReg(DestSub0)
4104         .addImm(AMDGPU::sub0)
4105         .addReg(DestSub1)
4106         .addImm(AMDGPU::sub1);
4107     TII->legalizeOperands(*LoHalf);
4108     TII->legalizeOperands(*HiHalf);
4109     MI.eraseFromParent();
4110     return BB;
4111   }
4112   case AMDGPU::S_ADD_CO_PSEUDO:
4113   case AMDGPU::S_SUB_CO_PSEUDO: {
4114     // This pseudo has a chance to be selected
4115     // only from uniform add/subcarry node. All the VGPR operands
4116     // therefore assumed to be splat vectors.
4117     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4118     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4119     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4120     MachineBasicBlock::iterator MII = MI;
4121     const DebugLoc &DL = MI.getDebugLoc();
4122     MachineOperand &Dest = MI.getOperand(0);
4123     MachineOperand &CarryDest = MI.getOperand(1);
4124     MachineOperand &Src0 = MI.getOperand(2);
4125     MachineOperand &Src1 = MI.getOperand(3);
4126     MachineOperand &Src2 = MI.getOperand(4);
4127     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4128                        ? AMDGPU::S_ADDC_U32
4129                        : AMDGPU::S_SUBB_U32;
4130     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4131       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4132       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4133           .addReg(Src0.getReg());
4134       Src0.setReg(RegOp0);
4135     }
4136     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4137       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4138       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4139           .addReg(Src1.getReg());
4140       Src1.setReg(RegOp1);
4141     }
4142     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4143     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4144       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4145           .addReg(Src2.getReg());
4146       Src2.setReg(RegOp2);
4147     }
4148 
4149     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4150     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4151     assert(WaveSize == 64 || WaveSize == 32);
4152 
4153     if (WaveSize == 64) {
4154       if (ST.hasScalarCompareEq64()) {
4155         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4156             .addReg(Src2.getReg())
4157             .addImm(0);
4158       } else {
4159         const TargetRegisterClass *SubRC =
4160             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4161         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4162             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4163         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4164             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4165         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4166 
4167         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4168             .add(Src2Sub0)
4169             .add(Src2Sub1);
4170 
4171         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4172             .addReg(Src2_32, RegState::Kill)
4173             .addImm(0);
4174       }
4175     } else {
4176       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4177           .addReg(Src2.getReg())
4178           .addImm(0);
4179     }
4180 
4181     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4182 
4183     unsigned SelOpc =
4184         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4185 
4186     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4187         .addImm(-1)
4188         .addImm(0);
4189 
4190     MI.eraseFromParent();
4191     return BB;
4192   }
4193   case AMDGPU::SI_INIT_M0: {
4194     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4195             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4196         .add(MI.getOperand(0));
4197     MI.eraseFromParent();
4198     return BB;
4199   }
4200   case AMDGPU::GET_GROUPSTATICSIZE: {
4201     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4202            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4203     DebugLoc DL = MI.getDebugLoc();
4204     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4205         .add(MI.getOperand(0))
4206         .addImm(MFI->getLDSSize());
4207     MI.eraseFromParent();
4208     return BB;
4209   }
4210   case AMDGPU::SI_INDIRECT_SRC_V1:
4211   case AMDGPU::SI_INDIRECT_SRC_V2:
4212   case AMDGPU::SI_INDIRECT_SRC_V4:
4213   case AMDGPU::SI_INDIRECT_SRC_V8:
4214   case AMDGPU::SI_INDIRECT_SRC_V16:
4215   case AMDGPU::SI_INDIRECT_SRC_V32:
4216     return emitIndirectSrc(MI, *BB, *getSubtarget());
4217   case AMDGPU::SI_INDIRECT_DST_V1:
4218   case AMDGPU::SI_INDIRECT_DST_V2:
4219   case AMDGPU::SI_INDIRECT_DST_V4:
4220   case AMDGPU::SI_INDIRECT_DST_V8:
4221   case AMDGPU::SI_INDIRECT_DST_V16:
4222   case AMDGPU::SI_INDIRECT_DST_V32:
4223     return emitIndirectDst(MI, *BB, *getSubtarget());
4224   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4225   case AMDGPU::SI_KILL_I1_PSEUDO:
4226     return splitKillBlock(MI, BB);
4227   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4228     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4229     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4230     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4231 
4232     Register Dst = MI.getOperand(0).getReg();
4233     Register Src0 = MI.getOperand(1).getReg();
4234     Register Src1 = MI.getOperand(2).getReg();
4235     const DebugLoc &DL = MI.getDebugLoc();
4236     Register SrcCond = MI.getOperand(3).getReg();
4237 
4238     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4239     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4240     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4241     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4242 
4243     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4244       .addReg(SrcCond);
4245     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4246       .addImm(0)
4247       .addReg(Src0, 0, AMDGPU::sub0)
4248       .addImm(0)
4249       .addReg(Src1, 0, AMDGPU::sub0)
4250       .addReg(SrcCondCopy);
4251     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4252       .addImm(0)
4253       .addReg(Src0, 0, AMDGPU::sub1)
4254       .addImm(0)
4255       .addReg(Src1, 0, AMDGPU::sub1)
4256       .addReg(SrcCondCopy);
4257 
4258     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4259       .addReg(DstLo)
4260       .addImm(AMDGPU::sub0)
4261       .addReg(DstHi)
4262       .addImm(AMDGPU::sub1);
4263     MI.eraseFromParent();
4264     return BB;
4265   }
4266   case AMDGPU::SI_BR_UNDEF: {
4267     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4268     const DebugLoc &DL = MI.getDebugLoc();
4269     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4270                            .add(MI.getOperand(0));
4271     Br->getOperand(1).setIsUndef(true); // read undef SCC
4272     MI.eraseFromParent();
4273     return BB;
4274   }
4275   case AMDGPU::ADJCALLSTACKUP:
4276   case AMDGPU::ADJCALLSTACKDOWN: {
4277     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4278     MachineInstrBuilder MIB(*MF, &MI);
4279     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4280        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4281     return BB;
4282   }
4283   case AMDGPU::SI_CALL_ISEL: {
4284     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4285     const DebugLoc &DL = MI.getDebugLoc();
4286 
4287     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4288 
4289     MachineInstrBuilder MIB;
4290     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4291 
4292     for (const MachineOperand &MO : MI.operands())
4293       MIB.add(MO);
4294 
4295     MIB.cloneMemRefs(MI);
4296     MI.eraseFromParent();
4297     return BB;
4298   }
4299   case AMDGPU::V_ADD_CO_U32_e32:
4300   case AMDGPU::V_SUB_CO_U32_e32:
4301   case AMDGPU::V_SUBREV_CO_U32_e32: {
4302     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4303     const DebugLoc &DL = MI.getDebugLoc();
4304     unsigned Opc = MI.getOpcode();
4305 
4306     bool NeedClampOperand = false;
4307     if (TII->pseudoToMCOpcode(Opc) == -1) {
4308       Opc = AMDGPU::getVOPe64(Opc);
4309       NeedClampOperand = true;
4310     }
4311 
4312     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4313     if (TII->isVOP3(*I)) {
4314       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4315       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4316       I.addReg(TRI->getVCC(), RegState::Define);
4317     }
4318     I.add(MI.getOperand(1))
4319      .add(MI.getOperand(2));
4320     if (NeedClampOperand)
4321       I.addImm(0); // clamp bit for e64 encoding
4322 
4323     TII->legalizeOperands(*I);
4324 
4325     MI.eraseFromParent();
4326     return BB;
4327   }
4328   case AMDGPU::V_ADDC_U32_e32:
4329   case AMDGPU::V_SUBB_U32_e32:
4330   case AMDGPU::V_SUBBREV_U32_e32:
4331     // These instructions have an implicit use of vcc which counts towards the
4332     // constant bus limit.
4333     TII->legalizeOperands(MI);
4334     return BB;
4335   case AMDGPU::DS_GWS_INIT:
4336   case AMDGPU::DS_GWS_SEMA_BR:
4337   case AMDGPU::DS_GWS_BARRIER:
4338     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
4339     LLVM_FALLTHROUGH;
4340   case AMDGPU::DS_GWS_SEMA_V:
4341   case AMDGPU::DS_GWS_SEMA_P:
4342   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4343     // A s_waitcnt 0 is required to be the instruction immediately following.
4344     if (getSubtarget()->hasGWSAutoReplay()) {
4345       bundleInstWithWaitcnt(MI);
4346       return BB;
4347     }
4348 
4349     return emitGWSMemViolTestLoop(MI, BB);
4350   case AMDGPU::S_SETREG_B32: {
4351     // Try to optimize cases that only set the denormal mode or rounding mode.
4352     //
4353     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4354     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4355     // instead.
4356     //
4357     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4358     // allow you to have a no side effect instruction in the output of a
4359     // sideeffecting pattern.
4360     unsigned ID, Offset, Width;
4361     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4362     if (ID != AMDGPU::Hwreg::ID_MODE)
4363       return BB;
4364 
4365     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4366     const unsigned SetMask = WidthMask << Offset;
4367 
4368     if (getSubtarget()->hasDenormModeInst()) {
4369       unsigned SetDenormOp = 0;
4370       unsigned SetRoundOp = 0;
4371 
4372       // The dedicated instructions can only set the whole denorm or round mode
4373       // at once, not a subset of bits in either.
4374       if (SetMask ==
4375           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4376         // If this fully sets both the round and denorm mode, emit the two
4377         // dedicated instructions for these.
4378         SetRoundOp = AMDGPU::S_ROUND_MODE;
4379         SetDenormOp = AMDGPU::S_DENORM_MODE;
4380       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4381         SetRoundOp = AMDGPU::S_ROUND_MODE;
4382       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4383         SetDenormOp = AMDGPU::S_DENORM_MODE;
4384       }
4385 
4386       if (SetRoundOp || SetDenormOp) {
4387         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4388         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4389         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4390           unsigned ImmVal = Def->getOperand(1).getImm();
4391           if (SetRoundOp) {
4392             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4393                 .addImm(ImmVal & 0xf);
4394 
4395             // If we also have the denorm mode, get just the denorm mode bits.
4396             ImmVal >>= 4;
4397           }
4398 
4399           if (SetDenormOp) {
4400             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4401                 .addImm(ImmVal & 0xf);
4402           }
4403 
4404           MI.eraseFromParent();
4405           return BB;
4406         }
4407       }
4408     }
4409 
4410     // If only FP bits are touched, used the no side effects pseudo.
4411     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4412                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4413       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4414 
4415     return BB;
4416   }
4417   default:
4418     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4419   }
4420 }
4421 
4422 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4423   return isTypeLegal(VT.getScalarType());
4424 }
4425 
4426 bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const {
4427   switch (Op.getValue(0).getSimpleValueType().SimpleTy) {
4428   case MVT::f32:
4429     return Subtarget->hasAtomicFaddRtnInsts();
4430   case MVT::v2f16:
4431   case MVT::f64:
4432     return Subtarget->hasGFX90AInsts();
4433   default:
4434     return false;
4435   }
4436 }
4437 
4438 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4439   // This currently forces unfolding various combinations of fsub into fma with
4440   // free fneg'd operands. As long as we have fast FMA (controlled by
4441   // isFMAFasterThanFMulAndFAdd), we should perform these.
4442 
4443   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4444   // most of these combines appear to be cycle neutral but save on instruction
4445   // count / code size.
4446   return true;
4447 }
4448 
4449 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4450 
4451 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4452                                          EVT VT) const {
4453   if (!VT.isVector()) {
4454     return MVT::i1;
4455   }
4456   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4457 }
4458 
4459 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4460   // TODO: Should i16 be used always if legal? For now it would force VALU
4461   // shifts.
4462   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4463 }
4464 
4465 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4466   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4467              ? Ty.changeElementSize(16)
4468              : Ty.changeElementSize(32);
4469 }
4470 
4471 // Answering this is somewhat tricky and depends on the specific device which
4472 // have different rates for fma or all f64 operations.
4473 //
4474 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4475 // regardless of which device (although the number of cycles differs between
4476 // devices), so it is always profitable for f64.
4477 //
4478 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4479 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4480 // which we can always do even without fused FP ops since it returns the same
4481 // result as the separate operations and since it is always full
4482 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4483 // however does not support denormals, so we do report fma as faster if we have
4484 // a fast fma device and require denormals.
4485 //
4486 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4487                                                   EVT VT) const {
4488   VT = VT.getScalarType();
4489 
4490   switch (VT.getSimpleVT().SimpleTy) {
4491   case MVT::f32: {
4492     // If mad is not available this depends only on if f32 fma is full rate.
4493     if (!Subtarget->hasMadMacF32Insts())
4494       return Subtarget->hasFastFMAF32();
4495 
4496     // Otherwise f32 mad is always full rate and returns the same result as
4497     // the separate operations so should be preferred over fma.
4498     // However does not support denormals.
4499     if (hasFP32Denormals(MF))
4500       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4501 
4502     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4503     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4504   }
4505   case MVT::f64:
4506     return true;
4507   case MVT::f16:
4508     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4509   default:
4510     break;
4511   }
4512 
4513   return false;
4514 }
4515 
4516 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4517                                                   LLT Ty) const {
4518   switch (Ty.getScalarSizeInBits()) {
4519   case 16:
4520     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4521   case 32:
4522     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4523   case 64:
4524     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4525   default:
4526     break;
4527   }
4528 
4529   return false;
4530 }
4531 
4532 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4533   if (!Ty.isScalar())
4534     return false;
4535 
4536   if (Ty.getScalarSizeInBits() == 16)
4537     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4538   if (Ty.getScalarSizeInBits() == 32)
4539     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4540 
4541   return false;
4542 }
4543 
4544 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4545                                    const SDNode *N) const {
4546   // TODO: Check future ftz flag
4547   // v_mad_f32/v_mac_f32 do not support denormals.
4548   EVT VT = N->getValueType(0);
4549   if (VT == MVT::f32)
4550     return Subtarget->hasMadMacF32Insts() &&
4551            !hasFP32Denormals(DAG.getMachineFunction());
4552   if (VT == MVT::f16) {
4553     return Subtarget->hasMadF16() &&
4554            !hasFP64FP16Denormals(DAG.getMachineFunction());
4555   }
4556 
4557   return false;
4558 }
4559 
4560 //===----------------------------------------------------------------------===//
4561 // Custom DAG Lowering Operations
4562 //===----------------------------------------------------------------------===//
4563 
4564 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4565 // wider vector type is legal.
4566 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4567                                              SelectionDAG &DAG) const {
4568   unsigned Opc = Op.getOpcode();
4569   EVT VT = Op.getValueType();
4570   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4571 
4572   SDValue Lo, Hi;
4573   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4574 
4575   SDLoc SL(Op);
4576   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4577                              Op->getFlags());
4578   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4579                              Op->getFlags());
4580 
4581   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4582 }
4583 
4584 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4585 // wider vector type is legal.
4586 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4587                                               SelectionDAG &DAG) const {
4588   unsigned Opc = Op.getOpcode();
4589   EVT VT = Op.getValueType();
4590   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4591          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 ||
4592          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
4593          VT == MVT::v32f32);
4594 
4595   SDValue Lo0, Hi0;
4596   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4597   SDValue Lo1, Hi1;
4598   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4599 
4600   SDLoc SL(Op);
4601 
4602   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4603                              Op->getFlags());
4604   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4605                              Op->getFlags());
4606 
4607   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4608 }
4609 
4610 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4611                                               SelectionDAG &DAG) const {
4612   unsigned Opc = Op.getOpcode();
4613   EVT VT = Op.getValueType();
4614   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4615          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 ||
4616          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
4617          VT == MVT::v32f32);
4618 
4619   SDValue Lo0, Hi0;
4620   SDValue Op0 = Op.getOperand(0);
4621   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4622                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4623                          : std::make_pair(Op0, Op0);
4624   SDValue Lo1, Hi1;
4625   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4626   SDValue Lo2, Hi2;
4627   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4628 
4629   SDLoc SL(Op);
4630   auto ResVT = DAG.GetSplitDestVTs(VT);
4631 
4632   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4633                              Op->getFlags());
4634   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4635                              Op->getFlags());
4636 
4637   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4638 }
4639 
4640 
4641 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4642   switch (Op.getOpcode()) {
4643   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4644   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4645   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4646   case ISD::LOAD: {
4647     SDValue Result = LowerLOAD(Op, DAG);
4648     assert((!Result.getNode() ||
4649             Result.getNode()->getNumValues() == 2) &&
4650            "Load should return a value and a chain");
4651     return Result;
4652   }
4653 
4654   case ISD::FSIN:
4655   case ISD::FCOS:
4656     return LowerTrig(Op, DAG);
4657   case ISD::SELECT: return LowerSELECT(Op, DAG);
4658   case ISD::FDIV: return LowerFDIV(Op, DAG);
4659   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4660   case ISD::STORE: return LowerSTORE(Op, DAG);
4661   case ISD::GlobalAddress: {
4662     MachineFunction &MF = DAG.getMachineFunction();
4663     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4664     return LowerGlobalAddress(MFI, Op, DAG);
4665   }
4666   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4667   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4668   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4669   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4670   case ISD::INSERT_SUBVECTOR:
4671     return lowerINSERT_SUBVECTOR(Op, DAG);
4672   case ISD::INSERT_VECTOR_ELT:
4673     return lowerINSERT_VECTOR_ELT(Op, DAG);
4674   case ISD::EXTRACT_VECTOR_ELT:
4675     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4676   case ISD::VECTOR_SHUFFLE:
4677     return lowerVECTOR_SHUFFLE(Op, DAG);
4678   case ISD::SCALAR_TO_VECTOR:
4679     return lowerSCALAR_TO_VECTOR(Op, DAG);
4680   case ISD::BUILD_VECTOR:
4681     return lowerBUILD_VECTOR(Op, DAG);
4682   case ISD::FP_ROUND:
4683     return lowerFP_ROUND(Op, DAG);
4684   case ISD::FPTRUNC_ROUND: {
4685     unsigned Opc;
4686     SDLoc DL(Op);
4687 
4688     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4689       return SDValue();
4690 
4691     // Get the rounding mode from the last operand
4692     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4693     if (RoundMode == (int)RoundingMode::TowardPositive)
4694       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4695     else if (RoundMode == (int)RoundingMode::TowardNegative)
4696       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4697     else
4698       return SDValue();
4699 
4700     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4701   }
4702   case ISD::TRAP:
4703     return lowerTRAP(Op, DAG);
4704   case ISD::DEBUGTRAP:
4705     return lowerDEBUGTRAP(Op, DAG);
4706   case ISD::FABS:
4707   case ISD::FNEG:
4708   case ISD::FCANONICALIZE:
4709   case ISD::BSWAP:
4710     return splitUnaryVectorOp(Op, DAG);
4711   case ISD::FMINNUM:
4712   case ISD::FMAXNUM:
4713     return lowerFMINNUM_FMAXNUM(Op, DAG);
4714   case ISD::FMA:
4715     return splitTernaryVectorOp(Op, DAG);
4716   case ISD::FP_TO_SINT:
4717   case ISD::FP_TO_UINT:
4718     return LowerFP_TO_INT(Op, DAG);
4719   case ISD::SHL:
4720   case ISD::SRA:
4721   case ISD::SRL:
4722   case ISD::ADD:
4723   case ISD::SUB:
4724   case ISD::MUL:
4725   case ISD::SMIN:
4726   case ISD::SMAX:
4727   case ISD::UMIN:
4728   case ISD::UMAX:
4729   case ISD::FADD:
4730   case ISD::FMUL:
4731   case ISD::FMINNUM_IEEE:
4732   case ISD::FMAXNUM_IEEE:
4733   case ISD::UADDSAT:
4734   case ISD::USUBSAT:
4735   case ISD::SADDSAT:
4736   case ISD::SSUBSAT:
4737     return splitBinaryVectorOp(Op, DAG);
4738   case ISD::SMULO:
4739   case ISD::UMULO:
4740     return lowerXMULO(Op, DAG);
4741   case ISD::SMUL_LOHI:
4742   case ISD::UMUL_LOHI:
4743     return lowerXMUL_LOHI(Op, DAG);
4744   case ISD::DYNAMIC_STACKALLOC:
4745     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4746   }
4747   return SDValue();
4748 }
4749 
4750 // Used for D16: Casts the result of an instruction into the right vector,
4751 // packs values if loads return unpacked values.
4752 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4753                                        const SDLoc &DL,
4754                                        SelectionDAG &DAG, bool Unpacked) {
4755   if (!LoadVT.isVector())
4756     return Result;
4757 
4758   // Cast back to the original packed type or to a larger type that is a
4759   // multiple of 32 bit for D16. Widening the return type is a required for
4760   // legalization.
4761   EVT FittingLoadVT = LoadVT;
4762   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4763     FittingLoadVT =
4764         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4765                          LoadVT.getVectorNumElements() + 1);
4766   }
4767 
4768   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4769     // Truncate to v2i16/v4i16.
4770     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4771 
4772     // Workaround legalizer not scalarizing truncate after vector op
4773     // legalization but not creating intermediate vector trunc.
4774     SmallVector<SDValue, 4> Elts;
4775     DAG.ExtractVectorElements(Result, Elts);
4776     for (SDValue &Elt : Elts)
4777       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4778 
4779     // Pad illegal v1i16/v3fi6 to v4i16
4780     if ((LoadVT.getVectorNumElements() % 2) == 1)
4781       Elts.push_back(DAG.getUNDEF(MVT::i16));
4782 
4783     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4784 
4785     // Bitcast to original type (v2f16/v4f16).
4786     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4787   }
4788 
4789   // Cast back to the original packed type.
4790   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4791 }
4792 
4793 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4794                                               MemSDNode *M,
4795                                               SelectionDAG &DAG,
4796                                               ArrayRef<SDValue> Ops,
4797                                               bool IsIntrinsic) const {
4798   SDLoc DL(M);
4799 
4800   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4801   EVT LoadVT = M->getValueType(0);
4802 
4803   EVT EquivLoadVT = LoadVT;
4804   if (LoadVT.isVector()) {
4805     if (Unpacked) {
4806       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4807                                      LoadVT.getVectorNumElements());
4808     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4809       // Widen v3f16 to legal type
4810       EquivLoadVT =
4811           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4812                            LoadVT.getVectorNumElements() + 1);
4813     }
4814   }
4815 
4816   // Change from v4f16/v2f16 to EquivLoadVT.
4817   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4818 
4819   SDValue Load
4820     = DAG.getMemIntrinsicNode(
4821       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4822       VTList, Ops, M->getMemoryVT(),
4823       M->getMemOperand());
4824 
4825   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4826 
4827   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4828 }
4829 
4830 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4831                                              SelectionDAG &DAG,
4832                                              ArrayRef<SDValue> Ops) const {
4833   SDLoc DL(M);
4834   EVT LoadVT = M->getValueType(0);
4835   EVT EltType = LoadVT.getScalarType();
4836   EVT IntVT = LoadVT.changeTypeToInteger();
4837 
4838   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4839 
4840   unsigned Opc =
4841       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4842 
4843   if (IsD16) {
4844     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4845   }
4846 
4847   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4848   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4849     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4850 
4851   if (isTypeLegal(LoadVT)) {
4852     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4853                                M->getMemOperand(), DAG);
4854   }
4855 
4856   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4857   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4858   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4859                                         M->getMemOperand(), DAG);
4860   return DAG.getMergeValues(
4861       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4862       DL);
4863 }
4864 
4865 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4866                                   SDNode *N, SelectionDAG &DAG) {
4867   EVT VT = N->getValueType(0);
4868   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4869   unsigned CondCode = CD->getZExtValue();
4870   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4871     return DAG.getUNDEF(VT);
4872 
4873   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4874 
4875   SDValue LHS = N->getOperand(1);
4876   SDValue RHS = N->getOperand(2);
4877 
4878   SDLoc DL(N);
4879 
4880   EVT CmpVT = LHS.getValueType();
4881   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4882     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4883       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4884     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4885     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4886   }
4887 
4888   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4889 
4890   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4891   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4892 
4893   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4894                               DAG.getCondCode(CCOpcode));
4895   if (VT.bitsEq(CCVT))
4896     return SetCC;
4897   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4898 }
4899 
4900 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4901                                   SDNode *N, SelectionDAG &DAG) {
4902   EVT VT = N->getValueType(0);
4903   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4904 
4905   unsigned CondCode = CD->getZExtValue();
4906   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4907     return DAG.getUNDEF(VT);
4908 
4909   SDValue Src0 = N->getOperand(1);
4910   SDValue Src1 = N->getOperand(2);
4911   EVT CmpVT = Src0.getValueType();
4912   SDLoc SL(N);
4913 
4914   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4915     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4916     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4917   }
4918 
4919   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4920   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4921   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4922   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4923   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4924                               Src1, DAG.getCondCode(CCOpcode));
4925   if (VT.bitsEq(CCVT))
4926     return SetCC;
4927   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4928 }
4929 
4930 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4931                                     SelectionDAG &DAG) {
4932   EVT VT = N->getValueType(0);
4933   SDValue Src = N->getOperand(1);
4934   SDLoc SL(N);
4935 
4936   if (Src.getOpcode() == ISD::SETCC) {
4937     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4938     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4939                        Src.getOperand(1), Src.getOperand(2));
4940   }
4941   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4942     // (ballot 0) -> 0
4943     if (Arg->isZero())
4944       return DAG.getConstant(0, SL, VT);
4945 
4946     // (ballot 1) -> EXEC/EXEC_LO
4947     if (Arg->isOne()) {
4948       Register Exec;
4949       if (VT.getScalarSizeInBits() == 32)
4950         Exec = AMDGPU::EXEC_LO;
4951       else if (VT.getScalarSizeInBits() == 64)
4952         Exec = AMDGPU::EXEC;
4953       else
4954         return SDValue();
4955 
4956       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4957     }
4958   }
4959 
4960   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4961   // ISD::SETNE)
4962   return DAG.getNode(
4963       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4964       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4965 }
4966 
4967 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4968                                           SmallVectorImpl<SDValue> &Results,
4969                                           SelectionDAG &DAG) const {
4970   switch (N->getOpcode()) {
4971   case ISD::INSERT_VECTOR_ELT: {
4972     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4973       Results.push_back(Res);
4974     return;
4975   }
4976   case ISD::EXTRACT_VECTOR_ELT: {
4977     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4978       Results.push_back(Res);
4979     return;
4980   }
4981   case ISD::INTRINSIC_WO_CHAIN: {
4982     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4983     switch (IID) {
4984     case Intrinsic::amdgcn_cvt_pkrtz: {
4985       SDValue Src0 = N->getOperand(1);
4986       SDValue Src1 = N->getOperand(2);
4987       SDLoc SL(N);
4988       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4989                                 Src0, Src1);
4990       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4991       return;
4992     }
4993     case Intrinsic::amdgcn_cvt_pknorm_i16:
4994     case Intrinsic::amdgcn_cvt_pknorm_u16:
4995     case Intrinsic::amdgcn_cvt_pk_i16:
4996     case Intrinsic::amdgcn_cvt_pk_u16: {
4997       SDValue Src0 = N->getOperand(1);
4998       SDValue Src1 = N->getOperand(2);
4999       SDLoc SL(N);
5000       unsigned Opcode;
5001 
5002       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5003         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5004       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5005         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5006       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5007         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5008       else
5009         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5010 
5011       EVT VT = N->getValueType(0);
5012       if (isTypeLegal(VT))
5013         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5014       else {
5015         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5016         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5017       }
5018       return;
5019     }
5020     }
5021     break;
5022   }
5023   case ISD::INTRINSIC_W_CHAIN: {
5024     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5025       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5026         // FIXME: Hacky
5027         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5028           Results.push_back(Res.getOperand(I));
5029         }
5030       } else {
5031         Results.push_back(Res);
5032         Results.push_back(Res.getValue(1));
5033       }
5034       return;
5035     }
5036 
5037     break;
5038   }
5039   case ISD::SELECT: {
5040     SDLoc SL(N);
5041     EVT VT = N->getValueType(0);
5042     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5043     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5044     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5045 
5046     EVT SelectVT = NewVT;
5047     if (NewVT.bitsLT(MVT::i32)) {
5048       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5049       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5050       SelectVT = MVT::i32;
5051     }
5052 
5053     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5054                                     N->getOperand(0), LHS, RHS);
5055 
5056     if (NewVT != SelectVT)
5057       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5058     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5059     return;
5060   }
5061   case ISD::FNEG: {
5062     if (N->getValueType(0) != MVT::v2f16)
5063       break;
5064 
5065     SDLoc SL(N);
5066     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5067 
5068     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5069                              BC,
5070                              DAG.getConstant(0x80008000, SL, MVT::i32));
5071     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5072     return;
5073   }
5074   case ISD::FABS: {
5075     if (N->getValueType(0) != MVT::v2f16)
5076       break;
5077 
5078     SDLoc SL(N);
5079     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5080 
5081     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5082                              BC,
5083                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5084     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5085     return;
5086   }
5087   default:
5088     break;
5089   }
5090 }
5091 
5092 /// Helper function for LowerBRCOND
5093 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5094 
5095   SDNode *Parent = Value.getNode();
5096   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5097        I != E; ++I) {
5098 
5099     if (I.getUse().get() != Value)
5100       continue;
5101 
5102     if (I->getOpcode() == Opcode)
5103       return *I;
5104   }
5105   return nullptr;
5106 }
5107 
5108 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5109   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5110     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5111     case Intrinsic::amdgcn_if:
5112       return AMDGPUISD::IF;
5113     case Intrinsic::amdgcn_else:
5114       return AMDGPUISD::ELSE;
5115     case Intrinsic::amdgcn_loop:
5116       return AMDGPUISD::LOOP;
5117     case Intrinsic::amdgcn_end_cf:
5118       llvm_unreachable("should not occur");
5119     default:
5120       return 0;
5121     }
5122   }
5123 
5124   // break, if_break, else_break are all only used as inputs to loop, not
5125   // directly as branch conditions.
5126   return 0;
5127 }
5128 
5129 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5130   const Triple &TT = getTargetMachine().getTargetTriple();
5131   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5132           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5133          AMDGPU::shouldEmitConstantsToTextSection(TT);
5134 }
5135 
5136 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5137   // FIXME: Either avoid relying on address space here or change the default
5138   // address space for functions to avoid the explicit check.
5139   return (GV->getValueType()->isFunctionTy() ||
5140           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5141          !shouldEmitFixup(GV) &&
5142          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5143 }
5144 
5145 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5146   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5147 }
5148 
5149 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5150   if (!GV->hasExternalLinkage())
5151     return true;
5152 
5153   const auto OS = getTargetMachine().getTargetTriple().getOS();
5154   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5155 }
5156 
5157 /// This transforms the control flow intrinsics to get the branch destination as
5158 /// last parameter, also switches branch target with BR if the need arise
5159 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5160                                       SelectionDAG &DAG) const {
5161   SDLoc DL(BRCOND);
5162 
5163   SDNode *Intr = BRCOND.getOperand(1).getNode();
5164   SDValue Target = BRCOND.getOperand(2);
5165   SDNode *BR = nullptr;
5166   SDNode *SetCC = nullptr;
5167 
5168   if (Intr->getOpcode() == ISD::SETCC) {
5169     // As long as we negate the condition everything is fine
5170     SetCC = Intr;
5171     Intr = SetCC->getOperand(0).getNode();
5172 
5173   } else {
5174     // Get the target from BR if we don't negate the condition
5175     BR = findUser(BRCOND, ISD::BR);
5176     assert(BR && "brcond missing unconditional branch user");
5177     Target = BR->getOperand(1);
5178   }
5179 
5180   unsigned CFNode = isCFIntrinsic(Intr);
5181   if (CFNode == 0) {
5182     // This is a uniform branch so we don't need to legalize.
5183     return BRCOND;
5184   }
5185 
5186   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5187                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5188 
5189   assert(!SetCC ||
5190         (SetCC->getConstantOperandVal(1) == 1 &&
5191          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5192                                                              ISD::SETNE));
5193 
5194   // operands of the new intrinsic call
5195   SmallVector<SDValue, 4> Ops;
5196   if (HaveChain)
5197     Ops.push_back(BRCOND.getOperand(0));
5198 
5199   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5200   Ops.push_back(Target);
5201 
5202   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5203 
5204   // build the new intrinsic call
5205   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5206 
5207   if (!HaveChain) {
5208     SDValue Ops[] =  {
5209       SDValue(Result, 0),
5210       BRCOND.getOperand(0)
5211     };
5212 
5213     Result = DAG.getMergeValues(Ops, DL).getNode();
5214   }
5215 
5216   if (BR) {
5217     // Give the branch instruction our target
5218     SDValue Ops[] = {
5219       BR->getOperand(0),
5220       BRCOND.getOperand(2)
5221     };
5222     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5223     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5224   }
5225 
5226   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5227 
5228   // Copy the intrinsic results to registers
5229   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5230     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5231     if (!CopyToReg)
5232       continue;
5233 
5234     Chain = DAG.getCopyToReg(
5235       Chain, DL,
5236       CopyToReg->getOperand(1),
5237       SDValue(Result, i - 1),
5238       SDValue());
5239 
5240     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5241   }
5242 
5243   // Remove the old intrinsic from the chain
5244   DAG.ReplaceAllUsesOfValueWith(
5245     SDValue(Intr, Intr->getNumValues() - 1),
5246     Intr->getOperand(0));
5247 
5248   return Chain;
5249 }
5250 
5251 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5252                                           SelectionDAG &DAG) const {
5253   MVT VT = Op.getSimpleValueType();
5254   SDLoc DL(Op);
5255   // Checking the depth
5256   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5257     return DAG.getConstant(0, DL, VT);
5258 
5259   MachineFunction &MF = DAG.getMachineFunction();
5260   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5261   // Check for kernel and shader functions
5262   if (Info->isEntryFunction())
5263     return DAG.getConstant(0, DL, VT);
5264 
5265   MachineFrameInfo &MFI = MF.getFrameInfo();
5266   // There is a call to @llvm.returnaddress in this function
5267   MFI.setReturnAddressIsTaken(true);
5268 
5269   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5270   // Get the return address reg and mark it as an implicit live-in
5271   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5272 
5273   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5274 }
5275 
5276 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5277                                             SDValue Op,
5278                                             const SDLoc &DL,
5279                                             EVT VT) const {
5280   return Op.getValueType().bitsLE(VT) ?
5281       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5282     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5283                 DAG.getTargetConstant(0, DL, MVT::i32));
5284 }
5285 
5286 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5287   assert(Op.getValueType() == MVT::f16 &&
5288          "Do not know how to custom lower FP_ROUND for non-f16 type");
5289 
5290   SDValue Src = Op.getOperand(0);
5291   EVT SrcVT = Src.getValueType();
5292   if (SrcVT != MVT::f64)
5293     return Op;
5294 
5295   SDLoc DL(Op);
5296 
5297   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5298   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5299   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5300 }
5301 
5302 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5303                                                SelectionDAG &DAG) const {
5304   EVT VT = Op.getValueType();
5305   const MachineFunction &MF = DAG.getMachineFunction();
5306   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5307   bool IsIEEEMode = Info->getMode().IEEE;
5308 
5309   // FIXME: Assert during selection that this is only selected for
5310   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5311   // mode functions, but this happens to be OK since it's only done in cases
5312   // where there is known no sNaN.
5313   if (IsIEEEMode)
5314     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5315 
5316   if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16)
5317     return splitBinaryVectorOp(Op, DAG);
5318   return Op;
5319 }
5320 
5321 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5322   EVT VT = Op.getValueType();
5323   SDLoc SL(Op);
5324   SDValue LHS = Op.getOperand(0);
5325   SDValue RHS = Op.getOperand(1);
5326   bool isSigned = Op.getOpcode() == ISD::SMULO;
5327 
5328   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5329     const APInt &C = RHSC->getAPIntValue();
5330     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5331     if (C.isPowerOf2()) {
5332       // smulo(x, signed_min) is same as umulo(x, signed_min).
5333       bool UseArithShift = isSigned && !C.isMinSignedValue();
5334       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5335       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5336       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5337           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5338                       SL, VT, Result, ShiftAmt),
5339           LHS, ISD::SETNE);
5340       return DAG.getMergeValues({ Result, Overflow }, SL);
5341     }
5342   }
5343 
5344   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5345   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5346                             SL, VT, LHS, RHS);
5347 
5348   SDValue Sign = isSigned
5349     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5350                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5351     : DAG.getConstant(0, SL, VT);
5352   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5353 
5354   return DAG.getMergeValues({ Result, Overflow }, SL);
5355 }
5356 
5357 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5358   if (Op->isDivergent()) {
5359     // Select to V_MAD_[IU]64_[IU]32.
5360     return Op;
5361   }
5362   if (Subtarget->hasSMulHi()) {
5363     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5364     return SDValue();
5365   }
5366   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5367   // calculate the high part, so we might as well do the whole thing with
5368   // V_MAD_[IU]64_[IU]32.
5369   return Op;
5370 }
5371 
5372 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5373   if (!Subtarget->isTrapHandlerEnabled() ||
5374       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5375     return lowerTrapEndpgm(Op, DAG);
5376 
5377   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5378     switch (*HsaAbiVer) {
5379     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5380     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5381       return lowerTrapHsaQueuePtr(Op, DAG);
5382     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5383     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5384       return Subtarget->supportsGetDoorbellID() ?
5385           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5386     }
5387   }
5388 
5389   llvm_unreachable("Unknown trap handler");
5390 }
5391 
5392 SDValue SITargetLowering::lowerTrapEndpgm(
5393     SDValue Op, SelectionDAG &DAG) const {
5394   SDLoc SL(Op);
5395   SDValue Chain = Op.getOperand(0);
5396   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5397 }
5398 
5399 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5400     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5401   MachineFunction &MF = DAG.getMachineFunction();
5402   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5403   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5404   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5405   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5406                      MachineMemOperand::MODereferenceable |
5407                          MachineMemOperand::MOInvariant);
5408 }
5409 
5410 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5411     SDValue Op, SelectionDAG &DAG) const {
5412   SDLoc SL(Op);
5413   SDValue Chain = Op.getOperand(0);
5414 
5415   SDValue QueuePtr;
5416   // For code object version 5, QueuePtr is passed through implicit kernarg.
5417   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5418     QueuePtr =
5419         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5420   } else {
5421     MachineFunction &MF = DAG.getMachineFunction();
5422     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5423     Register UserSGPR = Info->getQueuePtrUserSGPR();
5424 
5425     if (UserSGPR == AMDGPU::NoRegister) {
5426       // We probably are in a function incorrectly marked with
5427       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5428       // trap, so just use a null pointer.
5429       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5430     } else {
5431       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5432                                       MVT::i64);
5433     }
5434   }
5435 
5436   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5437   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5438                                    QueuePtr, SDValue());
5439 
5440   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5441   SDValue Ops[] = {
5442     ToReg,
5443     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5444     SGPR01,
5445     ToReg.getValue(1)
5446   };
5447   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5448 }
5449 
5450 SDValue SITargetLowering::lowerTrapHsa(
5451     SDValue Op, SelectionDAG &DAG) const {
5452   SDLoc SL(Op);
5453   SDValue Chain = Op.getOperand(0);
5454 
5455   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5456   SDValue Ops[] = {
5457     Chain,
5458     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5459   };
5460   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5461 }
5462 
5463 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5464   SDLoc SL(Op);
5465   SDValue Chain = Op.getOperand(0);
5466   MachineFunction &MF = DAG.getMachineFunction();
5467 
5468   if (!Subtarget->isTrapHandlerEnabled() ||
5469       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5470     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5471                                      "debugtrap handler not supported",
5472                                      Op.getDebugLoc(),
5473                                      DS_Warning);
5474     LLVMContext &Ctx = MF.getFunction().getContext();
5475     Ctx.diagnose(NoTrap);
5476     return Chain;
5477   }
5478 
5479   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5480   SDValue Ops[] = {
5481     Chain,
5482     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5483   };
5484   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5485 }
5486 
5487 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5488                                              SelectionDAG &DAG) const {
5489   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5490   if (Subtarget->hasApertureRegs()) {
5491     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5492         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5493         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5494     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5495         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5496         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5497     unsigned Encoding =
5498         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5499         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5500         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5501 
5502     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5503     SDValue ApertureReg = SDValue(
5504         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5505     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5506     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5507   }
5508 
5509   // For code object version 5, private_base and shared_base are passed through
5510   // implicit kernargs.
5511   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5512     ImplicitParameter Param =
5513         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5514     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5515   }
5516 
5517   MachineFunction &MF = DAG.getMachineFunction();
5518   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5519   Register UserSGPR = Info->getQueuePtrUserSGPR();
5520   if (UserSGPR == AMDGPU::NoRegister) {
5521     // We probably are in a function incorrectly marked with
5522     // amdgpu-no-queue-ptr. This is undefined.
5523     return DAG.getUNDEF(MVT::i32);
5524   }
5525 
5526   SDValue QueuePtr = CreateLiveInRegister(
5527     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5528 
5529   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5530   // private_segment_aperture_base_hi.
5531   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5532 
5533   SDValue Ptr =
5534       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5535 
5536   // TODO: Use custom target PseudoSourceValue.
5537   // TODO: We should use the value from the IR intrinsic call, but it might not
5538   // be available and how do we get it?
5539   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5540   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5541                      commonAlignment(Align(64), StructOffset),
5542                      MachineMemOperand::MODereferenceable |
5543                          MachineMemOperand::MOInvariant);
5544 }
5545 
5546 /// Return true if the value is a known valid address, such that a null check is
5547 /// not necessary.
5548 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5549                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5550   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5551       isa<BasicBlockSDNode>(Val))
5552     return true;
5553 
5554   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5555     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5556 
5557   // TODO: Search through arithmetic, handle arguments and loads
5558   // marked nonnull.
5559   return false;
5560 }
5561 
5562 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5563                                              SelectionDAG &DAG) const {
5564   SDLoc SL(Op);
5565   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5566 
5567   SDValue Src = ASC->getOperand(0);
5568   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5569   unsigned SrcAS = ASC->getSrcAddressSpace();
5570 
5571   const AMDGPUTargetMachine &TM =
5572     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5573 
5574   // flat -> local/private
5575   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5576     unsigned DestAS = ASC->getDestAddressSpace();
5577 
5578     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5579         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5580       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5581 
5582       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5583         return Ptr;
5584 
5585       unsigned NullVal = TM.getNullPointerValue(DestAS);
5586       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5587       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5588 
5589       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5590                          SegmentNullPtr);
5591     }
5592   }
5593 
5594   // local/private -> flat
5595   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5596     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5597         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5598 
5599       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5600       SDValue CvtPtr =
5601           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5602       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5603 
5604       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5605         return CvtPtr;
5606 
5607       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5608       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5609 
5610       SDValue NonNull
5611         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5612 
5613       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5614                          FlatNullPtr);
5615     }
5616   }
5617 
5618   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5619       Op.getValueType() == MVT::i64) {
5620     const SIMachineFunctionInfo *Info =
5621         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5622     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5623     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5624     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5625   }
5626 
5627   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5628       Src.getValueType() == MVT::i64)
5629     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5630 
5631   // global <-> flat are no-ops and never emitted.
5632 
5633   const MachineFunction &MF = DAG.getMachineFunction();
5634   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5635     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5636   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5637 
5638   return DAG.getUNDEF(ASC->getValueType(0));
5639 }
5640 
5641 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5642 // the small vector and inserting them into the big vector. That is better than
5643 // the default expansion of doing it via a stack slot. Even though the use of
5644 // the stack slot would be optimized away afterwards, the stack slot itself
5645 // remains.
5646 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5647                                                 SelectionDAG &DAG) const {
5648   SDValue Vec = Op.getOperand(0);
5649   SDValue Ins = Op.getOperand(1);
5650   SDValue Idx = Op.getOperand(2);
5651   EVT VecVT = Vec.getValueType();
5652   EVT InsVT = Ins.getValueType();
5653   EVT EltVT = VecVT.getVectorElementType();
5654   unsigned InsNumElts = InsVT.getVectorNumElements();
5655   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5656   SDLoc SL(Op);
5657 
5658   for (unsigned I = 0; I != InsNumElts; ++I) {
5659     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5660                               DAG.getConstant(I, SL, MVT::i32));
5661     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5662                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5663   }
5664   return Vec;
5665 }
5666 
5667 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5668                                                  SelectionDAG &DAG) const {
5669   SDValue Vec = Op.getOperand(0);
5670   SDValue InsVal = Op.getOperand(1);
5671   SDValue Idx = Op.getOperand(2);
5672   EVT VecVT = Vec.getValueType();
5673   EVT EltVT = VecVT.getVectorElementType();
5674   unsigned VecSize = VecVT.getSizeInBits();
5675   unsigned EltSize = EltVT.getSizeInBits();
5676   SDLoc SL(Op);
5677 
5678   // Specially handle the case of v4i16 with static indexing.
5679   unsigned NumElts = VecVT.getVectorNumElements();
5680   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5681   if (NumElts == 4 && EltSize == 16 && KIdx) {
5682     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5683 
5684     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5685                                  DAG.getConstant(0, SL, MVT::i32));
5686     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5687                                  DAG.getConstant(1, SL, MVT::i32));
5688 
5689     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5690     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5691 
5692     unsigned Idx = KIdx->getZExtValue();
5693     bool InsertLo = Idx < 2;
5694     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5695       InsertLo ? LoVec : HiVec,
5696       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5697       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5698 
5699     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5700 
5701     SDValue Concat = InsertLo ?
5702       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5703       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5704 
5705     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5706   }
5707 
5708   // Static indexing does not lower to stack access, and hence there is no need
5709   // for special custom lowering to avoid stack access.
5710   if (isa<ConstantSDNode>(Idx))
5711     return SDValue();
5712 
5713   // Avoid stack access for dynamic indexing by custom lowering to
5714   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5715 
5716   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5717 
5718   MVT IntVT = MVT::getIntegerVT(VecSize);
5719 
5720   // Convert vector index to bit-index and get the required bit mask.
5721   assert(isPowerOf2_32(EltSize));
5722   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5723   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5724   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5725                             DAG.getConstant(0xffff, SL, IntVT),
5726                             ScaledIdx);
5727 
5728   // 1. Create a congruent vector with the target value in each element.
5729   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5730                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5731 
5732   // 2. Mask off all other indicies except the required index within (1).
5733   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5734 
5735   // 3. Mask off the required index within the target vector.
5736   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5737   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5738                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5739 
5740   // 4. Get (2) and (3) ORed into the target vector.
5741   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5742 
5743   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5744 }
5745 
5746 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5747                                                   SelectionDAG &DAG) const {
5748   SDLoc SL(Op);
5749 
5750   EVT ResultVT = Op.getValueType();
5751   SDValue Vec = Op.getOperand(0);
5752   SDValue Idx = Op.getOperand(1);
5753   EVT VecVT = Vec.getValueType();
5754   unsigned VecSize = VecVT.getSizeInBits();
5755   EVT EltVT = VecVT.getVectorElementType();
5756 
5757   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5758 
5759   // Make sure we do any optimizations that will make it easier to fold
5760   // source modifiers before obscuring it with bit operations.
5761 
5762   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5763   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5764     return Combined;
5765 
5766   if (VecSize == 128 || VecSize == 256) {
5767     SDValue Lo, Hi;
5768     EVT LoVT, HiVT;
5769     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5770 
5771     if (VecSize == 128) {
5772       SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5773       Lo = DAG.getBitcast(LoVT,
5774                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5775                                       DAG.getConstant(0, SL, MVT::i32)));
5776       Hi = DAG.getBitcast(HiVT,
5777                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5778                                       DAG.getConstant(1, SL, MVT::i32)));
5779     } else {
5780       assert(VecSize == 256);
5781 
5782       SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
5783       SDValue Parts[4];
5784       for (unsigned P = 0; P < 4; ++P) {
5785         Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5786                                DAG.getConstant(P, SL, MVT::i32));
5787       }
5788 
5789       Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5790                                             Parts[0], Parts[1]));
5791       Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5792                                             Parts[2], Parts[3]));
5793     }
5794 
5795     EVT IdxVT = Idx.getValueType();
5796     unsigned NElem = VecVT.getVectorNumElements();
5797     assert(isPowerOf2_32(NElem));
5798     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5799     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5800     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5801     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5802   }
5803 
5804   assert(VecSize <= 64);
5805 
5806   MVT IntVT = MVT::getIntegerVT(VecSize);
5807 
5808   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5809   SDValue VecBC = peekThroughBitcasts(Vec);
5810   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5811     SDValue Src = VecBC.getOperand(0);
5812     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5813     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5814   }
5815 
5816   unsigned EltSize = EltVT.getSizeInBits();
5817   assert(isPowerOf2_32(EltSize));
5818 
5819   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5820 
5821   // Convert vector index to bit-index (* EltSize)
5822   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5823 
5824   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5825   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5826 
5827   if (ResultVT == MVT::f16) {
5828     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5829     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5830   }
5831 
5832   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5833 }
5834 
5835 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5836   assert(Elt % 2 == 0);
5837   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5838 }
5839 
5840 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5841                                               SelectionDAG &DAG) const {
5842   SDLoc SL(Op);
5843   EVT ResultVT = Op.getValueType();
5844   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5845 
5846   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5847   EVT EltVT = PackVT.getVectorElementType();
5848   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5849 
5850   // vector_shuffle <0,1,6,7> lhs, rhs
5851   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5852   //
5853   // vector_shuffle <6,7,2,3> lhs, rhs
5854   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5855   //
5856   // vector_shuffle <6,7,0,1> lhs, rhs
5857   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5858 
5859   // Avoid scalarizing when both halves are reading from consecutive elements.
5860   SmallVector<SDValue, 4> Pieces;
5861   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5862     if (elementPairIsContiguous(SVN->getMask(), I)) {
5863       const int Idx = SVN->getMaskElt(I);
5864       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5865       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5866       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5867                                     PackVT, SVN->getOperand(VecIdx),
5868                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5869       Pieces.push_back(SubVec);
5870     } else {
5871       const int Idx0 = SVN->getMaskElt(I);
5872       const int Idx1 = SVN->getMaskElt(I + 1);
5873       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5874       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5875       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5876       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5877 
5878       SDValue Vec0 = SVN->getOperand(VecIdx0);
5879       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5880                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5881 
5882       SDValue Vec1 = SVN->getOperand(VecIdx1);
5883       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5884                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5885       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5886     }
5887   }
5888 
5889   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5890 }
5891 
5892 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5893                                                 SelectionDAG &DAG) const {
5894   SDValue SVal = Op.getOperand(0);
5895   EVT ResultVT = Op.getValueType();
5896   EVT SValVT = SVal.getValueType();
5897   SDValue UndefVal = DAG.getUNDEF(SValVT);
5898   SDLoc SL(Op);
5899 
5900   SmallVector<SDValue, 8> VElts;
5901   VElts.push_back(SVal);
5902   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5903     VElts.push_back(UndefVal);
5904 
5905   return DAG.getBuildVector(ResultVT, SL, VElts);
5906 }
5907 
5908 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5909                                             SelectionDAG &DAG) const {
5910   SDLoc SL(Op);
5911   EVT VT = Op.getValueType();
5912 
5913   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5914       VT == MVT::v8i16 || VT == MVT::v8f16) {
5915     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5916                                   VT.getVectorNumElements() / 2);
5917     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5918 
5919     // Turn into pair of packed build_vectors.
5920     // TODO: Special case for constants that can be materialized with s_mov_b64.
5921     SmallVector<SDValue, 4> LoOps, HiOps;
5922     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5923       LoOps.push_back(Op.getOperand(I));
5924       HiOps.push_back(Op.getOperand(I + E));
5925     }
5926     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5927     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5928 
5929     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5930     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5931 
5932     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5933                                        { CastLo, CastHi });
5934     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5935   }
5936 
5937   if (VT == MVT::v16i16 || VT == MVT::v16f16) {
5938     EVT QuarterVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5939                                      VT.getVectorNumElements() / 4);
5940     MVT QuarterIntVT = MVT::getIntegerVT(QuarterVT.getSizeInBits());
5941 
5942     SmallVector<SDValue, 4> Parts[4];
5943     for (unsigned I = 0, E = VT.getVectorNumElements() / 4; I != E; ++I) {
5944       for (unsigned P = 0; P < 4; ++P)
5945         Parts[P].push_back(Op.getOperand(I + P * E));
5946     }
5947     SDValue Casts[4];
5948     for (unsigned P = 0; P < 4; ++P) {
5949       SDValue Vec = DAG.getBuildVector(QuarterVT, SL, Parts[P]);
5950       Casts[P] = DAG.getNode(ISD::BITCAST, SL, QuarterIntVT, Vec);
5951     }
5952 
5953     SDValue Blend =
5954         DAG.getBuildVector(MVT::getVectorVT(QuarterIntVT, 4), SL, Casts);
5955     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5956   }
5957 
5958   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5959   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5960 
5961   SDValue Lo = Op.getOperand(0);
5962   SDValue Hi = Op.getOperand(1);
5963 
5964   // Avoid adding defined bits with the zero_extend.
5965   if (Hi.isUndef()) {
5966     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5967     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5968     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5969   }
5970 
5971   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5972   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5973 
5974   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5975                               DAG.getConstant(16, SL, MVT::i32));
5976   if (Lo.isUndef())
5977     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5978 
5979   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5980   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5981 
5982   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5983   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5984 }
5985 
5986 bool
5987 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5988   // We can fold offsets for anything that doesn't require a GOT relocation.
5989   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5990           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5991           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5992          !shouldEmitGOTReloc(GA->getGlobal());
5993 }
5994 
5995 static SDValue
5996 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5997                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5998                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5999   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6000   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6001   // lowered to the following code sequence:
6002   //
6003   // For constant address space:
6004   //   s_getpc_b64 s[0:1]
6005   //   s_add_u32 s0, s0, $symbol
6006   //   s_addc_u32 s1, s1, 0
6007   //
6008   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6009   //   a fixup or relocation is emitted to replace $symbol with a literal
6010   //   constant, which is a pc-relative offset from the encoding of the $symbol
6011   //   operand to the global variable.
6012   //
6013   // For global address space:
6014   //   s_getpc_b64 s[0:1]
6015   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6016   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6017   //
6018   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6019   //   fixups or relocations are emitted to replace $symbol@*@lo and
6020   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6021   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6022   //   operand to the global variable.
6023   //
6024   // What we want here is an offset from the value returned by s_getpc
6025   // (which is the address of the s_add_u32 instruction) to the global
6026   // variable, but since the encoding of $symbol starts 4 bytes after the start
6027   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6028   // small. This requires us to add 4 to the global variable offset in order to
6029   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6030   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6031   // instruction.
6032   SDValue PtrLo =
6033       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6034   SDValue PtrHi;
6035   if (GAFlags == SIInstrInfo::MO_NONE) {
6036     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6037   } else {
6038     PtrHi =
6039         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6040   }
6041   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6042 }
6043 
6044 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6045                                              SDValue Op,
6046                                              SelectionDAG &DAG) const {
6047   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6048   SDLoc DL(GSD);
6049   EVT PtrVT = Op.getValueType();
6050 
6051   const GlobalValue *GV = GSD->getGlobal();
6052   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6053        shouldUseLDSConstAddress(GV)) ||
6054       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6055       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6056     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6057         GV->hasExternalLinkage()) {
6058       Type *Ty = GV->getValueType();
6059       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6060       // zero-sized type in other languages to declare the dynamic shared
6061       // memory which size is not known at the compile time. They will be
6062       // allocated by the runtime and placed directly after the static
6063       // allocated ones. They all share the same offset.
6064       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6065         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6066         // Adjust alignment for that dynamic shared memory array.
6067         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6068         return SDValue(
6069             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6070       }
6071     }
6072     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6073   }
6074 
6075   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6076     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6077                                             SIInstrInfo::MO_ABS32_LO);
6078     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6079   }
6080 
6081   if (shouldEmitFixup(GV))
6082     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6083   else if (shouldEmitPCReloc(GV))
6084     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6085                                    SIInstrInfo::MO_REL32);
6086 
6087   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6088                                             SIInstrInfo::MO_GOTPCREL32);
6089 
6090   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6091   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6092   const DataLayout &DataLayout = DAG.getDataLayout();
6093   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6094   MachinePointerInfo PtrInfo
6095     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6096 
6097   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6098                      MachineMemOperand::MODereferenceable |
6099                          MachineMemOperand::MOInvariant);
6100 }
6101 
6102 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6103                                    const SDLoc &DL, SDValue V) const {
6104   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6105   // the destination register.
6106   //
6107   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6108   // so we will end up with redundant moves to m0.
6109   //
6110   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6111 
6112   // A Null SDValue creates a glue result.
6113   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6114                                   V, Chain);
6115   return SDValue(M0, 0);
6116 }
6117 
6118 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6119                                                  SDValue Op,
6120                                                  MVT VT,
6121                                                  unsigned Offset) const {
6122   SDLoc SL(Op);
6123   SDValue Param = lowerKernargMemParameter(
6124       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6125   // The local size values will have the hi 16-bits as zero.
6126   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6127                      DAG.getValueType(VT));
6128 }
6129 
6130 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6131                                         EVT VT) {
6132   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6133                                       "non-hsa intrinsic with hsa target",
6134                                       DL.getDebugLoc());
6135   DAG.getContext()->diagnose(BadIntrin);
6136   return DAG.getUNDEF(VT);
6137 }
6138 
6139 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6140                                          EVT VT) {
6141   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6142                                       "intrinsic not supported on subtarget",
6143                                       DL.getDebugLoc());
6144   DAG.getContext()->diagnose(BadIntrin);
6145   return DAG.getUNDEF(VT);
6146 }
6147 
6148 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6149                                     ArrayRef<SDValue> Elts) {
6150   assert(!Elts.empty());
6151   MVT Type;
6152   unsigned NumElts = Elts.size();
6153 
6154   if (NumElts <= 8) {
6155     Type = MVT::getVectorVT(MVT::f32, NumElts);
6156   } else {
6157     assert(Elts.size() <= 16);
6158     Type = MVT::v16f32;
6159     NumElts = 16;
6160   }
6161 
6162   SmallVector<SDValue, 16> VecElts(NumElts);
6163   for (unsigned i = 0; i < Elts.size(); ++i) {
6164     SDValue Elt = Elts[i];
6165     if (Elt.getValueType() != MVT::f32)
6166       Elt = DAG.getBitcast(MVT::f32, Elt);
6167     VecElts[i] = Elt;
6168   }
6169   for (unsigned i = Elts.size(); i < NumElts; ++i)
6170     VecElts[i] = DAG.getUNDEF(MVT::f32);
6171 
6172   if (NumElts == 1)
6173     return VecElts[0];
6174   return DAG.getBuildVector(Type, DL, VecElts);
6175 }
6176 
6177 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6178                               SDValue Src, int ExtraElts) {
6179   EVT SrcVT = Src.getValueType();
6180 
6181   SmallVector<SDValue, 8> Elts;
6182 
6183   if (SrcVT.isVector())
6184     DAG.ExtractVectorElements(Src, Elts);
6185   else
6186     Elts.push_back(Src);
6187 
6188   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6189   while (ExtraElts--)
6190     Elts.push_back(Undef);
6191 
6192   return DAG.getBuildVector(CastVT, DL, Elts);
6193 }
6194 
6195 // Re-construct the required return value for a image load intrinsic.
6196 // This is more complicated due to the optional use TexFailCtrl which means the required
6197 // return type is an aggregate
6198 static SDValue constructRetValue(SelectionDAG &DAG,
6199                                  MachineSDNode *Result,
6200                                  ArrayRef<EVT> ResultTypes,
6201                                  bool IsTexFail, bool Unpacked, bool IsD16,
6202                                  int DMaskPop, int NumVDataDwords,
6203                                  const SDLoc &DL) {
6204   // Determine the required return type. This is the same regardless of IsTexFail flag
6205   EVT ReqRetVT = ResultTypes[0];
6206   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6207   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6208     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6209 
6210   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6211     DMaskPop : (DMaskPop + 1) / 2;
6212 
6213   MVT DataDwordVT = NumDataDwords == 1 ?
6214     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6215 
6216   MVT MaskPopVT = MaskPopDwords == 1 ?
6217     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6218 
6219   SDValue Data(Result, 0);
6220   SDValue TexFail;
6221 
6222   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6223     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6224     if (MaskPopVT.isVector()) {
6225       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6226                          SDValue(Result, 0), ZeroIdx);
6227     } else {
6228       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6229                          SDValue(Result, 0), ZeroIdx);
6230     }
6231   }
6232 
6233   if (DataDwordVT.isVector())
6234     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6235                           NumDataDwords - MaskPopDwords);
6236 
6237   if (IsD16)
6238     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6239 
6240   EVT LegalReqRetVT = ReqRetVT;
6241   if (!ReqRetVT.isVector()) {
6242     if (!Data.getValueType().isInteger())
6243       Data = DAG.getNode(ISD::BITCAST, DL,
6244                          Data.getValueType().changeTypeToInteger(), Data);
6245     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6246   } else {
6247     // We need to widen the return vector to a legal type
6248     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6249         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6250       LegalReqRetVT =
6251           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6252                            ReqRetVT.getVectorNumElements() + 1);
6253     }
6254   }
6255   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6256 
6257   if (IsTexFail) {
6258     TexFail =
6259         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6260                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6261 
6262     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6263   }
6264 
6265   if (Result->getNumValues() == 1)
6266     return Data;
6267 
6268   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6269 }
6270 
6271 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6272                          SDValue *LWE, bool &IsTexFail) {
6273   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6274 
6275   uint64_t Value = TexFailCtrlConst->getZExtValue();
6276   if (Value) {
6277     IsTexFail = true;
6278   }
6279 
6280   SDLoc DL(TexFailCtrlConst);
6281   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6282   Value &= ~(uint64_t)0x1;
6283   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6284   Value &= ~(uint64_t)0x2;
6285 
6286   return Value == 0;
6287 }
6288 
6289 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6290                                       MVT PackVectorVT,
6291                                       SmallVectorImpl<SDValue> &PackedAddrs,
6292                                       unsigned DimIdx, unsigned EndIdx,
6293                                       unsigned NumGradients) {
6294   SDLoc DL(Op);
6295   for (unsigned I = DimIdx; I < EndIdx; I++) {
6296     SDValue Addr = Op.getOperand(I);
6297 
6298     // Gradients are packed with undef for each coordinate.
6299     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6300     // 1D: undef,dx/dh; undef,dx/dv
6301     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6302     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6303     if (((I + 1) >= EndIdx) ||
6304         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6305                                          I == DimIdx + NumGradients - 1))) {
6306       if (Addr.getValueType() != MVT::i16)
6307         Addr = DAG.getBitcast(MVT::i16, Addr);
6308       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6309     } else {
6310       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6311       I++;
6312     }
6313     Addr = DAG.getBitcast(MVT::f32, Addr);
6314     PackedAddrs.push_back(Addr);
6315   }
6316 }
6317 
6318 SDValue SITargetLowering::lowerImage(SDValue Op,
6319                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6320                                      SelectionDAG &DAG, bool WithChain) const {
6321   SDLoc DL(Op);
6322   MachineFunction &MF = DAG.getMachineFunction();
6323   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6324   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6325       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6326   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6327   unsigned IntrOpcode = Intr->BaseOpcode;
6328   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6329   bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
6330 
6331   SmallVector<EVT, 3> ResultTypes(Op->values());
6332   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6333   bool IsD16 = false;
6334   bool IsG16 = false;
6335   bool IsA16 = false;
6336   SDValue VData;
6337   int NumVDataDwords;
6338   bool AdjustRetType = false;
6339 
6340   // Offset of intrinsic arguments
6341   const unsigned ArgOffset = WithChain ? 2 : 1;
6342 
6343   unsigned DMask;
6344   unsigned DMaskLanes = 0;
6345 
6346   if (BaseOpcode->Atomic) {
6347     VData = Op.getOperand(2);
6348 
6349     bool Is64Bit = VData.getValueType() == MVT::i64;
6350     if (BaseOpcode->AtomicX2) {
6351       SDValue VData2 = Op.getOperand(3);
6352       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6353                                  {VData, VData2});
6354       if (Is64Bit)
6355         VData = DAG.getBitcast(MVT::v4i32, VData);
6356 
6357       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6358       DMask = Is64Bit ? 0xf : 0x3;
6359       NumVDataDwords = Is64Bit ? 4 : 2;
6360     } else {
6361       DMask = Is64Bit ? 0x3 : 0x1;
6362       NumVDataDwords = Is64Bit ? 2 : 1;
6363     }
6364   } else {
6365     auto *DMaskConst =
6366         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6367     DMask = DMaskConst->getZExtValue();
6368     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6369 
6370     if (BaseOpcode->Store) {
6371       VData = Op.getOperand(2);
6372 
6373       MVT StoreVT = VData.getSimpleValueType();
6374       if (StoreVT.getScalarType() == MVT::f16) {
6375         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6376           return Op; // D16 is unsupported for this instruction
6377 
6378         IsD16 = true;
6379         VData = handleD16VData(VData, DAG, true);
6380       }
6381 
6382       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6383     } else {
6384       // Work out the num dwords based on the dmask popcount and underlying type
6385       // and whether packing is supported.
6386       MVT LoadVT = ResultTypes[0].getSimpleVT();
6387       if (LoadVT.getScalarType() == MVT::f16) {
6388         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6389           return Op; // D16 is unsupported for this instruction
6390 
6391         IsD16 = true;
6392       }
6393 
6394       // Confirm that the return type is large enough for the dmask specified
6395       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6396           (!LoadVT.isVector() && DMaskLanes > 1))
6397           return Op;
6398 
6399       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6400       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6401       // instructions.
6402       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6403           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6404         NumVDataDwords = (DMaskLanes + 1) / 2;
6405       else
6406         NumVDataDwords = DMaskLanes;
6407 
6408       AdjustRetType = true;
6409     }
6410   }
6411 
6412   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6413   SmallVector<SDValue, 4> VAddrs;
6414 
6415   // Check for 16 bit addresses or derivatives and pack if true.
6416   MVT VAddrVT =
6417       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6418   MVT VAddrScalarVT = VAddrVT.getScalarType();
6419   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6420   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6421 
6422   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6423   VAddrScalarVT = VAddrVT.getScalarType();
6424   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6425   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6426 
6427   // Push back extra arguments.
6428   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6429     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6430       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6431       // Special handling of bias when A16 is on. Bias is of type half but
6432       // occupies full 32-bit.
6433       SDValue Bias = DAG.getBuildVector(
6434           MVT::v2f16, DL,
6435           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6436       VAddrs.push_back(Bias);
6437     } else {
6438       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6439              "Bias needs to be converted to 16 bit in A16 mode");
6440       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6441     }
6442   }
6443 
6444   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6445     // 16 bit gradients are supported, but are tied to the A16 control
6446     // so both gradients and addresses must be 16 bit
6447     LLVM_DEBUG(
6448         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6449                   "require 16 bit args for both gradients and addresses");
6450     return Op;
6451   }
6452 
6453   if (IsA16) {
6454     if (!ST->hasA16()) {
6455       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6456                            "support 16 bit addresses\n");
6457       return Op;
6458     }
6459   }
6460 
6461   // We've dealt with incorrect input so we know that if IsA16, IsG16
6462   // are set then we have to compress/pack operands (either address,
6463   // gradient or both)
6464   // In the case where a16 and gradients are tied (no G16 support) then we
6465   // have already verified that both IsA16 and IsG16 are true
6466   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6467     // Activate g16
6468     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6469         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6470     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6471   }
6472 
6473   // Add gradients (packed or unpacked)
6474   if (IsG16) {
6475     // Pack the gradients
6476     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6477     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6478                               ArgOffset + Intr->GradientStart,
6479                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6480   } else {
6481     for (unsigned I = ArgOffset + Intr->GradientStart;
6482          I < ArgOffset + Intr->CoordStart; I++)
6483       VAddrs.push_back(Op.getOperand(I));
6484   }
6485 
6486   // Add addresses (packed or unpacked)
6487   if (IsA16) {
6488     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6489                               ArgOffset + Intr->CoordStart, VAddrEnd,
6490                               0 /* No gradients */);
6491   } else {
6492     // Add uncompressed address
6493     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6494       VAddrs.push_back(Op.getOperand(I));
6495   }
6496 
6497   // If the register allocator cannot place the address registers contiguously
6498   // without introducing moves, then using the non-sequential address encoding
6499   // is always preferable, since it saves VALU instructions and is usually a
6500   // wash in terms of code size or even better.
6501   //
6502   // However, we currently have no way of hinting to the register allocator that
6503   // MIMG addresses should be placed contiguously when it is possible to do so,
6504   // so force non-NSA for the common 2-address case as a heuristic.
6505   //
6506   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6507   // allocation when possible.
6508   //
6509   // TODO: we can actually allow partial NSA where the final register is a
6510   // contiguous set of the remaining addresses.
6511   // This could help where there are more addresses than supported.
6512   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6513                 VAddrs.size() >= 3 &&
6514                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6515   SDValue VAddr;
6516   if (!UseNSA)
6517     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6518 
6519   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6520   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6521   SDValue Unorm;
6522   if (!BaseOpcode->Sampler) {
6523     Unorm = True;
6524   } else {
6525     auto UnormConst =
6526         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6527 
6528     Unorm = UnormConst->getZExtValue() ? True : False;
6529   }
6530 
6531   SDValue TFE;
6532   SDValue LWE;
6533   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6534   bool IsTexFail = false;
6535   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6536     return Op;
6537 
6538   if (IsTexFail) {
6539     if (!DMaskLanes) {
6540       // Expecting to get an error flag since TFC is on - and dmask is 0
6541       // Force dmask to be at least 1 otherwise the instruction will fail
6542       DMask = 0x1;
6543       DMaskLanes = 1;
6544       NumVDataDwords = 1;
6545     }
6546     NumVDataDwords += 1;
6547     AdjustRetType = true;
6548   }
6549 
6550   // Has something earlier tagged that the return type needs adjusting
6551   // This happens if the instruction is a load or has set TexFailCtrl flags
6552   if (AdjustRetType) {
6553     // NumVDataDwords reflects the true number of dwords required in the return type
6554     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6555       // This is a no-op load. This can be eliminated
6556       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6557       if (isa<MemSDNode>(Op))
6558         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6559       return Undef;
6560     }
6561 
6562     EVT NewVT = NumVDataDwords > 1 ?
6563                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6564                 : MVT::i32;
6565 
6566     ResultTypes[0] = NewVT;
6567     if (ResultTypes.size() == 3) {
6568       // Original result was aggregate type used for TexFailCtrl results
6569       // The actual instruction returns as a vector type which has now been
6570       // created. Remove the aggregate result.
6571       ResultTypes.erase(&ResultTypes[1]);
6572     }
6573   }
6574 
6575   unsigned CPol = cast<ConstantSDNode>(
6576       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6577   if (BaseOpcode->Atomic)
6578     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6579   if (CPol & ~AMDGPU::CPol::ALL)
6580     return Op;
6581 
6582   SmallVector<SDValue, 26> Ops;
6583   if (BaseOpcode->Store || BaseOpcode->Atomic)
6584     Ops.push_back(VData); // vdata
6585   if (UseNSA)
6586     append_range(Ops, VAddrs);
6587   else
6588     Ops.push_back(VAddr);
6589   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6590   if (BaseOpcode->Sampler)
6591     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6592   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6593   if (IsGFX10Plus)
6594     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6595   Ops.push_back(Unorm);
6596   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6597   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6598                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6599   if (IsGFX10Plus)
6600     Ops.push_back(IsA16 ? True : False);
6601   if (!Subtarget->hasGFX90AInsts()) {
6602     Ops.push_back(TFE); //tfe
6603   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6604     report_fatal_error("TFE is not supported on this GPU");
6605   }
6606   Ops.push_back(LWE); // lwe
6607   if (!IsGFX10Plus)
6608     Ops.push_back(DimInfo->DA ? True : False);
6609   if (BaseOpcode->HasD16)
6610     Ops.push_back(IsD16 ? True : False);
6611   if (isa<MemSDNode>(Op))
6612     Ops.push_back(Op.getOperand(0)); // chain
6613 
6614   int NumVAddrDwords =
6615       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6616   int Opcode = -1;
6617 
6618   if (IsGFX11Plus) {
6619     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6620                                    UseNSA ? AMDGPU::MIMGEncGfx11NSA
6621                                           : AMDGPU::MIMGEncGfx11Default,
6622                                    NumVDataDwords, NumVAddrDwords);
6623   } else if (IsGFX10Plus) {
6624     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6625                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6626                                           : AMDGPU::MIMGEncGfx10Default,
6627                                    NumVDataDwords, NumVAddrDwords);
6628   } else {
6629     if (Subtarget->hasGFX90AInsts()) {
6630       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6631                                      NumVDataDwords, NumVAddrDwords);
6632       if (Opcode == -1)
6633         report_fatal_error(
6634             "requested image instruction is not supported on this GPU");
6635     }
6636     if (Opcode == -1 &&
6637         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6638       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6639                                      NumVDataDwords, NumVAddrDwords);
6640     if (Opcode == -1)
6641       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6642                                      NumVDataDwords, NumVAddrDwords);
6643   }
6644   assert(Opcode != -1);
6645 
6646   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6647   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6648     MachineMemOperand *MemRef = MemOp->getMemOperand();
6649     DAG.setNodeMemRefs(NewNode, {MemRef});
6650   }
6651 
6652   if (BaseOpcode->AtomicX2) {
6653     SmallVector<SDValue, 1> Elt;
6654     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6655     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6656   }
6657   if (BaseOpcode->Store)
6658     return SDValue(NewNode, 0);
6659   return constructRetValue(DAG, NewNode,
6660                            OrigResultTypes, IsTexFail,
6661                            Subtarget->hasUnpackedD16VMem(), IsD16,
6662                            DMaskLanes, NumVDataDwords, DL);
6663 }
6664 
6665 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6666                                        SDValue Offset, SDValue CachePolicy,
6667                                        SelectionDAG &DAG) const {
6668   MachineFunction &MF = DAG.getMachineFunction();
6669 
6670   const DataLayout &DataLayout = DAG.getDataLayout();
6671   Align Alignment =
6672       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6673 
6674   MachineMemOperand *MMO = MF.getMachineMemOperand(
6675       MachinePointerInfo(),
6676       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6677           MachineMemOperand::MOInvariant,
6678       VT.getStoreSize(), Alignment);
6679 
6680   if (!Offset->isDivergent()) {
6681     SDValue Ops[] = {
6682         Rsrc,
6683         Offset, // Offset
6684         CachePolicy
6685     };
6686 
6687     // Widen vec3 load to vec4.
6688     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6689       EVT WidenedVT =
6690           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6691       auto WidenedOp = DAG.getMemIntrinsicNode(
6692           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6693           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6694       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6695                                    DAG.getVectorIdxConstant(0, DL));
6696       return Subvector;
6697     }
6698 
6699     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6700                                    DAG.getVTList(VT), Ops, VT, MMO);
6701   }
6702 
6703   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6704   // assume that the buffer is unswizzled.
6705   SmallVector<SDValue, 4> Loads;
6706   unsigned NumLoads = 1;
6707   MVT LoadVT = VT.getSimpleVT();
6708   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6709   assert((LoadVT.getScalarType() == MVT::i32 ||
6710           LoadVT.getScalarType() == MVT::f32));
6711 
6712   if (NumElts == 8 || NumElts == 16) {
6713     NumLoads = NumElts / 4;
6714     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6715   }
6716 
6717   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6718   SDValue Ops[] = {
6719       DAG.getEntryNode(),                               // Chain
6720       Rsrc,                                             // rsrc
6721       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6722       {},                                               // voffset
6723       {},                                               // soffset
6724       {},                                               // offset
6725       CachePolicy,                                      // cachepolicy
6726       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6727   };
6728 
6729   // Use the alignment to ensure that the required offsets will fit into the
6730   // immediate offsets.
6731   setBufferOffsets(Offset, DAG, &Ops[3],
6732                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6733 
6734   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6735   for (unsigned i = 0; i < NumLoads; ++i) {
6736     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6737     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6738                                         LoadVT, MMO, DAG));
6739   }
6740 
6741   if (NumElts == 8 || NumElts == 16)
6742     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6743 
6744   return Loads[0];
6745 }
6746 
6747 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6748                                           unsigned Dim,
6749                                           const ArgDescriptor &Arg) const {
6750   SDLoc SL(Op);
6751   MachineFunction &MF = DAG.getMachineFunction();
6752   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6753   if (MaxID == 0)
6754     return DAG.getConstant(0, SL, MVT::i32);
6755 
6756   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6757                                SDLoc(DAG.getEntryNode()), Arg);
6758 
6759   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6760   // masking operations anyway.
6761   //
6762   // TODO: We could assert the top bit is 0 for the source copy.
6763   if (Arg.isMasked())
6764     return Val;
6765 
6766   // Preserve the known bits after expansion to a copy.
6767   EVT SmallVT =
6768       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6769   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6770                      DAG.getValueType(SmallVT));
6771 }
6772 
6773 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6774                                                   SelectionDAG &DAG) const {
6775   MachineFunction &MF = DAG.getMachineFunction();
6776   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6777 
6778   EVT VT = Op.getValueType();
6779   SDLoc DL(Op);
6780   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6781 
6782   // TODO: Should this propagate fast-math-flags?
6783 
6784   switch (IntrinsicID) {
6785   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6786     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6787       return emitNonHSAIntrinsicError(DAG, DL, VT);
6788     return getPreloadedValue(DAG, *MFI, VT,
6789                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6790   }
6791   case Intrinsic::amdgcn_dispatch_ptr:
6792   case Intrinsic::amdgcn_queue_ptr: {
6793     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6794       DiagnosticInfoUnsupported BadIntrin(
6795           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6796           DL.getDebugLoc());
6797       DAG.getContext()->diagnose(BadIntrin);
6798       return DAG.getUNDEF(VT);
6799     }
6800 
6801     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6802       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6803     return getPreloadedValue(DAG, *MFI, VT, RegID);
6804   }
6805   case Intrinsic::amdgcn_implicitarg_ptr: {
6806     if (MFI->isEntryFunction())
6807       return getImplicitArgPtr(DAG, DL);
6808     return getPreloadedValue(DAG, *MFI, VT,
6809                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6810   }
6811   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6812     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6813       // This only makes sense to call in a kernel, so just lower to null.
6814       return DAG.getConstant(0, DL, VT);
6815     }
6816 
6817     return getPreloadedValue(DAG, *MFI, VT,
6818                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6819   }
6820   case Intrinsic::amdgcn_dispatch_id: {
6821     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6822   }
6823   case Intrinsic::amdgcn_rcp:
6824     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6825   case Intrinsic::amdgcn_rsq:
6826     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6827   case Intrinsic::amdgcn_rsq_legacy:
6828     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6829       return emitRemovedIntrinsicError(DAG, DL, VT);
6830     return SDValue();
6831   case Intrinsic::amdgcn_rcp_legacy:
6832     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6833       return emitRemovedIntrinsicError(DAG, DL, VT);
6834     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6835   case Intrinsic::amdgcn_rsq_clamp: {
6836     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6837       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6838 
6839     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6840     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6841     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6842 
6843     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6844     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6845                               DAG.getConstantFP(Max, DL, VT));
6846     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6847                        DAG.getConstantFP(Min, DL, VT));
6848   }
6849   case Intrinsic::r600_read_ngroups_x:
6850     if (Subtarget->isAmdHsaOS())
6851       return emitNonHSAIntrinsicError(DAG, DL, VT);
6852 
6853     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6854                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6855                                     false);
6856   case Intrinsic::r600_read_ngroups_y:
6857     if (Subtarget->isAmdHsaOS())
6858       return emitNonHSAIntrinsicError(DAG, DL, VT);
6859 
6860     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6861                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6862                                     false);
6863   case Intrinsic::r600_read_ngroups_z:
6864     if (Subtarget->isAmdHsaOS())
6865       return emitNonHSAIntrinsicError(DAG, DL, VT);
6866 
6867     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6868                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6869                                     false);
6870   case Intrinsic::r600_read_global_size_x:
6871     if (Subtarget->isAmdHsaOS())
6872       return emitNonHSAIntrinsicError(DAG, DL, VT);
6873 
6874     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6875                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6876                                     Align(4), false);
6877   case Intrinsic::r600_read_global_size_y:
6878     if (Subtarget->isAmdHsaOS())
6879       return emitNonHSAIntrinsicError(DAG, DL, VT);
6880 
6881     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6882                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6883                                     Align(4), false);
6884   case Intrinsic::r600_read_global_size_z:
6885     if (Subtarget->isAmdHsaOS())
6886       return emitNonHSAIntrinsicError(DAG, DL, VT);
6887 
6888     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6889                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6890                                     Align(4), false);
6891   case Intrinsic::r600_read_local_size_x:
6892     if (Subtarget->isAmdHsaOS())
6893       return emitNonHSAIntrinsicError(DAG, DL, VT);
6894 
6895     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6896                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6897   case Intrinsic::r600_read_local_size_y:
6898     if (Subtarget->isAmdHsaOS())
6899       return emitNonHSAIntrinsicError(DAG, DL, VT);
6900 
6901     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6902                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6903   case Intrinsic::r600_read_local_size_z:
6904     if (Subtarget->isAmdHsaOS())
6905       return emitNonHSAIntrinsicError(DAG, DL, VT);
6906 
6907     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6908                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6909   case Intrinsic::amdgcn_workgroup_id_x:
6910     return getPreloadedValue(DAG, *MFI, VT,
6911                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6912   case Intrinsic::amdgcn_workgroup_id_y:
6913     return getPreloadedValue(DAG, *MFI, VT,
6914                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6915   case Intrinsic::amdgcn_workgroup_id_z:
6916     return getPreloadedValue(DAG, *MFI, VT,
6917                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6918   case Intrinsic::amdgcn_lds_kernel_id: {
6919     if (MFI->isEntryFunction())
6920       return getLDSKernelId(DAG, DL);
6921     return getPreloadedValue(DAG, *MFI, VT,
6922                              AMDGPUFunctionArgInfo::LDS_KERNEL_ID);
6923   }
6924   case Intrinsic::amdgcn_workitem_id_x:
6925     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6926   case Intrinsic::amdgcn_workitem_id_y:
6927     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6928   case Intrinsic::amdgcn_workitem_id_z:
6929     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6930   case Intrinsic::amdgcn_wavefrontsize:
6931     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6932                            SDLoc(Op), MVT::i32);
6933   case Intrinsic::amdgcn_s_buffer_load: {
6934     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6935     if (CPol & ~AMDGPU::CPol::ALL)
6936       return Op;
6937     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6938                         DAG);
6939   }
6940   case Intrinsic::amdgcn_fdiv_fast:
6941     return lowerFDIV_FAST(Op, DAG);
6942   case Intrinsic::amdgcn_sin:
6943     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6944 
6945   case Intrinsic::amdgcn_cos:
6946     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6947 
6948   case Intrinsic::amdgcn_mul_u24:
6949     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6950   case Intrinsic::amdgcn_mul_i24:
6951     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6952 
6953   case Intrinsic::amdgcn_log_clamp: {
6954     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6955       return SDValue();
6956 
6957     return emitRemovedIntrinsicError(DAG, DL, VT);
6958   }
6959   case Intrinsic::amdgcn_ldexp:
6960     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6961                        Op.getOperand(1), Op.getOperand(2));
6962 
6963   case Intrinsic::amdgcn_fract:
6964     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6965 
6966   case Intrinsic::amdgcn_class:
6967     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6968                        Op.getOperand(1), Op.getOperand(2));
6969   case Intrinsic::amdgcn_div_fmas:
6970     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6971                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6972                        Op.getOperand(4));
6973 
6974   case Intrinsic::amdgcn_div_fixup:
6975     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6976                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6977 
6978   case Intrinsic::amdgcn_div_scale: {
6979     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6980 
6981     // Translate to the operands expected by the machine instruction. The
6982     // first parameter must be the same as the first instruction.
6983     SDValue Numerator = Op.getOperand(1);
6984     SDValue Denominator = Op.getOperand(2);
6985 
6986     // Note this order is opposite of the machine instruction's operations,
6987     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6988     // intrinsic has the numerator as the first operand to match a normal
6989     // division operation.
6990 
6991     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6992 
6993     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6994                        Denominator, Numerator);
6995   }
6996   case Intrinsic::amdgcn_icmp: {
6997     // There is a Pat that handles this variant, so return it as-is.
6998     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6999         Op.getConstantOperandVal(2) == 0 &&
7000         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7001       return Op;
7002     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7003   }
7004   case Intrinsic::amdgcn_fcmp: {
7005     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7006   }
7007   case Intrinsic::amdgcn_ballot:
7008     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7009   case Intrinsic::amdgcn_fmed3:
7010     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7011                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7012   case Intrinsic::amdgcn_fdot2:
7013     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7014                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7015                        Op.getOperand(4));
7016   case Intrinsic::amdgcn_fmul_legacy:
7017     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7018                        Op.getOperand(1), Op.getOperand(2));
7019   case Intrinsic::amdgcn_sffbh:
7020     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7021   case Intrinsic::amdgcn_sbfe:
7022     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7023                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7024   case Intrinsic::amdgcn_ubfe:
7025     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7026                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7027   case Intrinsic::amdgcn_cvt_pkrtz:
7028   case Intrinsic::amdgcn_cvt_pknorm_i16:
7029   case Intrinsic::amdgcn_cvt_pknorm_u16:
7030   case Intrinsic::amdgcn_cvt_pk_i16:
7031   case Intrinsic::amdgcn_cvt_pk_u16: {
7032     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7033     EVT VT = Op.getValueType();
7034     unsigned Opcode;
7035 
7036     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7037       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7038     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7039       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7040     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7041       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7042     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7043       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7044     else
7045       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7046 
7047     if (isTypeLegal(VT))
7048       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7049 
7050     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7051                                Op.getOperand(1), Op.getOperand(2));
7052     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7053   }
7054   case Intrinsic::amdgcn_fmad_ftz:
7055     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7056                        Op.getOperand(2), Op.getOperand(3));
7057 
7058   case Intrinsic::amdgcn_if_break:
7059     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7060                                       Op->getOperand(1), Op->getOperand(2)), 0);
7061 
7062   case Intrinsic::amdgcn_groupstaticsize: {
7063     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7064     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7065       return Op;
7066 
7067     const Module *M = MF.getFunction().getParent();
7068     const GlobalValue *GV =
7069         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7070     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7071                                             SIInstrInfo::MO_ABS32_LO);
7072     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7073   }
7074   case Intrinsic::amdgcn_is_shared:
7075   case Intrinsic::amdgcn_is_private: {
7076     SDLoc SL(Op);
7077     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7078       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7079     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7080     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7081                                  Op.getOperand(1));
7082 
7083     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7084                                 DAG.getConstant(1, SL, MVT::i32));
7085     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7086   }
7087   case Intrinsic::amdgcn_perm:
7088     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7089                        Op.getOperand(2), Op.getOperand(3));
7090   case Intrinsic::amdgcn_reloc_constant: {
7091     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7092     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7093     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7094     auto RelocSymbol = cast<GlobalVariable>(
7095         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7096     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7097                                             SIInstrInfo::MO_ABS32_LO);
7098     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7099   }
7100   default:
7101     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7102             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7103       return lowerImage(Op, ImageDimIntr, DAG, false);
7104 
7105     return Op;
7106   }
7107 }
7108 
7109 /// Update \p MMO based on the offset inputs to an intrinsic.
7110 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7111                             SDValue SOffset, SDValue Offset,
7112                             SDValue VIndex = SDValue()) {
7113   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7114       !isa<ConstantSDNode>(Offset)) {
7115     // The combined offset is not known to be constant, so we cannot represent
7116     // it in the MMO. Give up.
7117     MMO->setValue((Value *)nullptr);
7118     return;
7119   }
7120 
7121   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7122                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7123     // The strided index component of the address is not known to be zero, so we
7124     // cannot represent it in the MMO. Give up.
7125     MMO->setValue((Value *)nullptr);
7126     return;
7127   }
7128 
7129   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7130                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7131                  cast<ConstantSDNode>(Offset)->getSExtValue());
7132 }
7133 
7134 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7135                                                      SelectionDAG &DAG,
7136                                                      unsigned NewOpcode) const {
7137   SDLoc DL(Op);
7138 
7139   SDValue VData = Op.getOperand(2);
7140   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7141   SDValue Ops[] = {
7142     Op.getOperand(0), // Chain
7143     VData,            // vdata
7144     Op.getOperand(3), // rsrc
7145     DAG.getConstant(0, DL, MVT::i32), // vindex
7146     Offsets.first,    // voffset
7147     Op.getOperand(5), // soffset
7148     Offsets.second,   // offset
7149     Op.getOperand(6), // cachepolicy
7150     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7151   };
7152 
7153   auto *M = cast<MemSDNode>(Op);
7154   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7155 
7156   EVT MemVT = VData.getValueType();
7157   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7158                                  M->getMemOperand());
7159 }
7160 
7161 // Return a value to use for the idxen operand by examining the vindex operand.
7162 static unsigned getIdxEn(SDValue VIndex) {
7163   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7164     // No need to set idxen if vindex is known to be zero.
7165     return VIndexC->getZExtValue() != 0;
7166   return 1;
7167 }
7168 
7169 SDValue
7170 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7171                                                 unsigned NewOpcode) const {
7172   SDLoc DL(Op);
7173 
7174   SDValue VData = Op.getOperand(2);
7175   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7176   SDValue Ops[] = {
7177     Op.getOperand(0), // Chain
7178     VData,            // vdata
7179     Op.getOperand(3), // rsrc
7180     Op.getOperand(4), // vindex
7181     Offsets.first,    // voffset
7182     Op.getOperand(6), // soffset
7183     Offsets.second,   // offset
7184     Op.getOperand(7), // cachepolicy
7185     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7186   };
7187 
7188   auto *M = cast<MemSDNode>(Op);
7189   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7190 
7191   EVT MemVT = VData.getValueType();
7192   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7193                                  M->getMemOperand());
7194 }
7195 
7196 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7197                                                  SelectionDAG &DAG) const {
7198   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7199   SDLoc DL(Op);
7200 
7201   switch (IntrID) {
7202   case Intrinsic::amdgcn_ds_ordered_add:
7203   case Intrinsic::amdgcn_ds_ordered_swap: {
7204     MemSDNode *M = cast<MemSDNode>(Op);
7205     SDValue Chain = M->getOperand(0);
7206     SDValue M0 = M->getOperand(2);
7207     SDValue Value = M->getOperand(3);
7208     unsigned IndexOperand = M->getConstantOperandVal(7);
7209     unsigned WaveRelease = M->getConstantOperandVal(8);
7210     unsigned WaveDone = M->getConstantOperandVal(9);
7211 
7212     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7213     IndexOperand &= ~0x3f;
7214     unsigned CountDw = 0;
7215 
7216     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7217       CountDw = (IndexOperand >> 24) & 0xf;
7218       IndexOperand &= ~(0xf << 24);
7219 
7220       if (CountDw < 1 || CountDw > 4) {
7221         report_fatal_error(
7222             "ds_ordered_count: dword count must be between 1 and 4");
7223       }
7224     }
7225 
7226     if (IndexOperand)
7227       report_fatal_error("ds_ordered_count: bad index operand");
7228 
7229     if (WaveDone && !WaveRelease)
7230       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7231 
7232     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7233     unsigned ShaderType =
7234         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7235     unsigned Offset0 = OrderedCountIndex << 2;
7236     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
7237 
7238     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7239       Offset1 |= (CountDw - 1) << 6;
7240 
7241     if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
7242       Offset1 |= ShaderType << 2;
7243 
7244     unsigned Offset = Offset0 | (Offset1 << 8);
7245 
7246     SDValue Ops[] = {
7247       Chain,
7248       Value,
7249       DAG.getTargetConstant(Offset, DL, MVT::i16),
7250       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7251     };
7252     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7253                                    M->getVTList(), Ops, M->getMemoryVT(),
7254                                    M->getMemOperand());
7255   }
7256   case Intrinsic::amdgcn_ds_fadd: {
7257     MemSDNode *M = cast<MemSDNode>(Op);
7258     unsigned Opc;
7259     switch (IntrID) {
7260     case Intrinsic::amdgcn_ds_fadd:
7261       Opc = ISD::ATOMIC_LOAD_FADD;
7262       break;
7263     }
7264 
7265     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7266                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7267                          M->getMemOperand());
7268   }
7269   case Intrinsic::amdgcn_atomic_inc:
7270   case Intrinsic::amdgcn_atomic_dec:
7271   case Intrinsic::amdgcn_ds_fmin:
7272   case Intrinsic::amdgcn_ds_fmax: {
7273     MemSDNode *M = cast<MemSDNode>(Op);
7274     unsigned Opc;
7275     switch (IntrID) {
7276     case Intrinsic::amdgcn_atomic_inc:
7277       Opc = AMDGPUISD::ATOMIC_INC;
7278       break;
7279     case Intrinsic::amdgcn_atomic_dec:
7280       Opc = AMDGPUISD::ATOMIC_DEC;
7281       break;
7282     case Intrinsic::amdgcn_ds_fmin:
7283       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7284       break;
7285     case Intrinsic::amdgcn_ds_fmax:
7286       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7287       break;
7288     default:
7289       llvm_unreachable("Unknown intrinsic!");
7290     }
7291     SDValue Ops[] = {
7292       M->getOperand(0), // Chain
7293       M->getOperand(2), // Ptr
7294       M->getOperand(3)  // Value
7295     };
7296 
7297     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7298                                    M->getMemoryVT(), M->getMemOperand());
7299   }
7300   case Intrinsic::amdgcn_buffer_load:
7301   case Intrinsic::amdgcn_buffer_load_format: {
7302     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7303     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7304     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7305     SDValue Ops[] = {
7306       Op.getOperand(0), // Chain
7307       Op.getOperand(2), // rsrc
7308       Op.getOperand(3), // vindex
7309       SDValue(),        // voffset -- will be set by setBufferOffsets
7310       SDValue(),        // soffset -- will be set by setBufferOffsets
7311       SDValue(),        // offset -- will be set by setBufferOffsets
7312       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7313       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7314     };
7315     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7316 
7317     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7318         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7319 
7320     EVT VT = Op.getValueType();
7321     EVT IntVT = VT.changeTypeToInteger();
7322     auto *M = cast<MemSDNode>(Op);
7323     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7324     EVT LoadVT = Op.getValueType();
7325 
7326     if (LoadVT.getScalarType() == MVT::f16)
7327       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7328                                  M, DAG, Ops);
7329 
7330     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7331     if (LoadVT.getScalarType() == MVT::i8 ||
7332         LoadVT.getScalarType() == MVT::i16)
7333       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7334 
7335     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7336                                M->getMemOperand(), DAG);
7337   }
7338   case Intrinsic::amdgcn_raw_buffer_load:
7339   case Intrinsic::amdgcn_raw_buffer_load_format: {
7340     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7341 
7342     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7343     SDValue Ops[] = {
7344       Op.getOperand(0), // Chain
7345       Op.getOperand(2), // rsrc
7346       DAG.getConstant(0, DL, MVT::i32), // vindex
7347       Offsets.first,    // voffset
7348       Op.getOperand(4), // soffset
7349       Offsets.second,   // offset
7350       Op.getOperand(5), // cachepolicy, swizzled buffer
7351       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7352     };
7353 
7354     auto *M = cast<MemSDNode>(Op);
7355     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7356     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7357   }
7358   case Intrinsic::amdgcn_struct_buffer_load:
7359   case Intrinsic::amdgcn_struct_buffer_load_format: {
7360     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7361 
7362     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7363     SDValue Ops[] = {
7364       Op.getOperand(0), // Chain
7365       Op.getOperand(2), // rsrc
7366       Op.getOperand(3), // vindex
7367       Offsets.first,    // voffset
7368       Op.getOperand(5), // soffset
7369       Offsets.second,   // offset
7370       Op.getOperand(6), // cachepolicy, swizzled buffer
7371       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7372     };
7373 
7374     auto *M = cast<MemSDNode>(Op);
7375     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7376     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7377   }
7378   case Intrinsic::amdgcn_tbuffer_load: {
7379     MemSDNode *M = cast<MemSDNode>(Op);
7380     EVT LoadVT = Op.getValueType();
7381 
7382     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7383     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7384     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7385     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7386     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7387     SDValue Ops[] = {
7388       Op.getOperand(0),  // Chain
7389       Op.getOperand(2),  // rsrc
7390       Op.getOperand(3),  // vindex
7391       Op.getOperand(4),  // voffset
7392       Op.getOperand(5),  // soffset
7393       Op.getOperand(6),  // offset
7394       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7395       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7396       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7397     };
7398 
7399     if (LoadVT.getScalarType() == MVT::f16)
7400       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7401                                  M, DAG, Ops);
7402     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7403                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7404                                DAG);
7405   }
7406   case Intrinsic::amdgcn_raw_tbuffer_load: {
7407     MemSDNode *M = cast<MemSDNode>(Op);
7408     EVT LoadVT = Op.getValueType();
7409     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7410 
7411     SDValue Ops[] = {
7412       Op.getOperand(0),  // Chain
7413       Op.getOperand(2),  // rsrc
7414       DAG.getConstant(0, DL, MVT::i32), // vindex
7415       Offsets.first,     // voffset
7416       Op.getOperand(4),  // soffset
7417       Offsets.second,    // offset
7418       Op.getOperand(5),  // format
7419       Op.getOperand(6),  // cachepolicy, swizzled buffer
7420       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7421     };
7422 
7423     if (LoadVT.getScalarType() == MVT::f16)
7424       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7425                                  M, DAG, Ops);
7426     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7427                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7428                                DAG);
7429   }
7430   case Intrinsic::amdgcn_struct_tbuffer_load: {
7431     MemSDNode *M = cast<MemSDNode>(Op);
7432     EVT LoadVT = Op.getValueType();
7433     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7434 
7435     SDValue Ops[] = {
7436       Op.getOperand(0),  // Chain
7437       Op.getOperand(2),  // rsrc
7438       Op.getOperand(3),  // vindex
7439       Offsets.first,     // voffset
7440       Op.getOperand(5),  // soffset
7441       Offsets.second,    // offset
7442       Op.getOperand(6),  // format
7443       Op.getOperand(7),  // cachepolicy, swizzled buffer
7444       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7445     };
7446 
7447     if (LoadVT.getScalarType() == MVT::f16)
7448       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7449                                  M, DAG, Ops);
7450     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7451                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7452                                DAG);
7453   }
7454   case Intrinsic::amdgcn_buffer_atomic_swap:
7455   case Intrinsic::amdgcn_buffer_atomic_add:
7456   case Intrinsic::amdgcn_buffer_atomic_sub:
7457   case Intrinsic::amdgcn_buffer_atomic_csub:
7458   case Intrinsic::amdgcn_buffer_atomic_smin:
7459   case Intrinsic::amdgcn_buffer_atomic_umin:
7460   case Intrinsic::amdgcn_buffer_atomic_smax:
7461   case Intrinsic::amdgcn_buffer_atomic_umax:
7462   case Intrinsic::amdgcn_buffer_atomic_and:
7463   case Intrinsic::amdgcn_buffer_atomic_or:
7464   case Intrinsic::amdgcn_buffer_atomic_xor:
7465   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7466     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7467     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7468     SDValue Ops[] = {
7469       Op.getOperand(0), // Chain
7470       Op.getOperand(2), // vdata
7471       Op.getOperand(3), // rsrc
7472       Op.getOperand(4), // vindex
7473       SDValue(),        // voffset -- will be set by setBufferOffsets
7474       SDValue(),        // soffset -- will be set by setBufferOffsets
7475       SDValue(),        // offset -- will be set by setBufferOffsets
7476       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7477       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7478     };
7479     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7480 
7481     EVT VT = Op.getValueType();
7482 
7483     auto *M = cast<MemSDNode>(Op);
7484     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7485     unsigned Opcode = 0;
7486 
7487     switch (IntrID) {
7488     case Intrinsic::amdgcn_buffer_atomic_swap:
7489       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7490       break;
7491     case Intrinsic::amdgcn_buffer_atomic_add:
7492       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7493       break;
7494     case Intrinsic::amdgcn_buffer_atomic_sub:
7495       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7496       break;
7497     case Intrinsic::amdgcn_buffer_atomic_csub:
7498       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7499       break;
7500     case Intrinsic::amdgcn_buffer_atomic_smin:
7501       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7502       break;
7503     case Intrinsic::amdgcn_buffer_atomic_umin:
7504       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7505       break;
7506     case Intrinsic::amdgcn_buffer_atomic_smax:
7507       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7508       break;
7509     case Intrinsic::amdgcn_buffer_atomic_umax:
7510       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7511       break;
7512     case Intrinsic::amdgcn_buffer_atomic_and:
7513       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7514       break;
7515     case Intrinsic::amdgcn_buffer_atomic_or:
7516       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7517       break;
7518     case Intrinsic::amdgcn_buffer_atomic_xor:
7519       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7520       break;
7521     case Intrinsic::amdgcn_buffer_atomic_fadd:
7522       if (!Op.getValue(0).use_empty() && !hasAtomicFaddRtnForTy(Op)) {
7523         DiagnosticInfoUnsupported
7524           NoFpRet(DAG.getMachineFunction().getFunction(),
7525                   "return versions of fp atomics not supported",
7526                   DL.getDebugLoc(), DS_Error);
7527         DAG.getContext()->diagnose(NoFpRet);
7528         return SDValue();
7529       }
7530       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7531       break;
7532     default:
7533       llvm_unreachable("unhandled atomic opcode");
7534     }
7535 
7536     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7537                                    M->getMemOperand());
7538   }
7539   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7540     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7541   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7542     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7543   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7544     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7545   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7546     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7547   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7548     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7549   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7550     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7551   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7552     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7553   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7554     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7555   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7556     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7557   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7558     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7559   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7560     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7561   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7562     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7563   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7564     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7565   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7566     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7567   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7568     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7569   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7570     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7571   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7572     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7573   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7574     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7575   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7576     return lowerStructBufferAtomicIntrin(Op, DAG,
7577                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7578   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7579     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7580   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7581     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7582   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7583     return lowerStructBufferAtomicIntrin(Op, DAG,
7584                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7585   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7586     return lowerStructBufferAtomicIntrin(Op, DAG,
7587                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7588   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7589     return lowerStructBufferAtomicIntrin(Op, DAG,
7590                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7591   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7592     return lowerStructBufferAtomicIntrin(Op, DAG,
7593                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7594   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7595     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7596   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7597     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7598   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7599     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7600   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7601     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7602   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7603     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7604 
7605   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7606     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7607     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7608     SDValue Ops[] = {
7609       Op.getOperand(0), // Chain
7610       Op.getOperand(2), // src
7611       Op.getOperand(3), // cmp
7612       Op.getOperand(4), // rsrc
7613       Op.getOperand(5), // vindex
7614       SDValue(),        // voffset -- will be set by setBufferOffsets
7615       SDValue(),        // soffset -- will be set by setBufferOffsets
7616       SDValue(),        // offset -- will be set by setBufferOffsets
7617       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7618       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7619     };
7620     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7621 
7622     EVT VT = Op.getValueType();
7623     auto *M = cast<MemSDNode>(Op);
7624     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7625 
7626     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7627                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7628   }
7629   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7630     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7631     SDValue Ops[] = {
7632       Op.getOperand(0), // Chain
7633       Op.getOperand(2), // src
7634       Op.getOperand(3), // cmp
7635       Op.getOperand(4), // rsrc
7636       DAG.getConstant(0, DL, MVT::i32), // vindex
7637       Offsets.first,    // voffset
7638       Op.getOperand(6), // soffset
7639       Offsets.second,   // offset
7640       Op.getOperand(7), // cachepolicy
7641       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7642     };
7643     EVT VT = Op.getValueType();
7644     auto *M = cast<MemSDNode>(Op);
7645     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7646 
7647     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7648                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7649   }
7650   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7651     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7652     SDValue Ops[] = {
7653       Op.getOperand(0), // Chain
7654       Op.getOperand(2), // src
7655       Op.getOperand(3), // cmp
7656       Op.getOperand(4), // rsrc
7657       Op.getOperand(5), // vindex
7658       Offsets.first,    // voffset
7659       Op.getOperand(7), // soffset
7660       Offsets.second,   // offset
7661       Op.getOperand(8), // cachepolicy
7662       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7663     };
7664     EVT VT = Op.getValueType();
7665     auto *M = cast<MemSDNode>(Op);
7666     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7667 
7668     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7669                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7670   }
7671   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7672     MemSDNode *M = cast<MemSDNode>(Op);
7673     SDValue NodePtr = M->getOperand(2);
7674     SDValue RayExtent = M->getOperand(3);
7675     SDValue RayOrigin = M->getOperand(4);
7676     SDValue RayDir = M->getOperand(5);
7677     SDValue RayInvDir = M->getOperand(6);
7678     SDValue TDescr = M->getOperand(7);
7679 
7680     assert(NodePtr.getValueType() == MVT::i32 ||
7681            NodePtr.getValueType() == MVT::i64);
7682     assert(RayDir.getValueType() == MVT::v3f16 ||
7683            RayDir.getValueType() == MVT::v3f32);
7684 
7685     if (!Subtarget->hasGFX10_AEncoding()) {
7686       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7687       return SDValue();
7688     }
7689 
7690     const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
7691     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7692     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7693     const unsigned NumVDataDwords = 4;
7694     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7695     const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
7696     const bool UseNSA =
7697         Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize();
7698     const unsigned BaseOpcodes[2][2] = {
7699         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7700         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7701          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7702     int Opcode;
7703     if (UseNSA) {
7704       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7705                                      IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA
7706                                                  : AMDGPU::MIMGEncGfx10NSA,
7707                                      NumVDataDwords, NumVAddrDwords);
7708     } else {
7709       Opcode =
7710           AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7711                                 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default
7712                                             : AMDGPU::MIMGEncGfx10Default,
7713                                 NumVDataDwords, PowerOf2Ceil(NumVAddrDwords));
7714     }
7715     assert(Opcode != -1);
7716 
7717     SmallVector<SDValue, 16> Ops;
7718 
7719     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7720       SmallVector<SDValue, 3> Lanes;
7721       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7722       if (Lanes[0].getValueSizeInBits() == 32) {
7723         for (unsigned I = 0; I < 3; ++I)
7724           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7725       } else {
7726         if (IsAligned) {
7727           Ops.push_back(
7728             DAG.getBitcast(MVT::i32,
7729                            DAG.getBuildVector(MVT::v2f16, DL,
7730                                               { Lanes[0], Lanes[1] })));
7731           Ops.push_back(Lanes[2]);
7732         } else {
7733           SDValue Elt0 = Ops.pop_back_val();
7734           Ops.push_back(
7735             DAG.getBitcast(MVT::i32,
7736                            DAG.getBuildVector(MVT::v2f16, DL,
7737                                               { Elt0, Lanes[0] })));
7738           Ops.push_back(
7739             DAG.getBitcast(MVT::i32,
7740                            DAG.getBuildVector(MVT::v2f16, DL,
7741                                               { Lanes[1], Lanes[2] })));
7742         }
7743       }
7744     };
7745 
7746     if (UseNSA && IsGFX11Plus) {
7747       Ops.push_back(NodePtr);
7748       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7749       Ops.push_back(RayOrigin);
7750       if (IsA16) {
7751         SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
7752         DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
7753         DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
7754         for (unsigned I = 0; I < 3; ++I) {
7755           MergedLanes.push_back(DAG.getBitcast(
7756               MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
7757                                            {DirLanes[I], InvDirLanes[I]})));
7758         }
7759         Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
7760       } else {
7761         Ops.push_back(RayDir);
7762         Ops.push_back(RayInvDir);
7763       }
7764     } else {
7765       if (Is64)
7766         DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
7767                                   2);
7768       else
7769         Ops.push_back(NodePtr);
7770 
7771       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7772       packLanes(RayOrigin, true);
7773       packLanes(RayDir, true);
7774       packLanes(RayInvDir, false);
7775     }
7776 
7777     if (!UseNSA) {
7778       // Build a single vector containing all the operands so far prepared.
7779       if (NumVAddrDwords > 8) {
7780         SDValue Undef = DAG.getUNDEF(MVT::i32);
7781         Ops.append(16 - Ops.size(), Undef);
7782       }
7783       assert(Ops.size() == 8 || Ops.size() == 16);
7784       SDValue MergedOps = DAG.getBuildVector(
7785           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7786       Ops.clear();
7787       Ops.push_back(MergedOps);
7788     }
7789 
7790     Ops.push_back(TDescr);
7791     if (IsA16)
7792       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7793     Ops.push_back(M->getChain());
7794 
7795     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7796     MachineMemOperand *MemRef = M->getMemOperand();
7797     DAG.setNodeMemRefs(NewNode, {MemRef});
7798     return SDValue(NewNode, 0);
7799   }
7800   case Intrinsic::amdgcn_global_atomic_fadd:
7801     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7802       DiagnosticInfoUnsupported
7803         NoFpRet(DAG.getMachineFunction().getFunction(),
7804                 "return versions of fp atomics not supported",
7805                 DL.getDebugLoc(), DS_Error);
7806       DAG.getContext()->diagnose(NoFpRet);
7807       return SDValue();
7808     }
7809     LLVM_FALLTHROUGH;
7810   case Intrinsic::amdgcn_global_atomic_fmin:
7811   case Intrinsic::amdgcn_global_atomic_fmax:
7812   case Intrinsic::amdgcn_flat_atomic_fadd:
7813   case Intrinsic::amdgcn_flat_atomic_fmin:
7814   case Intrinsic::amdgcn_flat_atomic_fmax: {
7815     MemSDNode *M = cast<MemSDNode>(Op);
7816     SDValue Ops[] = {
7817       M->getOperand(0), // Chain
7818       M->getOperand(2), // Ptr
7819       M->getOperand(3)  // Value
7820     };
7821     unsigned Opcode = 0;
7822     switch (IntrID) {
7823     case Intrinsic::amdgcn_global_atomic_fadd:
7824     case Intrinsic::amdgcn_flat_atomic_fadd: {
7825       EVT VT = Op.getOperand(3).getValueType();
7826       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7827                            DAG.getVTList(VT, MVT::Other), Ops,
7828                            M->getMemOperand());
7829     }
7830     case Intrinsic::amdgcn_global_atomic_fmin:
7831     case Intrinsic::amdgcn_flat_atomic_fmin: {
7832       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7833       break;
7834     }
7835     case Intrinsic::amdgcn_global_atomic_fmax:
7836     case Intrinsic::amdgcn_flat_atomic_fmax: {
7837       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7838       break;
7839     }
7840     default:
7841       llvm_unreachable("unhandled atomic opcode");
7842     }
7843     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7844                                    M->getVTList(), Ops, M->getMemoryVT(),
7845                                    M->getMemOperand());
7846   }
7847   default:
7848 
7849     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7850             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7851       return lowerImage(Op, ImageDimIntr, DAG, true);
7852 
7853     return SDValue();
7854   }
7855 }
7856 
7857 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7858 // dwordx4 if on SI.
7859 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7860                                               SDVTList VTList,
7861                                               ArrayRef<SDValue> Ops, EVT MemVT,
7862                                               MachineMemOperand *MMO,
7863                                               SelectionDAG &DAG) const {
7864   EVT VT = VTList.VTs[0];
7865   EVT WidenedVT = VT;
7866   EVT WidenedMemVT = MemVT;
7867   if (!Subtarget->hasDwordx3LoadStores() &&
7868       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7869     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7870                                  WidenedVT.getVectorElementType(), 4);
7871     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7872                                     WidenedMemVT.getVectorElementType(), 4);
7873     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7874   }
7875 
7876   assert(VTList.NumVTs == 2);
7877   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7878 
7879   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7880                                        WidenedMemVT, MMO);
7881   if (WidenedVT != VT) {
7882     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7883                                DAG.getVectorIdxConstant(0, DL));
7884     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7885   }
7886   return NewOp;
7887 }
7888 
7889 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7890                                          bool ImageStore) const {
7891   EVT StoreVT = VData.getValueType();
7892 
7893   // No change for f16 and legal vector D16 types.
7894   if (!StoreVT.isVector())
7895     return VData;
7896 
7897   SDLoc DL(VData);
7898   unsigned NumElements = StoreVT.getVectorNumElements();
7899 
7900   if (Subtarget->hasUnpackedD16VMem()) {
7901     // We need to unpack the packed data to store.
7902     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7903     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7904 
7905     EVT EquivStoreVT =
7906         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7907     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7908     return DAG.UnrollVectorOp(ZExt.getNode());
7909   }
7910 
7911   // The sq block of gfx8.1 does not estimate register use correctly for d16
7912   // image store instructions. The data operand is computed as if it were not a
7913   // d16 image instruction.
7914   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7915     // Bitcast to i16
7916     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7917     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7918 
7919     // Decompose into scalars
7920     SmallVector<SDValue, 4> Elts;
7921     DAG.ExtractVectorElements(IntVData, Elts);
7922 
7923     // Group pairs of i16 into v2i16 and bitcast to i32
7924     SmallVector<SDValue, 4> PackedElts;
7925     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7926       SDValue Pair =
7927           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7928       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7929       PackedElts.push_back(IntPair);
7930     }
7931     if ((NumElements % 2) == 1) {
7932       // Handle v3i16
7933       unsigned I = Elts.size() / 2;
7934       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7935                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7936       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7937       PackedElts.push_back(IntPair);
7938     }
7939 
7940     // Pad using UNDEF
7941     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7942 
7943     // Build final vector
7944     EVT VecVT =
7945         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7946     return DAG.getBuildVector(VecVT, DL, PackedElts);
7947   }
7948 
7949   if (NumElements == 3) {
7950     EVT IntStoreVT =
7951         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7952     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7953 
7954     EVT WidenedStoreVT = EVT::getVectorVT(
7955         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7956     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7957                                          WidenedStoreVT.getStoreSizeInBits());
7958     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7959     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7960   }
7961 
7962   assert(isTypeLegal(StoreVT));
7963   return VData;
7964 }
7965 
7966 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7967                                               SelectionDAG &DAG) const {
7968   SDLoc DL(Op);
7969   SDValue Chain = Op.getOperand(0);
7970   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7971   MachineFunction &MF = DAG.getMachineFunction();
7972 
7973   switch (IntrinsicID) {
7974   case Intrinsic::amdgcn_exp_compr: {
7975     if (!Subtarget->hasCompressedExport()) {
7976       DiagnosticInfoUnsupported BadIntrin(
7977           DAG.getMachineFunction().getFunction(),
7978           "intrinsic not supported on subtarget", DL.getDebugLoc());
7979       DAG.getContext()->diagnose(BadIntrin);
7980     }
7981     SDValue Src0 = Op.getOperand(4);
7982     SDValue Src1 = Op.getOperand(5);
7983     // Hack around illegal type on SI by directly selecting it.
7984     if (isTypeLegal(Src0.getValueType()))
7985       return SDValue();
7986 
7987     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7988     SDValue Undef = DAG.getUNDEF(MVT::f32);
7989     const SDValue Ops[] = {
7990       Op.getOperand(2), // tgt
7991       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7992       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7993       Undef, // src2
7994       Undef, // src3
7995       Op.getOperand(7), // vm
7996       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7997       Op.getOperand(3), // en
7998       Op.getOperand(0) // Chain
7999     };
8000 
8001     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
8002     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
8003   }
8004   case Intrinsic::amdgcn_s_barrier: {
8005     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
8006       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
8007       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
8008       if (WGSize <= ST.getWavefrontSize())
8009         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
8010                                           Op.getOperand(0)), 0);
8011     }
8012     return SDValue();
8013   };
8014   case Intrinsic::amdgcn_tbuffer_store: {
8015     SDValue VData = Op.getOperand(2);
8016     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8017     if (IsD16)
8018       VData = handleD16VData(VData, DAG);
8019     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
8020     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
8021     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
8022     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
8023     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8024     SDValue Ops[] = {
8025       Chain,
8026       VData,             // vdata
8027       Op.getOperand(3),  // rsrc
8028       Op.getOperand(4),  // vindex
8029       Op.getOperand(5),  // voffset
8030       Op.getOperand(6),  // soffset
8031       Op.getOperand(7),  // offset
8032       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8033       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8034       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8035     };
8036     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8037                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8038     MemSDNode *M = cast<MemSDNode>(Op);
8039     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8040                                    M->getMemoryVT(), M->getMemOperand());
8041   }
8042 
8043   case Intrinsic::amdgcn_struct_tbuffer_store: {
8044     SDValue VData = Op.getOperand(2);
8045     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8046     if (IsD16)
8047       VData = handleD16VData(VData, DAG);
8048     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8049     SDValue Ops[] = {
8050       Chain,
8051       VData,             // vdata
8052       Op.getOperand(3),  // rsrc
8053       Op.getOperand(4),  // vindex
8054       Offsets.first,     // voffset
8055       Op.getOperand(6),  // soffset
8056       Offsets.second,    // offset
8057       Op.getOperand(7),  // format
8058       Op.getOperand(8),  // cachepolicy, swizzled buffer
8059       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8060     };
8061     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8062                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8063     MemSDNode *M = cast<MemSDNode>(Op);
8064     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8065                                    M->getMemoryVT(), M->getMemOperand());
8066   }
8067 
8068   case Intrinsic::amdgcn_raw_tbuffer_store: {
8069     SDValue VData = Op.getOperand(2);
8070     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8071     if (IsD16)
8072       VData = handleD16VData(VData, DAG);
8073     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8074     SDValue Ops[] = {
8075       Chain,
8076       VData,             // vdata
8077       Op.getOperand(3),  // rsrc
8078       DAG.getConstant(0, DL, MVT::i32), // vindex
8079       Offsets.first,     // voffset
8080       Op.getOperand(5),  // soffset
8081       Offsets.second,    // offset
8082       Op.getOperand(6),  // format
8083       Op.getOperand(7),  // cachepolicy, swizzled buffer
8084       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8085     };
8086     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8087                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8088     MemSDNode *M = cast<MemSDNode>(Op);
8089     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8090                                    M->getMemoryVT(), M->getMemOperand());
8091   }
8092 
8093   case Intrinsic::amdgcn_buffer_store:
8094   case Intrinsic::amdgcn_buffer_store_format: {
8095     SDValue VData = Op.getOperand(2);
8096     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8097     if (IsD16)
8098       VData = handleD16VData(VData, DAG);
8099     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8100     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8101     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8102     SDValue Ops[] = {
8103       Chain,
8104       VData,
8105       Op.getOperand(3), // rsrc
8106       Op.getOperand(4), // vindex
8107       SDValue(), // voffset -- will be set by setBufferOffsets
8108       SDValue(), // soffset -- will be set by setBufferOffsets
8109       SDValue(), // offset -- will be set by setBufferOffsets
8110       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8111       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8112     };
8113     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8114 
8115     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8116                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8117     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8118     MemSDNode *M = cast<MemSDNode>(Op);
8119     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8120 
8121     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8122     EVT VDataType = VData.getValueType().getScalarType();
8123     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8124       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8125 
8126     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8127                                    M->getMemoryVT(), M->getMemOperand());
8128   }
8129 
8130   case Intrinsic::amdgcn_raw_buffer_store:
8131   case Intrinsic::amdgcn_raw_buffer_store_format: {
8132     const bool IsFormat =
8133         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8134 
8135     SDValue VData = Op.getOperand(2);
8136     EVT VDataVT = VData.getValueType();
8137     EVT EltType = VDataVT.getScalarType();
8138     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8139     if (IsD16) {
8140       VData = handleD16VData(VData, DAG);
8141       VDataVT = VData.getValueType();
8142     }
8143 
8144     if (!isTypeLegal(VDataVT)) {
8145       VData =
8146           DAG.getNode(ISD::BITCAST, DL,
8147                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8148     }
8149 
8150     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8151     SDValue Ops[] = {
8152       Chain,
8153       VData,
8154       Op.getOperand(3), // rsrc
8155       DAG.getConstant(0, DL, MVT::i32), // vindex
8156       Offsets.first,    // voffset
8157       Op.getOperand(5), // soffset
8158       Offsets.second,   // offset
8159       Op.getOperand(6), // cachepolicy, swizzled buffer
8160       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8161     };
8162     unsigned Opc =
8163         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8164     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8165     MemSDNode *M = cast<MemSDNode>(Op);
8166     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8167 
8168     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8169     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8170       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8171 
8172     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8173                                    M->getMemoryVT(), M->getMemOperand());
8174   }
8175 
8176   case Intrinsic::amdgcn_struct_buffer_store:
8177   case Intrinsic::amdgcn_struct_buffer_store_format: {
8178     const bool IsFormat =
8179         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8180 
8181     SDValue VData = Op.getOperand(2);
8182     EVT VDataVT = VData.getValueType();
8183     EVT EltType = VDataVT.getScalarType();
8184     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8185 
8186     if (IsD16) {
8187       VData = handleD16VData(VData, DAG);
8188       VDataVT = VData.getValueType();
8189     }
8190 
8191     if (!isTypeLegal(VDataVT)) {
8192       VData =
8193           DAG.getNode(ISD::BITCAST, DL,
8194                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8195     }
8196 
8197     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8198     SDValue Ops[] = {
8199       Chain,
8200       VData,
8201       Op.getOperand(3), // rsrc
8202       Op.getOperand(4), // vindex
8203       Offsets.first,    // voffset
8204       Op.getOperand(6), // soffset
8205       Offsets.second,   // offset
8206       Op.getOperand(7), // cachepolicy, swizzled buffer
8207       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8208     };
8209     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8210                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8211     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8212     MemSDNode *M = cast<MemSDNode>(Op);
8213     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8214 
8215     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8216     EVT VDataType = VData.getValueType().getScalarType();
8217     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8218       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8219 
8220     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8221                                    M->getMemoryVT(), M->getMemOperand());
8222   }
8223   case Intrinsic::amdgcn_raw_buffer_load_lds:
8224   case Intrinsic::amdgcn_struct_buffer_load_lds: {
8225     unsigned Opc;
8226     bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8227     unsigned OpOffset = HasVIndex ? 1 : 0;
8228     SDValue VOffset = Op.getOperand(5 + OpOffset);
8229     auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8230     bool HasVOffset = !CVOffset || !CVOffset->isZero();
8231     unsigned Size = Op->getConstantOperandVal(4);
8232 
8233     switch (Size) {
8234     default:
8235       return SDValue();
8236     case 1:
8237       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8238                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8239                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8240                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8241       break;
8242     case 2:
8243       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8244                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8245                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8246                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8247       break;
8248     case 4:
8249       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8250                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8251                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8252                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8253       break;
8254     }
8255 
8256     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8257 
8258     SmallVector<SDValue, 8> Ops;
8259 
8260     if (HasVIndex && HasVOffset)
8261       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8262                                        { Op.getOperand(5), // VIndex
8263                                          VOffset }));
8264     else if (HasVIndex)
8265       Ops.push_back(Op.getOperand(5));
8266     else if (HasVOffset)
8267       Ops.push_back(VOffset);
8268 
8269     Ops.push_back(Op.getOperand(2));           // rsrc
8270     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8271     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8272     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8273     Ops.push_back(
8274       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8275     Ops.push_back(
8276       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
8277     Ops.push_back(M0Val.getValue(0)); // Chain
8278     Ops.push_back(M0Val.getValue(1)); // Glue
8279 
8280     auto *M = cast<MemSDNode>(Op);
8281     MachineMemOperand *LoadMMO = M->getMemOperand();
8282     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8283     LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8284     MachinePointerInfo StorePtrI = LoadPtrI;
8285     StorePtrI.V = nullptr;
8286     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8287 
8288     auto F = LoadMMO->getFlags() &
8289              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8290     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8291                                       Size, LoadMMO->getBaseAlign());
8292 
8293     MachineMemOperand *StoreMMO =
8294         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8295                                 sizeof(int32_t), LoadMMO->getBaseAlign());
8296 
8297     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8298     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8299 
8300     return SDValue(Load, 0);
8301   }
8302   case Intrinsic::amdgcn_global_load_lds: {
8303     unsigned Opc;
8304     unsigned Size = Op->getConstantOperandVal(4);
8305     switch (Size) {
8306     default:
8307       return SDValue();
8308     case 1:
8309       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8310       break;
8311     case 2:
8312       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8313       break;
8314     case 4:
8315       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8316       break;
8317     }
8318 
8319     auto *M = cast<MemSDNode>(Op);
8320     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8321 
8322     SmallVector<SDValue, 6> Ops;
8323 
8324     SDValue Addr = Op.getOperand(2); // Global ptr
8325     SDValue VOffset;
8326     // Try to split SAddr and VOffset. Global and LDS pointers share the same
8327     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8328     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8329       SDValue LHS = Addr.getOperand(0);
8330       SDValue RHS = Addr.getOperand(1);
8331 
8332       if (LHS->isDivergent())
8333         std::swap(LHS, RHS);
8334 
8335       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8336           RHS.getOperand(0).getValueType() == MVT::i32) {
8337         // add (i64 sgpr), (zero_extend (i32 vgpr))
8338         Addr = LHS;
8339         VOffset = RHS.getOperand(0);
8340       }
8341     }
8342 
8343     Ops.push_back(Addr);
8344     if (!Addr->isDivergent()) {
8345       Opc = AMDGPU::getGlobalSaddrOp(Opc);
8346       if (!VOffset)
8347         VOffset = SDValue(
8348             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8349                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8350       Ops.push_back(VOffset);
8351     }
8352 
8353     Ops.push_back(Op.getOperand(5));  // Offset
8354     Ops.push_back(Op.getOperand(6));  // CPol
8355     Ops.push_back(M0Val.getValue(0)); // Chain
8356     Ops.push_back(M0Val.getValue(1)); // Glue
8357 
8358     MachineMemOperand *LoadMMO = M->getMemOperand();
8359     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8360     LoadPtrI.Offset = Op->getConstantOperandVal(5);
8361     MachinePointerInfo StorePtrI = LoadPtrI;
8362     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8363     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8364     auto F = LoadMMO->getFlags() &
8365              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8366     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8367                                       Size, LoadMMO->getBaseAlign());
8368     MachineMemOperand *StoreMMO =
8369         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8370                                 sizeof(int32_t), Align(4));
8371 
8372     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8373     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8374 
8375     return SDValue(Load, 0);
8376   }
8377   case Intrinsic::amdgcn_end_cf:
8378     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8379                                       Op->getOperand(2), Chain), 0);
8380 
8381   default: {
8382     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8383             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8384       return lowerImage(Op, ImageDimIntr, DAG, true);
8385 
8386     return Op;
8387   }
8388   }
8389 }
8390 
8391 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8392 // offset (the offset that is included in bounds checking and swizzling, to be
8393 // split between the instruction's voffset and immoffset fields) and soffset
8394 // (the offset that is excluded from bounds checking and swizzling, to go in
8395 // the instruction's soffset field).  This function takes the first kind of
8396 // offset and figures out how to split it between voffset and immoffset.
8397 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8398     SDValue Offset, SelectionDAG &DAG) const {
8399   SDLoc DL(Offset);
8400   const unsigned MaxImm = 4095;
8401   SDValue N0 = Offset;
8402   ConstantSDNode *C1 = nullptr;
8403 
8404   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8405     N0 = SDValue();
8406   else if (DAG.isBaseWithConstantOffset(N0)) {
8407     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8408     N0 = N0.getOperand(0);
8409   }
8410 
8411   if (C1) {
8412     unsigned ImmOffset = C1->getZExtValue();
8413     // If the immediate value is too big for the immoffset field, put the value
8414     // and -4096 into the immoffset field so that the value that is copied/added
8415     // for the voffset field is a multiple of 4096, and it stands more chance
8416     // of being CSEd with the copy/add for another similar load/store.
8417     // However, do not do that rounding down to a multiple of 4096 if that is a
8418     // negative number, as it appears to be illegal to have a negative offset
8419     // in the vgpr, even if adding the immediate offset makes it positive.
8420     unsigned Overflow = ImmOffset & ~MaxImm;
8421     ImmOffset -= Overflow;
8422     if ((int32_t)Overflow < 0) {
8423       Overflow += ImmOffset;
8424       ImmOffset = 0;
8425     }
8426     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8427     if (Overflow) {
8428       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8429       if (!N0)
8430         N0 = OverflowVal;
8431       else {
8432         SDValue Ops[] = { N0, OverflowVal };
8433         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8434       }
8435     }
8436   }
8437   if (!N0)
8438     N0 = DAG.getConstant(0, DL, MVT::i32);
8439   if (!C1)
8440     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8441   return {N0, SDValue(C1, 0)};
8442 }
8443 
8444 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8445 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8446 // pointed to by Offsets.
8447 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8448                                         SelectionDAG &DAG, SDValue *Offsets,
8449                                         Align Alignment) const {
8450   SDLoc DL(CombinedOffset);
8451   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8452     uint32_t Imm = C->getZExtValue();
8453     uint32_t SOffset, ImmOffset;
8454     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8455                                  Alignment)) {
8456       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8457       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8458       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8459       return;
8460     }
8461   }
8462   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8463     SDValue N0 = CombinedOffset.getOperand(0);
8464     SDValue N1 = CombinedOffset.getOperand(1);
8465     uint32_t SOffset, ImmOffset;
8466     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8467     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8468                                                 Subtarget, Alignment)) {
8469       Offsets[0] = N0;
8470       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8471       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8472       return;
8473     }
8474   }
8475   Offsets[0] = CombinedOffset;
8476   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8477   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8478 }
8479 
8480 // Handle 8 bit and 16 bit buffer loads
8481 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8482                                                      EVT LoadVT, SDLoc DL,
8483                                                      ArrayRef<SDValue> Ops,
8484                                                      MemSDNode *M) const {
8485   EVT IntVT = LoadVT.changeTypeToInteger();
8486   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8487          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8488 
8489   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8490   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8491                                                Ops, IntVT,
8492                                                M->getMemOperand());
8493   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8494   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8495 
8496   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8497 }
8498 
8499 // Handle 8 bit and 16 bit buffer stores
8500 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8501                                                       EVT VDataType, SDLoc DL,
8502                                                       SDValue Ops[],
8503                                                       MemSDNode *M) const {
8504   if (VDataType == MVT::f16)
8505     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8506 
8507   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8508   Ops[1] = BufferStoreExt;
8509   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8510                                  AMDGPUISD::BUFFER_STORE_SHORT;
8511   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8512   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8513                                      M->getMemOperand());
8514 }
8515 
8516 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8517                                  ISD::LoadExtType ExtType, SDValue Op,
8518                                  const SDLoc &SL, EVT VT) {
8519   if (VT.bitsLT(Op.getValueType()))
8520     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8521 
8522   switch (ExtType) {
8523   case ISD::SEXTLOAD:
8524     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8525   case ISD::ZEXTLOAD:
8526     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8527   case ISD::EXTLOAD:
8528     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8529   case ISD::NON_EXTLOAD:
8530     return Op;
8531   }
8532 
8533   llvm_unreachable("invalid ext type");
8534 }
8535 
8536 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8537   SelectionDAG &DAG = DCI.DAG;
8538   if (Ld->getAlign() < Align(4) || Ld->isDivergent())
8539     return SDValue();
8540 
8541   // FIXME: Constant loads should all be marked invariant.
8542   unsigned AS = Ld->getAddressSpace();
8543   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8544       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8545       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8546     return SDValue();
8547 
8548   // Don't do this early, since it may interfere with adjacent load merging for
8549   // illegal types. We can avoid losing alignment information for exotic types
8550   // pre-legalize.
8551   EVT MemVT = Ld->getMemoryVT();
8552   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8553       MemVT.getSizeInBits() >= 32)
8554     return SDValue();
8555 
8556   SDLoc SL(Ld);
8557 
8558   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8559          "unexpected vector extload");
8560 
8561   // TODO: Drop only high part of range.
8562   SDValue Ptr = Ld->getBasePtr();
8563   SDValue NewLoad = DAG.getLoad(
8564       ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
8565       Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
8566       Ld->getMemOperand()->getFlags(), Ld->getAAInfo(),
8567       nullptr); // Drop ranges
8568 
8569   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8570   if (MemVT.isFloatingPoint()) {
8571     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8572            "unexpected fp extload");
8573     TruncVT = MemVT.changeTypeToInteger();
8574   }
8575 
8576   SDValue Cvt = NewLoad;
8577   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8578     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8579                       DAG.getValueType(TruncVT));
8580   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8581              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8582     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8583   } else {
8584     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8585   }
8586 
8587   EVT VT = Ld->getValueType(0);
8588   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8589 
8590   DCI.AddToWorklist(Cvt.getNode());
8591 
8592   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8593   // the appropriate extension from the 32-bit load.
8594   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8595   DCI.AddToWorklist(Cvt.getNode());
8596 
8597   // Handle conversion back to floating point if necessary.
8598   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8599 
8600   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8601 }
8602 
8603 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8604   SDLoc DL(Op);
8605   LoadSDNode *Load = cast<LoadSDNode>(Op);
8606   ISD::LoadExtType ExtType = Load->getExtensionType();
8607   EVT MemVT = Load->getMemoryVT();
8608 
8609   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8610     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8611       return SDValue();
8612 
8613     // FIXME: Copied from PPC
8614     // First, load into 32 bits, then truncate to 1 bit.
8615 
8616     SDValue Chain = Load->getChain();
8617     SDValue BasePtr = Load->getBasePtr();
8618     MachineMemOperand *MMO = Load->getMemOperand();
8619 
8620     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8621 
8622     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8623                                    BasePtr, RealMemVT, MMO);
8624 
8625     if (!MemVT.isVector()) {
8626       SDValue Ops[] = {
8627         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8628         NewLD.getValue(1)
8629       };
8630 
8631       return DAG.getMergeValues(Ops, DL);
8632     }
8633 
8634     SmallVector<SDValue, 3> Elts;
8635     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8636       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8637                                 DAG.getConstant(I, DL, MVT::i32));
8638 
8639       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8640     }
8641 
8642     SDValue Ops[] = {
8643       DAG.getBuildVector(MemVT, DL, Elts),
8644       NewLD.getValue(1)
8645     };
8646 
8647     return DAG.getMergeValues(Ops, DL);
8648   }
8649 
8650   if (!MemVT.isVector())
8651     return SDValue();
8652 
8653   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8654          "Custom lowering for non-i32 vectors hasn't been implemented.");
8655 
8656   Align Alignment = Load->getAlign();
8657   unsigned AS = Load->getAddressSpace();
8658   if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS &&
8659       Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8660     return SplitVectorLoad(Op, DAG);
8661   }
8662 
8663   MachineFunction &MF = DAG.getMachineFunction();
8664   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8665   // If there is a possibility that flat instruction access scratch memory
8666   // then we need to use the same legalization rules we use for private.
8667   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8668       !Subtarget->hasMultiDwordFlatScratchAddressing())
8669     AS = MFI->hasFlatScratchInit() ?
8670          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8671 
8672   unsigned NumElements = MemVT.getVectorNumElements();
8673 
8674   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8675       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8676     if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) {
8677       if (MemVT.isPow2VectorType())
8678         return SDValue();
8679       return WidenOrSplitVectorLoad(Op, DAG);
8680     }
8681     // Non-uniform loads will be selected to MUBUF instructions, so they
8682     // have the same legalization requirements as global and private
8683     // loads.
8684     //
8685   }
8686 
8687   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8688       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8689       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8690     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8691         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8692         Alignment >= Align(4) && NumElements < 32) {
8693       if (MemVT.isPow2VectorType())
8694         return SDValue();
8695       return WidenOrSplitVectorLoad(Op, DAG);
8696     }
8697     // Non-uniform loads will be selected to MUBUF instructions, so they
8698     // have the same legalization requirements as global and private
8699     // loads.
8700     //
8701   }
8702   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8703       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8704       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8705       AS == AMDGPUAS::FLAT_ADDRESS) {
8706     if (NumElements > 4)
8707       return SplitVectorLoad(Op, DAG);
8708     // v3 loads not supported on SI.
8709     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8710       return WidenOrSplitVectorLoad(Op, DAG);
8711 
8712     // v3 and v4 loads are supported for private and global memory.
8713     return SDValue();
8714   }
8715   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8716     // Depending on the setting of the private_element_size field in the
8717     // resource descriptor, we can only make private accesses up to a certain
8718     // size.
8719     switch (Subtarget->getMaxPrivateElementSize()) {
8720     case 4: {
8721       SDValue Ops[2];
8722       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8723       return DAG.getMergeValues(Ops, DL);
8724     }
8725     case 8:
8726       if (NumElements > 2)
8727         return SplitVectorLoad(Op, DAG);
8728       return SDValue();
8729     case 16:
8730       // Same as global/flat
8731       if (NumElements > 4)
8732         return SplitVectorLoad(Op, DAG);
8733       // v3 loads not supported on SI.
8734       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8735         return WidenOrSplitVectorLoad(Op, DAG);
8736 
8737       return SDValue();
8738     default:
8739       llvm_unreachable("unsupported private_element_size");
8740     }
8741   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8742     bool Fast = false;
8743     auto Flags = Load->getMemOperand()->getFlags();
8744     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8745                                            Load->getAlign(), Flags, &Fast) &&
8746         Fast)
8747       return SDValue();
8748 
8749     if (MemVT.isVector())
8750       return SplitVectorLoad(Op, DAG);
8751   }
8752 
8753   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8754                                       MemVT, *Load->getMemOperand())) {
8755     SDValue Ops[2];
8756     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8757     return DAG.getMergeValues(Ops, DL);
8758   }
8759 
8760   return SDValue();
8761 }
8762 
8763 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8764   EVT VT = Op.getValueType();
8765   if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
8766     return splitTernaryVectorOp(Op, DAG);
8767 
8768   assert(VT.getSizeInBits() == 64);
8769 
8770   SDLoc DL(Op);
8771   SDValue Cond = Op.getOperand(0);
8772 
8773   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8774   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8775 
8776   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8777   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8778 
8779   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8780   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8781 
8782   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8783 
8784   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8785   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8786 
8787   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8788 
8789   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8790   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8791 }
8792 
8793 // Catch division cases where we can use shortcuts with rcp and rsq
8794 // instructions.
8795 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8796                                               SelectionDAG &DAG) const {
8797   SDLoc SL(Op);
8798   SDValue LHS = Op.getOperand(0);
8799   SDValue RHS = Op.getOperand(1);
8800   EVT VT = Op.getValueType();
8801   const SDNodeFlags Flags = Op->getFlags();
8802 
8803   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8804 
8805   // Without !fpmath accuracy information, we can't do more because we don't
8806   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8807   if (!AllowInaccurateRcp)
8808     return SDValue();
8809 
8810   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8811     if (CLHS->isExactlyValue(1.0)) {
8812       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8813       // the CI documentation has a worst case error of 1 ulp.
8814       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8815       // use it as long as we aren't trying to use denormals.
8816       //
8817       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8818 
8819       // 1.0 / sqrt(x) -> rsq(x)
8820 
8821       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8822       // error seems really high at 2^29 ULP.
8823       if (RHS.getOpcode() == ISD::FSQRT)
8824         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8825 
8826       // 1.0 / x -> rcp(x)
8827       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8828     }
8829 
8830     // Same as for 1.0, but expand the sign out of the constant.
8831     if (CLHS->isExactlyValue(-1.0)) {
8832       // -1.0 / x -> rcp (fneg x)
8833       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8834       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8835     }
8836   }
8837 
8838   // Turn into multiply by the reciprocal.
8839   // x / y -> x * (1.0 / y)
8840   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8841   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8842 }
8843 
8844 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8845                                                 SelectionDAG &DAG) const {
8846   SDLoc SL(Op);
8847   SDValue X = Op.getOperand(0);
8848   SDValue Y = Op.getOperand(1);
8849   EVT VT = Op.getValueType();
8850   const SDNodeFlags Flags = Op->getFlags();
8851 
8852   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8853                             DAG.getTarget().Options.UnsafeFPMath;
8854   if (!AllowInaccurateDiv)
8855     return SDValue();
8856 
8857   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8858   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8859 
8860   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8861   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8862 
8863   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8864   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8865   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8866   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8867   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8868   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8869 }
8870 
8871 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8872                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8873                           SDNodeFlags Flags) {
8874   if (GlueChain->getNumValues() <= 1) {
8875     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8876   }
8877 
8878   assert(GlueChain->getNumValues() == 3);
8879 
8880   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8881   switch (Opcode) {
8882   default: llvm_unreachable("no chain equivalent for opcode");
8883   case ISD::FMUL:
8884     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8885     break;
8886   }
8887 
8888   return DAG.getNode(Opcode, SL, VTList,
8889                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8890                      Flags);
8891 }
8892 
8893 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8894                            EVT VT, SDValue A, SDValue B, SDValue C,
8895                            SDValue GlueChain, SDNodeFlags Flags) {
8896   if (GlueChain->getNumValues() <= 1) {
8897     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8898   }
8899 
8900   assert(GlueChain->getNumValues() == 3);
8901 
8902   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8903   switch (Opcode) {
8904   default: llvm_unreachable("no chain equivalent for opcode");
8905   case ISD::FMA:
8906     Opcode = AMDGPUISD::FMA_W_CHAIN;
8907     break;
8908   }
8909 
8910   return DAG.getNode(Opcode, SL, VTList,
8911                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8912                      Flags);
8913 }
8914 
8915 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8916   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8917     return FastLowered;
8918 
8919   SDLoc SL(Op);
8920   SDValue Src0 = Op.getOperand(0);
8921   SDValue Src1 = Op.getOperand(1);
8922 
8923   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8924   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8925 
8926   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8927   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8928 
8929   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8930   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8931 
8932   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8933 }
8934 
8935 // Faster 2.5 ULP division that does not support denormals.
8936 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8937   SDLoc SL(Op);
8938   SDValue LHS = Op.getOperand(1);
8939   SDValue RHS = Op.getOperand(2);
8940 
8941   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8942 
8943   const APFloat K0Val(BitsToFloat(0x6f800000));
8944   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8945 
8946   const APFloat K1Val(BitsToFloat(0x2f800000));
8947   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8948 
8949   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8950 
8951   EVT SetCCVT =
8952     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8953 
8954   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8955 
8956   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8957 
8958   // TODO: Should this propagate fast-math-flags?
8959   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8960 
8961   // rcp does not support denormals.
8962   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8963 
8964   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8965 
8966   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8967 }
8968 
8969 // Returns immediate value for setting the F32 denorm mode when using the
8970 // S_DENORM_MODE instruction.
8971 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8972                                     const SDLoc &SL, const GCNSubtarget *ST) {
8973   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8974   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8975                                 ? FP_DENORM_FLUSH_NONE
8976                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8977 
8978   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8979   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8980 }
8981 
8982 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8983   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8984     return FastLowered;
8985 
8986   // The selection matcher assumes anything with a chain selecting to a
8987   // mayRaiseFPException machine instruction. Since we're introducing a chain
8988   // here, we need to explicitly report nofpexcept for the regular fdiv
8989   // lowering.
8990   SDNodeFlags Flags = Op->getFlags();
8991   Flags.setNoFPExcept(true);
8992 
8993   SDLoc SL(Op);
8994   SDValue LHS = Op.getOperand(0);
8995   SDValue RHS = Op.getOperand(1);
8996 
8997   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8998 
8999   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
9000 
9001   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9002                                           {RHS, RHS, LHS}, Flags);
9003   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9004                                         {LHS, RHS, LHS}, Flags);
9005 
9006   // Denominator is scaled to not be denormal, so using rcp is ok.
9007   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
9008                                   DenominatorScaled, Flags);
9009   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
9010                                      DenominatorScaled, Flags);
9011 
9012   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
9013                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
9014                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
9015   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
9016 
9017   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
9018 
9019   if (!HasFP32Denormals) {
9020     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
9021     // lowering. The chain dependence is insufficient, and we need glue. We do
9022     // not need the glue variants in a strictfp function.
9023 
9024     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
9025 
9026     SDNode *EnableDenorm;
9027     if (Subtarget->hasDenormModeInst()) {
9028       const SDValue EnableDenormValue =
9029           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
9030 
9031       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
9032                                  DAG.getEntryNode(), EnableDenormValue).getNode();
9033     } else {
9034       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
9035                                                         SL, MVT::i32);
9036       EnableDenorm =
9037           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
9038                              {EnableDenormValue, BitField, DAG.getEntryNode()});
9039     }
9040 
9041     SDValue Ops[3] = {
9042       NegDivScale0,
9043       SDValue(EnableDenorm, 0),
9044       SDValue(EnableDenorm, 1)
9045     };
9046 
9047     NegDivScale0 = DAG.getMergeValues(Ops, SL);
9048   }
9049 
9050   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
9051                              ApproxRcp, One, NegDivScale0, Flags);
9052 
9053   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
9054                              ApproxRcp, Fma0, Flags);
9055 
9056   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
9057                            Fma1, Fma1, Flags);
9058 
9059   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
9060                              NumeratorScaled, Mul, Flags);
9061 
9062   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
9063                              Fma2, Fma1, Mul, Fma2, Flags);
9064 
9065   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
9066                              NumeratorScaled, Fma3, Flags);
9067 
9068   if (!HasFP32Denormals) {
9069     SDNode *DisableDenorm;
9070     if (Subtarget->hasDenormModeInst()) {
9071       const SDValue DisableDenormValue =
9072           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
9073 
9074       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
9075                                   Fma4.getValue(1), DisableDenormValue,
9076                                   Fma4.getValue(2)).getNode();
9077     } else {
9078       const SDValue DisableDenormValue =
9079           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
9080 
9081       DisableDenorm = DAG.getMachineNode(
9082           AMDGPU::S_SETREG_B32, SL, MVT::Other,
9083           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
9084     }
9085 
9086     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
9087                                       SDValue(DisableDenorm, 0), DAG.getRoot());
9088     DAG.setRoot(OutputChain);
9089   }
9090 
9091   SDValue Scale = NumeratorScaled.getValue(1);
9092   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
9093                              {Fma4, Fma1, Fma3, Scale}, Flags);
9094 
9095   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
9096 }
9097 
9098 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
9099   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
9100     return FastLowered;
9101 
9102   SDLoc SL(Op);
9103   SDValue X = Op.getOperand(0);
9104   SDValue Y = Op.getOperand(1);
9105 
9106   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
9107 
9108   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
9109 
9110   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
9111 
9112   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
9113 
9114   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
9115 
9116   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
9117 
9118   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
9119 
9120   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
9121 
9122   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
9123 
9124   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
9125   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
9126 
9127   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
9128                              NegDivScale0, Mul, DivScale1);
9129 
9130   SDValue Scale;
9131 
9132   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
9133     // Workaround a hardware bug on SI where the condition output from div_scale
9134     // is not usable.
9135 
9136     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
9137 
9138     // Figure out if the scale to use for div_fmas.
9139     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
9140     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
9141     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
9142     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
9143 
9144     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
9145     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
9146 
9147     SDValue Scale0Hi
9148       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
9149     SDValue Scale1Hi
9150       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
9151 
9152     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
9153     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
9154     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9155   } else {
9156     Scale = DivScale1.getValue(1);
9157   }
9158 
9159   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9160                              Fma4, Fma3, Mul, Scale);
9161 
9162   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9163 }
9164 
9165 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9166   EVT VT = Op.getValueType();
9167 
9168   if (VT == MVT::f32)
9169     return LowerFDIV32(Op, DAG);
9170 
9171   if (VT == MVT::f64)
9172     return LowerFDIV64(Op, DAG);
9173 
9174   if (VT == MVT::f16)
9175     return LowerFDIV16(Op, DAG);
9176 
9177   llvm_unreachable("Unexpected type for fdiv");
9178 }
9179 
9180 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9181   SDLoc DL(Op);
9182   StoreSDNode *Store = cast<StoreSDNode>(Op);
9183   EVT VT = Store->getMemoryVT();
9184 
9185   if (VT == MVT::i1) {
9186     return DAG.getTruncStore(Store->getChain(), DL,
9187        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9188        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9189   }
9190 
9191   assert(VT.isVector() &&
9192          Store->getValue().getValueType().getScalarType() == MVT::i32);
9193 
9194   unsigned AS = Store->getAddressSpace();
9195   if (Subtarget->hasLDSMisalignedBug() &&
9196       AS == AMDGPUAS::FLAT_ADDRESS &&
9197       Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9198     return SplitVectorStore(Op, DAG);
9199   }
9200 
9201   MachineFunction &MF = DAG.getMachineFunction();
9202   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9203   // If there is a possibility that flat instruction access scratch memory
9204   // then we need to use the same legalization rules we use for private.
9205   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9206       !Subtarget->hasMultiDwordFlatScratchAddressing())
9207     AS = MFI->hasFlatScratchInit() ?
9208          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9209 
9210   unsigned NumElements = VT.getVectorNumElements();
9211   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9212       AS == AMDGPUAS::FLAT_ADDRESS) {
9213     if (NumElements > 4)
9214       return SplitVectorStore(Op, DAG);
9215     // v3 stores not supported on SI.
9216     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9217       return SplitVectorStore(Op, DAG);
9218 
9219     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9220                                         VT, *Store->getMemOperand()))
9221       return expandUnalignedStore(Store, DAG);
9222 
9223     return SDValue();
9224   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9225     switch (Subtarget->getMaxPrivateElementSize()) {
9226     case 4:
9227       return scalarizeVectorStore(Store, DAG);
9228     case 8:
9229       if (NumElements > 2)
9230         return SplitVectorStore(Op, DAG);
9231       return SDValue();
9232     case 16:
9233       if (NumElements > 4 ||
9234           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9235         return SplitVectorStore(Op, DAG);
9236       return SDValue();
9237     default:
9238       llvm_unreachable("unsupported private_element_size");
9239     }
9240   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9241     bool Fast = false;
9242     auto Flags = Store->getMemOperand()->getFlags();
9243     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9244                                            Store->getAlign(), Flags, &Fast) &&
9245         Fast)
9246       return SDValue();
9247 
9248     if (VT.isVector())
9249       return SplitVectorStore(Op, DAG);
9250 
9251     return expandUnalignedStore(Store, DAG);
9252   }
9253 
9254   // Probably an invalid store. If so we'll end up emitting a selection error.
9255   return SDValue();
9256 }
9257 
9258 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9259   SDLoc DL(Op);
9260   EVT VT = Op.getValueType();
9261   SDValue Arg = Op.getOperand(0);
9262   SDValue TrigVal;
9263 
9264   // Propagate fast-math flags so that the multiply we introduce can be folded
9265   // if Arg is already the result of a multiply by constant.
9266   auto Flags = Op->getFlags();
9267 
9268   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9269 
9270   if (Subtarget->hasTrigReducedRange()) {
9271     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9272     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9273   } else {
9274     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9275   }
9276 
9277   switch (Op.getOpcode()) {
9278   case ISD::FCOS:
9279     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9280   case ISD::FSIN:
9281     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9282   default:
9283     llvm_unreachable("Wrong trig opcode");
9284   }
9285 }
9286 
9287 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9288   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9289   assert(AtomicNode->isCompareAndSwap());
9290   unsigned AS = AtomicNode->getAddressSpace();
9291 
9292   // No custom lowering required for local address space
9293   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9294     return Op;
9295 
9296   // Non-local address space requires custom lowering for atomic compare
9297   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9298   SDLoc DL(Op);
9299   SDValue ChainIn = Op.getOperand(0);
9300   SDValue Addr = Op.getOperand(1);
9301   SDValue Old = Op.getOperand(2);
9302   SDValue New = Op.getOperand(3);
9303   EVT VT = Op.getValueType();
9304   MVT SimpleVT = VT.getSimpleVT();
9305   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9306 
9307   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9308   SDValue Ops[] = { ChainIn, Addr, NewOld };
9309 
9310   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9311                                  Ops, VT, AtomicNode->getMemOperand());
9312 }
9313 
9314 //===----------------------------------------------------------------------===//
9315 // Custom DAG optimizations
9316 //===----------------------------------------------------------------------===//
9317 
9318 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9319                                                      DAGCombinerInfo &DCI) const {
9320   EVT VT = N->getValueType(0);
9321   EVT ScalarVT = VT.getScalarType();
9322   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9323     return SDValue();
9324 
9325   SelectionDAG &DAG = DCI.DAG;
9326   SDLoc DL(N);
9327 
9328   SDValue Src = N->getOperand(0);
9329   EVT SrcVT = Src.getValueType();
9330 
9331   // TODO: We could try to match extracting the higher bytes, which would be
9332   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9333   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9334   // about in practice.
9335   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9336     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9337       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9338       DCI.AddToWorklist(Cvt.getNode());
9339 
9340       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9341       if (ScalarVT != MVT::f32) {
9342         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9343                           DAG.getTargetConstant(0, DL, MVT::i32));
9344       }
9345       return Cvt;
9346     }
9347   }
9348 
9349   return SDValue();
9350 }
9351 
9352 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9353 
9354 // This is a variant of
9355 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9356 //
9357 // The normal DAG combiner will do this, but only if the add has one use since
9358 // that would increase the number of instructions.
9359 //
9360 // This prevents us from seeing a constant offset that can be folded into a
9361 // memory instruction's addressing mode. If we know the resulting add offset of
9362 // a pointer can be folded into an addressing offset, we can replace the pointer
9363 // operand with the add of new constant offset. This eliminates one of the uses,
9364 // and may allow the remaining use to also be simplified.
9365 //
9366 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9367                                                unsigned AddrSpace,
9368                                                EVT MemVT,
9369                                                DAGCombinerInfo &DCI) const {
9370   SDValue N0 = N->getOperand(0);
9371   SDValue N1 = N->getOperand(1);
9372 
9373   // We only do this to handle cases where it's profitable when there are
9374   // multiple uses of the add, so defer to the standard combine.
9375   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9376       N0->hasOneUse())
9377     return SDValue();
9378 
9379   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9380   if (!CN1)
9381     return SDValue();
9382 
9383   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9384   if (!CAdd)
9385     return SDValue();
9386 
9387   // If the resulting offset is too large, we can't fold it into the addressing
9388   // mode offset.
9389   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9390   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9391 
9392   AddrMode AM;
9393   AM.HasBaseReg = true;
9394   AM.BaseOffs = Offset.getSExtValue();
9395   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9396     return SDValue();
9397 
9398   SelectionDAG &DAG = DCI.DAG;
9399   SDLoc SL(N);
9400   EVT VT = N->getValueType(0);
9401 
9402   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9403   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9404 
9405   SDNodeFlags Flags;
9406   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9407                           (N0.getOpcode() == ISD::OR ||
9408                            N0->getFlags().hasNoUnsignedWrap()));
9409 
9410   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9411 }
9412 
9413 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9414 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9415 /// specific intrinsic, but they all place the pointer operand first.
9416 static unsigned getBasePtrIndex(const MemSDNode *N) {
9417   switch (N->getOpcode()) {
9418   case ISD::STORE:
9419   case ISD::INTRINSIC_W_CHAIN:
9420   case ISD::INTRINSIC_VOID:
9421     return 2;
9422   default:
9423     return 1;
9424   }
9425 }
9426 
9427 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9428                                                   DAGCombinerInfo &DCI) const {
9429   SelectionDAG &DAG = DCI.DAG;
9430   SDLoc SL(N);
9431 
9432   unsigned PtrIdx = getBasePtrIndex(N);
9433   SDValue Ptr = N->getOperand(PtrIdx);
9434 
9435   // TODO: We could also do this for multiplies.
9436   if (Ptr.getOpcode() == ISD::SHL) {
9437     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9438                                           N->getMemoryVT(), DCI);
9439     if (NewPtr) {
9440       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9441 
9442       NewOps[PtrIdx] = NewPtr;
9443       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9444     }
9445   }
9446 
9447   return SDValue();
9448 }
9449 
9450 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9451   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9452          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9453          (Opc == ISD::XOR && Val == 0);
9454 }
9455 
9456 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9457 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9458 // integer combine opportunities since most 64-bit operations are decomposed
9459 // this way.  TODO: We won't want this for SALU especially if it is an inline
9460 // immediate.
9461 SDValue SITargetLowering::splitBinaryBitConstantOp(
9462   DAGCombinerInfo &DCI,
9463   const SDLoc &SL,
9464   unsigned Opc, SDValue LHS,
9465   const ConstantSDNode *CRHS) const {
9466   uint64_t Val = CRHS->getZExtValue();
9467   uint32_t ValLo = Lo_32(Val);
9468   uint32_t ValHi = Hi_32(Val);
9469   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9470 
9471     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9472          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9473         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9474     // If we need to materialize a 64-bit immediate, it will be split up later
9475     // anyway. Avoid creating the harder to understand 64-bit immediate
9476     // materialization.
9477     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9478   }
9479 
9480   return SDValue();
9481 }
9482 
9483 // Returns true if argument is a boolean value which is not serialized into
9484 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9485 static bool isBoolSGPR(SDValue V) {
9486   if (V.getValueType() != MVT::i1)
9487     return false;
9488   switch (V.getOpcode()) {
9489   default:
9490     break;
9491   case ISD::SETCC:
9492   case AMDGPUISD::FP_CLASS:
9493     return true;
9494   case ISD::AND:
9495   case ISD::OR:
9496   case ISD::XOR:
9497     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9498   }
9499   return false;
9500 }
9501 
9502 // If a constant has all zeroes or all ones within each byte return it.
9503 // Otherwise return 0.
9504 static uint32_t getConstantPermuteMask(uint32_t C) {
9505   // 0xff for any zero byte in the mask
9506   uint32_t ZeroByteMask = 0;
9507   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9508   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9509   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9510   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9511   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9512   if ((NonZeroByteMask & C) != NonZeroByteMask)
9513     return 0; // Partial bytes selected.
9514   return C;
9515 }
9516 
9517 // Check if a node selects whole bytes from its operand 0 starting at a byte
9518 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9519 // or -1 if not succeeded.
9520 // Note byte select encoding:
9521 // value 0-3 selects corresponding source byte;
9522 // value 0xc selects zero;
9523 // value 0xff selects 0xff.
9524 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9525   assert(V.getValueSizeInBits() == 32);
9526 
9527   if (V.getNumOperands() != 2)
9528     return ~0;
9529 
9530   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9531   if (!N1)
9532     return ~0;
9533 
9534   uint32_t C = N1->getZExtValue();
9535 
9536   switch (V.getOpcode()) {
9537   default:
9538     break;
9539   case ISD::AND:
9540     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9541       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9542     }
9543     break;
9544 
9545   case ISD::OR:
9546     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9547       return (0x03020100 & ~ConstMask) | ConstMask;
9548     }
9549     break;
9550 
9551   case ISD::SHL:
9552     if (C % 8)
9553       return ~0;
9554 
9555     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9556 
9557   case ISD::SRL:
9558     if (C % 8)
9559       return ~0;
9560 
9561     return uint32_t(0x0c0c0c0c03020100ull >> C);
9562   }
9563 
9564   return ~0;
9565 }
9566 
9567 SDValue SITargetLowering::performAndCombine(SDNode *N,
9568                                             DAGCombinerInfo &DCI) const {
9569   if (DCI.isBeforeLegalize())
9570     return SDValue();
9571 
9572   SelectionDAG &DAG = DCI.DAG;
9573   EVT VT = N->getValueType(0);
9574   SDValue LHS = N->getOperand(0);
9575   SDValue RHS = N->getOperand(1);
9576 
9577 
9578   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9579   if (VT == MVT::i64 && CRHS) {
9580     if (SDValue Split
9581         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9582       return Split;
9583   }
9584 
9585   if (CRHS && VT == MVT::i32) {
9586     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9587     // nb = number of trailing zeroes in mask
9588     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9589     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9590     uint64_t Mask = CRHS->getZExtValue();
9591     unsigned Bits = countPopulation(Mask);
9592     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9593         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9594       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9595         unsigned Shift = CShift->getZExtValue();
9596         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9597         unsigned Offset = NB + Shift;
9598         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9599           SDLoc SL(N);
9600           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9601                                     LHS->getOperand(0),
9602                                     DAG.getConstant(Offset, SL, MVT::i32),
9603                                     DAG.getConstant(Bits, SL, MVT::i32));
9604           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9605           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9606                                     DAG.getValueType(NarrowVT));
9607           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9608                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9609           return Shl;
9610         }
9611       }
9612     }
9613 
9614     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9615     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9616         isa<ConstantSDNode>(LHS.getOperand(2))) {
9617       uint32_t Sel = getConstantPermuteMask(Mask);
9618       if (!Sel)
9619         return SDValue();
9620 
9621       // Select 0xc for all zero bytes
9622       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9623       SDLoc DL(N);
9624       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9625                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9626     }
9627   }
9628 
9629   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9630   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9631   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9632     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9633     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9634 
9635     SDValue X = LHS.getOperand(0);
9636     SDValue Y = RHS.getOperand(0);
9637     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9638       return SDValue();
9639 
9640     if (LCC == ISD::SETO) {
9641       if (X != LHS.getOperand(1))
9642         return SDValue();
9643 
9644       if (RCC == ISD::SETUNE) {
9645         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9646         if (!C1 || !C1->isInfinity() || C1->isNegative())
9647           return SDValue();
9648 
9649         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9650                               SIInstrFlags::N_SUBNORMAL |
9651                               SIInstrFlags::N_ZERO |
9652                               SIInstrFlags::P_ZERO |
9653                               SIInstrFlags::P_SUBNORMAL |
9654                               SIInstrFlags::P_NORMAL;
9655 
9656         static_assert(((~(SIInstrFlags::S_NAN |
9657                           SIInstrFlags::Q_NAN |
9658                           SIInstrFlags::N_INFINITY |
9659                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9660                       "mask not equal");
9661 
9662         SDLoc DL(N);
9663         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9664                            X, DAG.getConstant(Mask, DL, MVT::i32));
9665       }
9666     }
9667   }
9668 
9669   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9670     std::swap(LHS, RHS);
9671 
9672   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9673       RHS.hasOneUse()) {
9674     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9675     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9676     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9677     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9678     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9679         (RHS.getOperand(0) == LHS.getOperand(0) &&
9680          LHS.getOperand(0) == LHS.getOperand(1))) {
9681       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9682       unsigned NewMask = LCC == ISD::SETO ?
9683         Mask->getZExtValue() & ~OrdMask :
9684         Mask->getZExtValue() & OrdMask;
9685 
9686       SDLoc DL(N);
9687       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9688                          DAG.getConstant(NewMask, DL, MVT::i32));
9689     }
9690   }
9691 
9692   if (VT == MVT::i32 &&
9693       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9694     // and x, (sext cc from i1) => select cc, x, 0
9695     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9696       std::swap(LHS, RHS);
9697     if (isBoolSGPR(RHS.getOperand(0)))
9698       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9699                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9700   }
9701 
9702   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9703   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9704   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9705       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9706     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9707     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9708     if (LHSMask != ~0u && RHSMask != ~0u) {
9709       // Canonicalize the expression in an attempt to have fewer unique masks
9710       // and therefore fewer registers used to hold the masks.
9711       if (LHSMask > RHSMask) {
9712         std::swap(LHSMask, RHSMask);
9713         std::swap(LHS, RHS);
9714       }
9715 
9716       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9717       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9718       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9719       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9720 
9721       // Check of we need to combine values from two sources within a byte.
9722       if (!(LHSUsedLanes & RHSUsedLanes) &&
9723           // If we select high and lower word keep it for SDWA.
9724           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9725           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9726         // Each byte in each mask is either selector mask 0-3, or has higher
9727         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9728         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9729         // mask which is not 0xff wins. By anding both masks we have a correct
9730         // result except that 0x0c shall be corrected to give 0x0c only.
9731         uint32_t Mask = LHSMask & RHSMask;
9732         for (unsigned I = 0; I < 32; I += 8) {
9733           uint32_t ByteSel = 0xff << I;
9734           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9735             Mask &= (0x0c << I) & 0xffffffff;
9736         }
9737 
9738         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9739         // or 0x0c.
9740         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9741         SDLoc DL(N);
9742 
9743         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9744                            LHS.getOperand(0), RHS.getOperand(0),
9745                            DAG.getConstant(Sel, DL, MVT::i32));
9746       }
9747     }
9748   }
9749 
9750   return SDValue();
9751 }
9752 
9753 SDValue SITargetLowering::performOrCombine(SDNode *N,
9754                                            DAGCombinerInfo &DCI) const {
9755   SelectionDAG &DAG = DCI.DAG;
9756   SDValue LHS = N->getOperand(0);
9757   SDValue RHS = N->getOperand(1);
9758 
9759   EVT VT = N->getValueType(0);
9760   if (VT == MVT::i1) {
9761     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9762     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9763         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9764       SDValue Src = LHS.getOperand(0);
9765       if (Src != RHS.getOperand(0))
9766         return SDValue();
9767 
9768       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9769       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9770       if (!CLHS || !CRHS)
9771         return SDValue();
9772 
9773       // Only 10 bits are used.
9774       static const uint32_t MaxMask = 0x3ff;
9775 
9776       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9777       SDLoc DL(N);
9778       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9779                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9780     }
9781 
9782     return SDValue();
9783   }
9784 
9785   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9786   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9787       LHS.getOpcode() == AMDGPUISD::PERM &&
9788       isa<ConstantSDNode>(LHS.getOperand(2))) {
9789     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9790     if (!Sel)
9791       return SDValue();
9792 
9793     Sel |= LHS.getConstantOperandVal(2);
9794     SDLoc DL(N);
9795     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9796                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9797   }
9798 
9799   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9800   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9801   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9802       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9803     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9804     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9805     if (LHSMask != ~0u && RHSMask != ~0u) {
9806       // Canonicalize the expression in an attempt to have fewer unique masks
9807       // and therefore fewer registers used to hold the masks.
9808       if (LHSMask > RHSMask) {
9809         std::swap(LHSMask, RHSMask);
9810         std::swap(LHS, RHS);
9811       }
9812 
9813       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9814       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9815       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9816       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9817 
9818       // Check of we need to combine values from two sources within a byte.
9819       if (!(LHSUsedLanes & RHSUsedLanes) &&
9820           // If we select high and lower word keep it for SDWA.
9821           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9822           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9823         // Kill zero bytes selected by other mask. Zero value is 0xc.
9824         LHSMask &= ~RHSUsedLanes;
9825         RHSMask &= ~LHSUsedLanes;
9826         // Add 4 to each active LHS lane
9827         LHSMask |= LHSUsedLanes & 0x04040404;
9828         // Combine masks
9829         uint32_t Sel = LHSMask | RHSMask;
9830         SDLoc DL(N);
9831 
9832         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9833                            LHS.getOperand(0), RHS.getOperand(0),
9834                            DAG.getConstant(Sel, DL, MVT::i32));
9835       }
9836     }
9837   }
9838 
9839   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9840     return SDValue();
9841 
9842   // TODO: This could be a generic combine with a predicate for extracting the
9843   // high half of an integer being free.
9844 
9845   // (or i64:x, (zero_extend i32:y)) ->
9846   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9847   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9848       RHS.getOpcode() != ISD::ZERO_EXTEND)
9849     std::swap(LHS, RHS);
9850 
9851   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9852     SDValue ExtSrc = RHS.getOperand(0);
9853     EVT SrcVT = ExtSrc.getValueType();
9854     if (SrcVT == MVT::i32) {
9855       SDLoc SL(N);
9856       SDValue LowLHS, HiBits;
9857       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9858       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9859 
9860       DCI.AddToWorklist(LowOr.getNode());
9861       DCI.AddToWorklist(HiBits.getNode());
9862 
9863       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9864                                 LowOr, HiBits);
9865       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9866     }
9867   }
9868 
9869   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9870   if (CRHS) {
9871     if (SDValue Split
9872           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9873                                      N->getOperand(0), CRHS))
9874       return Split;
9875   }
9876 
9877   return SDValue();
9878 }
9879 
9880 SDValue SITargetLowering::performXorCombine(SDNode *N,
9881                                             DAGCombinerInfo &DCI) const {
9882   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9883     return RV;
9884 
9885   EVT VT = N->getValueType(0);
9886   if (VT != MVT::i64)
9887     return SDValue();
9888 
9889   SDValue LHS = N->getOperand(0);
9890   SDValue RHS = N->getOperand(1);
9891 
9892   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9893   if (CRHS) {
9894     if (SDValue Split
9895           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9896       return Split;
9897   }
9898 
9899   return SDValue();
9900 }
9901 
9902 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9903                                                    DAGCombinerInfo &DCI) const {
9904   if (!Subtarget->has16BitInsts() ||
9905       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9906     return SDValue();
9907 
9908   EVT VT = N->getValueType(0);
9909   if (VT != MVT::i32)
9910     return SDValue();
9911 
9912   SDValue Src = N->getOperand(0);
9913   if (Src.getValueType() != MVT::i16)
9914     return SDValue();
9915 
9916   return SDValue();
9917 }
9918 
9919 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9920                                                         DAGCombinerInfo &DCI)
9921                                                         const {
9922   SDValue Src = N->getOperand(0);
9923   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9924 
9925   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9926       VTSign->getVT() == MVT::i8) ||
9927       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9928       VTSign->getVT() == MVT::i16)) &&
9929       Src.hasOneUse()) {
9930     auto *M = cast<MemSDNode>(Src);
9931     SDValue Ops[] = {
9932       Src.getOperand(0), // Chain
9933       Src.getOperand(1), // rsrc
9934       Src.getOperand(2), // vindex
9935       Src.getOperand(3), // voffset
9936       Src.getOperand(4), // soffset
9937       Src.getOperand(5), // offset
9938       Src.getOperand(6),
9939       Src.getOperand(7)
9940     };
9941     // replace with BUFFER_LOAD_BYTE/SHORT
9942     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9943                                          Src.getOperand(0).getValueType());
9944     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9945                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9946     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9947                                                           ResList,
9948                                                           Ops, M->getMemoryVT(),
9949                                                           M->getMemOperand());
9950     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9951                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9952   }
9953   return SDValue();
9954 }
9955 
9956 SDValue SITargetLowering::performClassCombine(SDNode *N,
9957                                               DAGCombinerInfo &DCI) const {
9958   SelectionDAG &DAG = DCI.DAG;
9959   SDValue Mask = N->getOperand(1);
9960 
9961   // fp_class x, 0 -> false
9962   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9963     if (CMask->isZero())
9964       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9965   }
9966 
9967   if (N->getOperand(0).isUndef())
9968     return DAG.getUNDEF(MVT::i1);
9969 
9970   return SDValue();
9971 }
9972 
9973 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9974                                             DAGCombinerInfo &DCI) const {
9975   EVT VT = N->getValueType(0);
9976   SDValue N0 = N->getOperand(0);
9977 
9978   if (N0.isUndef())
9979     return N0;
9980 
9981   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9982                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9983     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9984                            N->getFlags());
9985   }
9986 
9987   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9988     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9989                            N0.getOperand(0), N->getFlags());
9990   }
9991 
9992   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9993 }
9994 
9995 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9996                                        unsigned MaxDepth) const {
9997   unsigned Opcode = Op.getOpcode();
9998   if (Opcode == ISD::FCANONICALIZE)
9999     return true;
10000 
10001   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10002     auto F = CFP->getValueAPF();
10003     if (F.isNaN() && F.isSignaling())
10004       return false;
10005     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
10006   }
10007 
10008   // If source is a result of another standard FP operation it is already in
10009   // canonical form.
10010   if (MaxDepth == 0)
10011     return false;
10012 
10013   switch (Opcode) {
10014   // These will flush denorms if required.
10015   case ISD::FADD:
10016   case ISD::FSUB:
10017   case ISD::FMUL:
10018   case ISD::FCEIL:
10019   case ISD::FFLOOR:
10020   case ISD::FMA:
10021   case ISD::FMAD:
10022   case ISD::FSQRT:
10023   case ISD::FDIV:
10024   case ISD::FREM:
10025   case ISD::FP_ROUND:
10026   case ISD::FP_EXTEND:
10027   case AMDGPUISD::FMUL_LEGACY:
10028   case AMDGPUISD::FMAD_FTZ:
10029   case AMDGPUISD::RCP:
10030   case AMDGPUISD::RSQ:
10031   case AMDGPUISD::RSQ_CLAMP:
10032   case AMDGPUISD::RCP_LEGACY:
10033   case AMDGPUISD::RCP_IFLAG:
10034   case AMDGPUISD::DIV_SCALE:
10035   case AMDGPUISD::DIV_FMAS:
10036   case AMDGPUISD::DIV_FIXUP:
10037   case AMDGPUISD::FRACT:
10038   case AMDGPUISD::LDEXP:
10039   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10040   case AMDGPUISD::CVT_F32_UBYTE0:
10041   case AMDGPUISD::CVT_F32_UBYTE1:
10042   case AMDGPUISD::CVT_F32_UBYTE2:
10043   case AMDGPUISD::CVT_F32_UBYTE3:
10044     return true;
10045 
10046   // It can/will be lowered or combined as a bit operation.
10047   // Need to check their input recursively to handle.
10048   case ISD::FNEG:
10049   case ISD::FABS:
10050   case ISD::FCOPYSIGN:
10051     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10052 
10053   case ISD::FSIN:
10054   case ISD::FCOS:
10055   case ISD::FSINCOS:
10056     return Op.getValueType().getScalarType() != MVT::f16;
10057 
10058   case ISD::FMINNUM:
10059   case ISD::FMAXNUM:
10060   case ISD::FMINNUM_IEEE:
10061   case ISD::FMAXNUM_IEEE:
10062   case AMDGPUISD::CLAMP:
10063   case AMDGPUISD::FMED3:
10064   case AMDGPUISD::FMAX3:
10065   case AMDGPUISD::FMIN3: {
10066     // FIXME: Shouldn't treat the generic operations different based these.
10067     // However, we aren't really required to flush the result from
10068     // minnum/maxnum..
10069 
10070     // snans will be quieted, so we only need to worry about denormals.
10071     if (Subtarget->supportsMinMaxDenormModes() ||
10072         denormalsEnabledForType(DAG, Op.getValueType()))
10073       return true;
10074 
10075     // Flushing may be required.
10076     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
10077     // targets need to check their input recursively.
10078 
10079     // FIXME: Does this apply with clamp? It's implemented with max.
10080     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
10081       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
10082         return false;
10083     }
10084 
10085     return true;
10086   }
10087   case ISD::SELECT: {
10088     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
10089            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
10090   }
10091   case ISD::BUILD_VECTOR: {
10092     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
10093       SDValue SrcOp = Op.getOperand(i);
10094       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
10095         return false;
10096     }
10097 
10098     return true;
10099   }
10100   case ISD::EXTRACT_VECTOR_ELT:
10101   case ISD::EXTRACT_SUBVECTOR: {
10102     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10103   }
10104   case ISD::INSERT_VECTOR_ELT: {
10105     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
10106            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
10107   }
10108   case ISD::UNDEF:
10109     // Could be anything.
10110     return false;
10111 
10112   case ISD::BITCAST:
10113     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10114   case ISD::TRUNCATE: {
10115     // Hack round the mess we make when legalizing extract_vector_elt
10116     if (Op.getValueType() == MVT::i16) {
10117       SDValue TruncSrc = Op.getOperand(0);
10118       if (TruncSrc.getValueType() == MVT::i32 &&
10119           TruncSrc.getOpcode() == ISD::BITCAST &&
10120           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
10121         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
10122       }
10123     }
10124     return false;
10125   }
10126   case ISD::INTRINSIC_WO_CHAIN: {
10127     unsigned IntrinsicID
10128       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10129     // TODO: Handle more intrinsics
10130     switch (IntrinsicID) {
10131     case Intrinsic::amdgcn_cvt_pkrtz:
10132     case Intrinsic::amdgcn_cubeid:
10133     case Intrinsic::amdgcn_frexp_mant:
10134     case Intrinsic::amdgcn_fdot2:
10135     case Intrinsic::amdgcn_rcp:
10136     case Intrinsic::amdgcn_rsq:
10137     case Intrinsic::amdgcn_rsq_clamp:
10138     case Intrinsic::amdgcn_rcp_legacy:
10139     case Intrinsic::amdgcn_rsq_legacy:
10140     case Intrinsic::amdgcn_trig_preop:
10141       return true;
10142     default:
10143       break;
10144     }
10145 
10146     LLVM_FALLTHROUGH;
10147   }
10148   default:
10149     return denormalsEnabledForType(DAG, Op.getValueType()) &&
10150            DAG.isKnownNeverSNaN(Op);
10151   }
10152 
10153   llvm_unreachable("invalid operation");
10154 }
10155 
10156 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10157                                        unsigned MaxDepth) const {
10158   MachineRegisterInfo &MRI = MF.getRegInfo();
10159   MachineInstr *MI = MRI.getVRegDef(Reg);
10160   unsigned Opcode = MI->getOpcode();
10161 
10162   if (Opcode == AMDGPU::G_FCANONICALIZE)
10163     return true;
10164 
10165   Optional<FPValueAndVReg> FCR;
10166   // Constant splat (can be padded with undef) or scalar constant.
10167   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10168     if (FCR->Value.isSignaling())
10169       return false;
10170     return !FCR->Value.isDenormal() ||
10171            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10172   }
10173 
10174   if (MaxDepth == 0)
10175     return false;
10176 
10177   switch (Opcode) {
10178   case AMDGPU::G_FMINNUM_IEEE:
10179   case AMDGPU::G_FMAXNUM_IEEE: {
10180     if (Subtarget->supportsMinMaxDenormModes() ||
10181         denormalsEnabledForType(MRI.getType(Reg), MF))
10182       return true;
10183     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10184       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10185         return false;
10186     return true;
10187   }
10188   default:
10189     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10190            isKnownNeverSNaN(Reg, MRI);
10191   }
10192 
10193   llvm_unreachable("invalid operation");
10194 }
10195 
10196 // Constant fold canonicalize.
10197 SDValue SITargetLowering::getCanonicalConstantFP(
10198   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10199   // Flush denormals to 0 if not enabled.
10200   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10201     return DAG.getConstantFP(0.0, SL, VT);
10202 
10203   if (C.isNaN()) {
10204     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10205     if (C.isSignaling()) {
10206       // Quiet a signaling NaN.
10207       // FIXME: Is this supposed to preserve payload bits?
10208       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10209     }
10210 
10211     // Make sure it is the canonical NaN bitpattern.
10212     //
10213     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10214     // immediate?
10215     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10216       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10217   }
10218 
10219   // Already canonical.
10220   return DAG.getConstantFP(C, SL, VT);
10221 }
10222 
10223 static bool vectorEltWillFoldAway(SDValue Op) {
10224   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10225 }
10226 
10227 SDValue SITargetLowering::performFCanonicalizeCombine(
10228   SDNode *N,
10229   DAGCombinerInfo &DCI) const {
10230   SelectionDAG &DAG = DCI.DAG;
10231   SDValue N0 = N->getOperand(0);
10232   EVT VT = N->getValueType(0);
10233 
10234   // fcanonicalize undef -> qnan
10235   if (N0.isUndef()) {
10236     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10237     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10238   }
10239 
10240   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10241     EVT VT = N->getValueType(0);
10242     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10243   }
10244 
10245   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10246   //                                                   (fcanonicalize k)
10247   //
10248   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10249 
10250   // TODO: This could be better with wider vectors that will be split to v2f16,
10251   // and to consider uses since there aren't that many packed operations.
10252   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10253       isTypeLegal(MVT::v2f16)) {
10254     SDLoc SL(N);
10255     SDValue NewElts[2];
10256     SDValue Lo = N0.getOperand(0);
10257     SDValue Hi = N0.getOperand(1);
10258     EVT EltVT = Lo.getValueType();
10259 
10260     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10261       for (unsigned I = 0; I != 2; ++I) {
10262         SDValue Op = N0.getOperand(I);
10263         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10264           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10265                                               CFP->getValueAPF());
10266         } else if (Op.isUndef()) {
10267           // Handled below based on what the other operand is.
10268           NewElts[I] = Op;
10269         } else {
10270           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10271         }
10272       }
10273 
10274       // If one half is undef, and one is constant, prefer a splat vector rather
10275       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10276       // cheaper to use and may be free with a packed operation.
10277       if (NewElts[0].isUndef()) {
10278         if (isa<ConstantFPSDNode>(NewElts[1]))
10279           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10280             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10281       }
10282 
10283       if (NewElts[1].isUndef()) {
10284         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10285           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10286       }
10287 
10288       return DAG.getBuildVector(VT, SL, NewElts);
10289     }
10290   }
10291 
10292   unsigned SrcOpc = N0.getOpcode();
10293 
10294   // If it's free to do so, push canonicalizes further up the source, which may
10295   // find a canonical source.
10296   //
10297   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10298   // sNaNs.
10299   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10300     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10301     if (CRHS && N0.hasOneUse()) {
10302       SDLoc SL(N);
10303       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10304                                    N0.getOperand(0));
10305       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10306       DCI.AddToWorklist(Canon0.getNode());
10307 
10308       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10309     }
10310   }
10311 
10312   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10313 }
10314 
10315 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10316   switch (Opc) {
10317   case ISD::FMAXNUM:
10318   case ISD::FMAXNUM_IEEE:
10319     return AMDGPUISD::FMAX3;
10320   case ISD::SMAX:
10321     return AMDGPUISD::SMAX3;
10322   case ISD::UMAX:
10323     return AMDGPUISD::UMAX3;
10324   case ISD::FMINNUM:
10325   case ISD::FMINNUM_IEEE:
10326     return AMDGPUISD::FMIN3;
10327   case ISD::SMIN:
10328     return AMDGPUISD::SMIN3;
10329   case ISD::UMIN:
10330     return AMDGPUISD::UMIN3;
10331   default:
10332     llvm_unreachable("Not a min/max opcode");
10333   }
10334 }
10335 
10336 SDValue SITargetLowering::performIntMed3ImmCombine(
10337   SelectionDAG &DAG, const SDLoc &SL,
10338   SDValue Op0, SDValue Op1, bool Signed) const {
10339   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10340   if (!K1)
10341     return SDValue();
10342 
10343   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10344   if (!K0)
10345     return SDValue();
10346 
10347   if (Signed) {
10348     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10349       return SDValue();
10350   } else {
10351     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10352       return SDValue();
10353   }
10354 
10355   EVT VT = K0->getValueType(0);
10356   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10357   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10358     return DAG.getNode(Med3Opc, SL, VT,
10359                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10360   }
10361 
10362   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10363   if (VT == MVT::i16) {
10364     MVT NVT = MVT::i32;
10365     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10366 
10367     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10368     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10369     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10370 
10371     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10372     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10373   }
10374 
10375   return SDValue();
10376 }
10377 
10378 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10379   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10380     return C;
10381 
10382   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10383     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10384       return C;
10385   }
10386 
10387   return nullptr;
10388 }
10389 
10390 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10391                                                   const SDLoc &SL,
10392                                                   SDValue Op0,
10393                                                   SDValue Op1) const {
10394   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10395   if (!K1)
10396     return SDValue();
10397 
10398   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10399   if (!K0)
10400     return SDValue();
10401 
10402   // Ordered >= (although NaN inputs should have folded away by now).
10403   if (K0->getValueAPF() > K1->getValueAPF())
10404     return SDValue();
10405 
10406   const MachineFunction &MF = DAG.getMachineFunction();
10407   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10408 
10409   // TODO: Check IEEE bit enabled?
10410   EVT VT = Op0.getValueType();
10411   if (Info->getMode().DX10Clamp) {
10412     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10413     // hardware fmed3 behavior converting to a min.
10414     // FIXME: Should this be allowing -0.0?
10415     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10416       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10417   }
10418 
10419   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10420   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10421     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10422     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10423     // then give the other result, which is different from med3 with a NaN
10424     // input.
10425     SDValue Var = Op0.getOperand(0);
10426     if (!DAG.isKnownNeverSNaN(Var))
10427       return SDValue();
10428 
10429     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10430 
10431     if ((!K0->hasOneUse() ||
10432          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10433         (!K1->hasOneUse() ||
10434          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10435       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10436                          Var, SDValue(K0, 0), SDValue(K1, 0));
10437     }
10438   }
10439 
10440   return SDValue();
10441 }
10442 
10443 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10444                                                DAGCombinerInfo &DCI) const {
10445   SelectionDAG &DAG = DCI.DAG;
10446 
10447   EVT VT = N->getValueType(0);
10448   unsigned Opc = N->getOpcode();
10449   SDValue Op0 = N->getOperand(0);
10450   SDValue Op1 = N->getOperand(1);
10451 
10452   // Only do this if the inner op has one use since this will just increases
10453   // register pressure for no benefit.
10454 
10455   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10456       !VT.isVector() &&
10457       (VT == MVT::i32 || VT == MVT::f32 ||
10458        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10459     // max(max(a, b), c) -> max3(a, b, c)
10460     // min(min(a, b), c) -> min3(a, b, c)
10461     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10462       SDLoc DL(N);
10463       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10464                          DL,
10465                          N->getValueType(0),
10466                          Op0.getOperand(0),
10467                          Op0.getOperand(1),
10468                          Op1);
10469     }
10470 
10471     // Try commuted.
10472     // max(a, max(b, c)) -> max3(a, b, c)
10473     // min(a, min(b, c)) -> min3(a, b, c)
10474     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10475       SDLoc DL(N);
10476       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10477                          DL,
10478                          N->getValueType(0),
10479                          Op0,
10480                          Op1.getOperand(0),
10481                          Op1.getOperand(1));
10482     }
10483   }
10484 
10485   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10486   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10487     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10488       return Med3;
10489   }
10490 
10491   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10492     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10493       return Med3;
10494   }
10495 
10496   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10497   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10498        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10499        (Opc == AMDGPUISD::FMIN_LEGACY &&
10500         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10501       (VT == MVT::f32 || VT == MVT::f64 ||
10502        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10503        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10504       Op0.hasOneUse()) {
10505     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10506       return Res;
10507   }
10508 
10509   return SDValue();
10510 }
10511 
10512 static bool isClampZeroToOne(SDValue A, SDValue B) {
10513   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10514     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10515       // FIXME: Should this be allowing -0.0?
10516       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10517              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10518     }
10519   }
10520 
10521   return false;
10522 }
10523 
10524 // FIXME: Should only worry about snans for version with chain.
10525 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10526                                               DAGCombinerInfo &DCI) const {
10527   EVT VT = N->getValueType(0);
10528   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10529   // NaNs. With a NaN input, the order of the operands may change the result.
10530 
10531   SelectionDAG &DAG = DCI.DAG;
10532   SDLoc SL(N);
10533 
10534   SDValue Src0 = N->getOperand(0);
10535   SDValue Src1 = N->getOperand(1);
10536   SDValue Src2 = N->getOperand(2);
10537 
10538   if (isClampZeroToOne(Src0, Src1)) {
10539     // const_a, const_b, x -> clamp is safe in all cases including signaling
10540     // nans.
10541     // FIXME: Should this be allowing -0.0?
10542     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10543   }
10544 
10545   const MachineFunction &MF = DAG.getMachineFunction();
10546   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10547 
10548   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10549   // handling no dx10-clamp?
10550   if (Info->getMode().DX10Clamp) {
10551     // If NaNs is clamped to 0, we are free to reorder the inputs.
10552 
10553     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10554       std::swap(Src0, Src1);
10555 
10556     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10557       std::swap(Src1, Src2);
10558 
10559     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10560       std::swap(Src0, Src1);
10561 
10562     if (isClampZeroToOne(Src1, Src2))
10563       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10564   }
10565 
10566   return SDValue();
10567 }
10568 
10569 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10570                                                  DAGCombinerInfo &DCI) const {
10571   SDValue Src0 = N->getOperand(0);
10572   SDValue Src1 = N->getOperand(1);
10573   if (Src0.isUndef() && Src1.isUndef())
10574     return DCI.DAG.getUNDEF(N->getValueType(0));
10575   return SDValue();
10576 }
10577 
10578 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10579 // expanded into a set of cmp/select instructions.
10580 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10581                                                 unsigned NumElem,
10582                                                 bool IsDivergentIdx,
10583                                                 const GCNSubtarget *Subtarget) {
10584   if (UseDivergentRegisterIndexing)
10585     return false;
10586 
10587   unsigned VecSize = EltSize * NumElem;
10588 
10589   // Sub-dword vectors of size 2 dword or less have better implementation.
10590   if (VecSize <= 64 && EltSize < 32)
10591     return false;
10592 
10593   // Always expand the rest of sub-dword instructions, otherwise it will be
10594   // lowered via memory.
10595   if (EltSize < 32)
10596     return true;
10597 
10598   // Always do this if var-idx is divergent, otherwise it will become a loop.
10599   if (IsDivergentIdx)
10600     return true;
10601 
10602   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10603   unsigned NumInsts = NumElem /* Number of compares */ +
10604                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10605 
10606   // On some architectures (GFX9) movrel is not available and it's better
10607   // to expand.
10608   if (!Subtarget->hasMovrel())
10609     return NumInsts <= 16;
10610 
10611   // If movrel is available, use it instead of expanding for vector of 8
10612   // elements.
10613   return NumInsts <= 15;
10614 }
10615 
10616 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
10617   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10618   if (isa<ConstantSDNode>(Idx))
10619     return false;
10620 
10621   SDValue Vec = N->getOperand(0);
10622   EVT VecVT = Vec.getValueType();
10623   EVT EltVT = VecVT.getVectorElementType();
10624   unsigned EltSize = EltVT.getSizeInBits();
10625   unsigned NumElem = VecVT.getVectorNumElements();
10626 
10627   return SITargetLowering::shouldExpandVectorDynExt(
10628       EltSize, NumElem, Idx->isDivergent(), getSubtarget());
10629 }
10630 
10631 SDValue SITargetLowering::performExtractVectorEltCombine(
10632   SDNode *N, DAGCombinerInfo &DCI) const {
10633   SDValue Vec = N->getOperand(0);
10634   SelectionDAG &DAG = DCI.DAG;
10635 
10636   EVT VecVT = Vec.getValueType();
10637   EVT EltVT = VecVT.getVectorElementType();
10638 
10639   if ((Vec.getOpcode() == ISD::FNEG ||
10640        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10641     SDLoc SL(N);
10642     EVT EltVT = N->getValueType(0);
10643     SDValue Idx = N->getOperand(1);
10644     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10645                               Vec.getOperand(0), Idx);
10646     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10647   }
10648 
10649   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10650   //    =>
10651   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10652   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10653   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10654   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10655     SDLoc SL(N);
10656     EVT EltVT = N->getValueType(0);
10657     SDValue Idx = N->getOperand(1);
10658     unsigned Opc = Vec.getOpcode();
10659 
10660     switch(Opc) {
10661     default:
10662       break;
10663       // TODO: Support other binary operations.
10664     case ISD::FADD:
10665     case ISD::FSUB:
10666     case ISD::FMUL:
10667     case ISD::ADD:
10668     case ISD::UMIN:
10669     case ISD::UMAX:
10670     case ISD::SMIN:
10671     case ISD::SMAX:
10672     case ISD::FMAXNUM:
10673     case ISD::FMINNUM:
10674     case ISD::FMAXNUM_IEEE:
10675     case ISD::FMINNUM_IEEE: {
10676       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10677                                  Vec.getOperand(0), Idx);
10678       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10679                                  Vec.getOperand(1), Idx);
10680 
10681       DCI.AddToWorklist(Elt0.getNode());
10682       DCI.AddToWorklist(Elt1.getNode());
10683       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10684     }
10685     }
10686   }
10687 
10688   unsigned VecSize = VecVT.getSizeInBits();
10689   unsigned EltSize = EltVT.getSizeInBits();
10690 
10691   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10692   if (shouldExpandVectorDynExt(N)) {
10693     SDLoc SL(N);
10694     SDValue Idx = N->getOperand(1);
10695     SDValue V;
10696     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10697       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10698       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10699       if (I == 0)
10700         V = Elt;
10701       else
10702         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10703     }
10704     return V;
10705   }
10706 
10707   if (!DCI.isBeforeLegalize())
10708     return SDValue();
10709 
10710   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10711   // elements. This exposes more load reduction opportunities by replacing
10712   // multiple small extract_vector_elements with a single 32-bit extract.
10713   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10714   if (isa<MemSDNode>(Vec) &&
10715       EltSize <= 16 &&
10716       EltVT.isByteSized() &&
10717       VecSize > 32 &&
10718       VecSize % 32 == 0 &&
10719       Idx) {
10720     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10721 
10722     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10723     unsigned EltIdx = BitIndex / 32;
10724     unsigned LeftoverBitIdx = BitIndex % 32;
10725     SDLoc SL(N);
10726 
10727     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10728     DCI.AddToWorklist(Cast.getNode());
10729 
10730     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10731                               DAG.getConstant(EltIdx, SL, MVT::i32));
10732     DCI.AddToWorklist(Elt.getNode());
10733     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10734                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10735     DCI.AddToWorklist(Srl.getNode());
10736 
10737     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10738     DCI.AddToWorklist(Trunc.getNode());
10739     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10740   }
10741 
10742   return SDValue();
10743 }
10744 
10745 SDValue
10746 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10747                                                 DAGCombinerInfo &DCI) const {
10748   SDValue Vec = N->getOperand(0);
10749   SDValue Idx = N->getOperand(2);
10750   EVT VecVT = Vec.getValueType();
10751   EVT EltVT = VecVT.getVectorElementType();
10752 
10753   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10754   // => BUILD_VECTOR n x select (e, const-idx)
10755   if (!shouldExpandVectorDynExt(N))
10756     return SDValue();
10757 
10758   SelectionDAG &DAG = DCI.DAG;
10759   SDLoc SL(N);
10760   SDValue Ins = N->getOperand(1);
10761   EVT IdxVT = Idx.getValueType();
10762 
10763   SmallVector<SDValue, 16> Ops;
10764   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10765     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10766     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10767     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10768     Ops.push_back(V);
10769   }
10770 
10771   return DAG.getBuildVector(VecVT, SL, Ops);
10772 }
10773 
10774 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10775                                           const SDNode *N0,
10776                                           const SDNode *N1) const {
10777   EVT VT = N0->getValueType(0);
10778 
10779   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10780   // support denormals ever.
10781   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10782        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10783         getSubtarget()->hasMadF16())) &&
10784        isOperationLegal(ISD::FMAD, VT))
10785     return ISD::FMAD;
10786 
10787   const TargetOptions &Options = DAG.getTarget().Options;
10788   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10789        (N0->getFlags().hasAllowContract() &&
10790         N1->getFlags().hasAllowContract())) &&
10791       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10792     return ISD::FMA;
10793   }
10794 
10795   return 0;
10796 }
10797 
10798 // For a reassociatable opcode perform:
10799 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10800 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10801                                                SelectionDAG &DAG) const {
10802   EVT VT = N->getValueType(0);
10803   if (VT != MVT::i32 && VT != MVT::i64)
10804     return SDValue();
10805 
10806   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10807     return SDValue();
10808 
10809   unsigned Opc = N->getOpcode();
10810   SDValue Op0 = N->getOperand(0);
10811   SDValue Op1 = N->getOperand(1);
10812 
10813   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10814     return SDValue();
10815 
10816   if (Op0->isDivergent())
10817     std::swap(Op0, Op1);
10818 
10819   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10820     return SDValue();
10821 
10822   SDValue Op2 = Op1.getOperand(1);
10823   Op1 = Op1.getOperand(0);
10824   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10825     return SDValue();
10826 
10827   if (Op1->isDivergent())
10828     std::swap(Op1, Op2);
10829 
10830   SDLoc SL(N);
10831   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10832   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10833 }
10834 
10835 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10836                            EVT VT,
10837                            SDValue N0, SDValue N1, SDValue N2,
10838                            bool Signed) {
10839   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10840   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10841   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10842   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10843 }
10844 
10845 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
10846 // multiplies, if any.
10847 //
10848 // Full 64-bit multiplies that feed into an addition are lowered here instead
10849 // of using the generic expansion. The generic expansion ends up with
10850 // a tree of ADD nodes that prevents us from using the "add" part of the
10851 // MAD instruction. The expansion produced here results in a chain of ADDs
10852 // instead of a tree.
10853 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10854                                             DAGCombinerInfo &DCI) const {
10855   assert(N->getOpcode() == ISD::ADD);
10856 
10857   SelectionDAG &DAG = DCI.DAG;
10858   EVT VT = N->getValueType(0);
10859   SDLoc SL(N);
10860   SDValue LHS = N->getOperand(0);
10861   SDValue RHS = N->getOperand(1);
10862 
10863   if (VT.isVector())
10864     return SDValue();
10865 
10866   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
10867   // result in scalar registers for uniform values.
10868   if (!N->isDivergent() && Subtarget->hasSMulHi())
10869     return SDValue();
10870 
10871   unsigned NumBits = VT.getScalarSizeInBits();
10872   if (NumBits <= 32 || NumBits > 64)
10873     return SDValue();
10874 
10875   if (LHS.getOpcode() != ISD::MUL) {
10876     assert(RHS.getOpcode() == ISD::MUL);
10877     std::swap(LHS, RHS);
10878   }
10879 
10880   // Avoid the fold if it would unduly increase the number of multiplies due to
10881   // multiple uses, except on hardware with full-rate multiply-add (which is
10882   // part of full-rate 64-bit ops).
10883   if (!Subtarget->hasFullRate64Ops()) {
10884     unsigned NumUsers = 0;
10885     for (SDNode *Use : LHS->uses()) {
10886       // There is a use that does not feed into addition, so the multiply can't
10887       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
10888       if (Use->getOpcode() != ISD::ADD)
10889         return SDValue();
10890 
10891       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
10892       // MUL + 3xADD + 3xADDC over 3xMAD.
10893       ++NumUsers;
10894       if (NumUsers >= 3)
10895         return SDValue();
10896     }
10897   }
10898 
10899   SDValue MulLHS = LHS.getOperand(0);
10900   SDValue MulRHS = LHS.getOperand(1);
10901   SDValue AddRHS = RHS;
10902 
10903   // Always check whether operands are small unsigned values, since that
10904   // knowledge is useful in more cases. Check for small signed values only if
10905   // doing so can unlock a shorter code sequence.
10906   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
10907   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
10908 
10909   bool MulSignedLo = false;
10910   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
10911     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
10912                   numBitsSigned(MulRHS, DAG) <= 32;
10913   }
10914 
10915   // The operands and final result all have the same number of bits. If
10916   // operands need to be extended, they can be extended with garbage. The
10917   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
10918   // truncated away in the end.
10919   if (VT != MVT::i64) {
10920     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
10921     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
10922     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
10923   }
10924 
10925   // The basic code generated is conceptually straightforward. Pseudo code:
10926   //
10927   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
10928   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
10929   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
10930   //
10931   // The second and third lines are optional, depending on whether the factors
10932   // are {sign,zero}-extended or not.
10933   //
10934   // The actual DAG is noisier than the pseudo code, but only due to
10935   // instructions that disassemble values into low and high parts, and
10936   // assemble the final result.
10937   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
10938   SDValue One = DAG.getConstant(1, SL, MVT::i32);
10939 
10940   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
10941   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
10942   SDValue Accum =
10943       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
10944 
10945   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
10946     auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero);
10947     auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One);
10948 
10949     if (!MulLHSUnsigned32) {
10950       auto MulLHSHi =
10951           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
10952       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
10953       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10954     }
10955 
10956     if (!MulRHSUnsigned32) {
10957       auto MulRHSHi =
10958           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
10959       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
10960       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10961     }
10962 
10963     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
10964     Accum = DAG.getBitcast(MVT::i64, Accum);
10965   }
10966 
10967   if (VT != MVT::i64)
10968     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
10969   return Accum;
10970 }
10971 
10972 SDValue SITargetLowering::performAddCombine(SDNode *N,
10973                                             DAGCombinerInfo &DCI) const {
10974   SelectionDAG &DAG = DCI.DAG;
10975   EVT VT = N->getValueType(0);
10976   SDLoc SL(N);
10977   SDValue LHS = N->getOperand(0);
10978   SDValue RHS = N->getOperand(1);
10979 
10980   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10981     if (Subtarget->hasMad64_32()) {
10982       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10983         return Folded;
10984     }
10985 
10986     return SDValue();
10987   }
10988 
10989   if (SDValue V = reassociateScalarOps(N, DAG)) {
10990     return V;
10991   }
10992 
10993   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10994     return SDValue();
10995 
10996   // add x, zext (setcc) => addcarry x, 0, setcc
10997   // add x, sext (setcc) => subcarry x, 0, setcc
10998   unsigned Opc = LHS.getOpcode();
10999   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
11000       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
11001     std::swap(RHS, LHS);
11002 
11003   Opc = RHS.getOpcode();
11004   switch (Opc) {
11005   default: break;
11006   case ISD::ZERO_EXTEND:
11007   case ISD::SIGN_EXTEND:
11008   case ISD::ANY_EXTEND: {
11009     auto Cond = RHS.getOperand(0);
11010     // If this won't be a real VOPC output, we would still need to insert an
11011     // extra instruction anyway.
11012     if (!isBoolSGPR(Cond))
11013       break;
11014     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11015     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11016     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
11017     return DAG.getNode(Opc, SL, VTList, Args);
11018   }
11019   case ISD::ADDCARRY: {
11020     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
11021     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
11022     if (!C || C->getZExtValue() != 0) break;
11023     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
11024     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
11025   }
11026   }
11027   return SDValue();
11028 }
11029 
11030 SDValue SITargetLowering::performSubCombine(SDNode *N,
11031                                             DAGCombinerInfo &DCI) const {
11032   SelectionDAG &DAG = DCI.DAG;
11033   EVT VT = N->getValueType(0);
11034 
11035   if (VT != MVT::i32)
11036     return SDValue();
11037 
11038   SDLoc SL(N);
11039   SDValue LHS = N->getOperand(0);
11040   SDValue RHS = N->getOperand(1);
11041 
11042   // sub x, zext (setcc) => subcarry x, 0, setcc
11043   // sub x, sext (setcc) => addcarry x, 0, setcc
11044   unsigned Opc = RHS.getOpcode();
11045   switch (Opc) {
11046   default: break;
11047   case ISD::ZERO_EXTEND:
11048   case ISD::SIGN_EXTEND:
11049   case ISD::ANY_EXTEND: {
11050     auto Cond = RHS.getOperand(0);
11051     // If this won't be a real VOPC output, we would still need to insert an
11052     // extra instruction anyway.
11053     if (!isBoolSGPR(Cond))
11054       break;
11055     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11056     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11057     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
11058     return DAG.getNode(Opc, SL, VTList, Args);
11059   }
11060   }
11061 
11062   if (LHS.getOpcode() == ISD::SUBCARRY) {
11063     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
11064     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
11065     if (!C || !C->isZero())
11066       return SDValue();
11067     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
11068     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
11069   }
11070   return SDValue();
11071 }
11072 
11073 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
11074   DAGCombinerInfo &DCI) const {
11075 
11076   if (N->getValueType(0) != MVT::i32)
11077     return SDValue();
11078 
11079   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11080   if (!C || C->getZExtValue() != 0)
11081     return SDValue();
11082 
11083   SelectionDAG &DAG = DCI.DAG;
11084   SDValue LHS = N->getOperand(0);
11085 
11086   // addcarry (add x, y), 0, cc => addcarry x, y, cc
11087   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
11088   unsigned LHSOpc = LHS.getOpcode();
11089   unsigned Opc = N->getOpcode();
11090   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
11091       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
11092     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
11093     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
11094   }
11095   return SDValue();
11096 }
11097 
11098 SDValue SITargetLowering::performFAddCombine(SDNode *N,
11099                                              DAGCombinerInfo &DCI) const {
11100   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11101     return SDValue();
11102 
11103   SelectionDAG &DAG = DCI.DAG;
11104   EVT VT = N->getValueType(0);
11105 
11106   SDLoc SL(N);
11107   SDValue LHS = N->getOperand(0);
11108   SDValue RHS = N->getOperand(1);
11109 
11110   // These should really be instruction patterns, but writing patterns with
11111   // source modifiers is a pain.
11112 
11113   // fadd (fadd (a, a), b) -> mad 2.0, a, b
11114   if (LHS.getOpcode() == ISD::FADD) {
11115     SDValue A = LHS.getOperand(0);
11116     if (A == LHS.getOperand(1)) {
11117       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11118       if (FusedOp != 0) {
11119         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11120         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
11121       }
11122     }
11123   }
11124 
11125   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
11126   if (RHS.getOpcode() == ISD::FADD) {
11127     SDValue A = RHS.getOperand(0);
11128     if (A == RHS.getOperand(1)) {
11129       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11130       if (FusedOp != 0) {
11131         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11132         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
11133       }
11134     }
11135   }
11136 
11137   return SDValue();
11138 }
11139 
11140 SDValue SITargetLowering::performFSubCombine(SDNode *N,
11141                                              DAGCombinerInfo &DCI) const {
11142   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11143     return SDValue();
11144 
11145   SelectionDAG &DAG = DCI.DAG;
11146   SDLoc SL(N);
11147   EVT VT = N->getValueType(0);
11148   assert(!VT.isVector());
11149 
11150   // Try to get the fneg to fold into the source modifier. This undoes generic
11151   // DAG combines and folds them into the mad.
11152   //
11153   // Only do this if we are not trying to support denormals. v_mad_f32 does
11154   // not support denormals ever.
11155   SDValue LHS = N->getOperand(0);
11156   SDValue RHS = N->getOperand(1);
11157   if (LHS.getOpcode() == ISD::FADD) {
11158     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
11159     SDValue A = LHS.getOperand(0);
11160     if (A == LHS.getOperand(1)) {
11161       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11162       if (FusedOp != 0){
11163         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11164         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
11165 
11166         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
11167       }
11168     }
11169   }
11170 
11171   if (RHS.getOpcode() == ISD::FADD) {
11172     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11173 
11174     SDValue A = RHS.getOperand(0);
11175     if (A == RHS.getOperand(1)) {
11176       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11177       if (FusedOp != 0){
11178         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11179         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11180       }
11181     }
11182   }
11183 
11184   return SDValue();
11185 }
11186 
11187 SDValue SITargetLowering::performFMACombine(SDNode *N,
11188                                             DAGCombinerInfo &DCI) const {
11189   SelectionDAG &DAG = DCI.DAG;
11190   EVT VT = N->getValueType(0);
11191   SDLoc SL(N);
11192 
11193   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11194     return SDValue();
11195 
11196   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11197   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11198   SDValue Op1 = N->getOperand(0);
11199   SDValue Op2 = N->getOperand(1);
11200   SDValue FMA = N->getOperand(2);
11201 
11202   if (FMA.getOpcode() != ISD::FMA ||
11203       Op1.getOpcode() != ISD::FP_EXTEND ||
11204       Op2.getOpcode() != ISD::FP_EXTEND)
11205     return SDValue();
11206 
11207   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11208   // regardless of the denorm mode setting. Therefore,
11209   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11210   const TargetOptions &Options = DAG.getTarget().Options;
11211   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11212       (N->getFlags().hasAllowContract() &&
11213        FMA->getFlags().hasAllowContract())) {
11214     Op1 = Op1.getOperand(0);
11215     Op2 = Op2.getOperand(0);
11216     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11217         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11218       return SDValue();
11219 
11220     SDValue Vec1 = Op1.getOperand(0);
11221     SDValue Idx1 = Op1.getOperand(1);
11222     SDValue Vec2 = Op2.getOperand(0);
11223 
11224     SDValue FMAOp1 = FMA.getOperand(0);
11225     SDValue FMAOp2 = FMA.getOperand(1);
11226     SDValue FMAAcc = FMA.getOperand(2);
11227 
11228     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11229         FMAOp2.getOpcode() != ISD::FP_EXTEND)
11230       return SDValue();
11231 
11232     FMAOp1 = FMAOp1.getOperand(0);
11233     FMAOp2 = FMAOp2.getOperand(0);
11234     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11235         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11236       return SDValue();
11237 
11238     SDValue Vec3 = FMAOp1.getOperand(0);
11239     SDValue Vec4 = FMAOp2.getOperand(0);
11240     SDValue Idx2 = FMAOp1.getOperand(1);
11241 
11242     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11243         // Idx1 and Idx2 cannot be the same.
11244         Idx1 == Idx2)
11245       return SDValue();
11246 
11247     if (Vec1 == Vec2 || Vec3 == Vec4)
11248       return SDValue();
11249 
11250     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11251       return SDValue();
11252 
11253     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11254         (Vec1 == Vec4 && Vec2 == Vec3)) {
11255       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11256                          DAG.getTargetConstant(0, SL, MVT::i1));
11257     }
11258   }
11259   return SDValue();
11260 }
11261 
11262 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11263                                               DAGCombinerInfo &DCI) const {
11264   SelectionDAG &DAG = DCI.DAG;
11265   SDLoc SL(N);
11266 
11267   SDValue LHS = N->getOperand(0);
11268   SDValue RHS = N->getOperand(1);
11269   EVT VT = LHS.getValueType();
11270   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11271 
11272   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11273   if (!CRHS) {
11274     CRHS = dyn_cast<ConstantSDNode>(LHS);
11275     if (CRHS) {
11276       std::swap(LHS, RHS);
11277       CC = getSetCCSwappedOperands(CC);
11278     }
11279   }
11280 
11281   if (CRHS) {
11282     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11283         isBoolSGPR(LHS.getOperand(0))) {
11284       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11285       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11286       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11287       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11288       if ((CRHS->isAllOnes() &&
11289            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11290           (CRHS->isZero() &&
11291            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11292         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11293                            DAG.getConstant(-1, SL, MVT::i1));
11294       if ((CRHS->isAllOnes() &&
11295            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11296           (CRHS->isZero() &&
11297            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11298         return LHS.getOperand(0);
11299     }
11300 
11301     const APInt &CRHSVal = CRHS->getAPIntValue();
11302     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11303         LHS.getOpcode() == ISD::SELECT &&
11304         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11305         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11306         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11307         isBoolSGPR(LHS.getOperand(0))) {
11308       // Given CT != FT:
11309       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11310       // setcc (select cc, CT, CF), CF, ne => cc
11311       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11312       // setcc (select cc, CT, CF), CT, eq => cc
11313       const APInt &CT = LHS.getConstantOperandAPInt(1);
11314       const APInt &CF = LHS.getConstantOperandAPInt(2);
11315 
11316       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11317           (CT == CRHSVal && CC == ISD::SETNE))
11318         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11319                            DAG.getConstant(-1, SL, MVT::i1));
11320       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11321           (CT == CRHSVal && CC == ISD::SETEQ))
11322         return LHS.getOperand(0);
11323     }
11324   }
11325 
11326   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11327                                            VT != MVT::f16))
11328     return SDValue();
11329 
11330   // Match isinf/isfinite pattern
11331   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11332   // (fcmp one (fabs x), inf) -> (fp_class x,
11333   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11334   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11335     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11336     if (!CRHS)
11337       return SDValue();
11338 
11339     const APFloat &APF = CRHS->getValueAPF();
11340     if (APF.isInfinity() && !APF.isNegative()) {
11341       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11342                                  SIInstrFlags::N_INFINITY;
11343       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11344                                     SIInstrFlags::P_ZERO |
11345                                     SIInstrFlags::N_NORMAL |
11346                                     SIInstrFlags::P_NORMAL |
11347                                     SIInstrFlags::N_SUBNORMAL |
11348                                     SIInstrFlags::P_SUBNORMAL;
11349       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11350       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11351                          DAG.getConstant(Mask, SL, MVT::i32));
11352     }
11353   }
11354 
11355   return SDValue();
11356 }
11357 
11358 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11359                                                      DAGCombinerInfo &DCI) const {
11360   SelectionDAG &DAG = DCI.DAG;
11361   SDLoc SL(N);
11362   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11363 
11364   SDValue Src = N->getOperand(0);
11365   SDValue Shift = N->getOperand(0);
11366 
11367   // TODO: Extend type shouldn't matter (assuming legal types).
11368   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11369     Shift = Shift.getOperand(0);
11370 
11371   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11372     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11373     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11374     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11375     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11376     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11377     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11378       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11379                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11380 
11381       unsigned ShiftOffset = 8 * Offset;
11382       if (Shift.getOpcode() == ISD::SHL)
11383         ShiftOffset -= C->getZExtValue();
11384       else
11385         ShiftOffset += C->getZExtValue();
11386 
11387       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11388         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11389                            MVT::f32, Shifted);
11390       }
11391     }
11392   }
11393 
11394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11395   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11396   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11397     // We simplified Src. If this node is not dead, visit it again so it is
11398     // folded properly.
11399     if (N->getOpcode() != ISD::DELETED_NODE)
11400       DCI.AddToWorklist(N);
11401     return SDValue(N, 0);
11402   }
11403 
11404   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11405   if (SDValue DemandedSrc =
11406           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11407     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11408 
11409   return SDValue();
11410 }
11411 
11412 SDValue SITargetLowering::performClampCombine(SDNode *N,
11413                                               DAGCombinerInfo &DCI) const {
11414   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11415   if (!CSrc)
11416     return SDValue();
11417 
11418   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11419   const APFloat &F = CSrc->getValueAPF();
11420   APFloat Zero = APFloat::getZero(F.getSemantics());
11421   if (F < Zero ||
11422       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11423     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11424   }
11425 
11426   APFloat One(F.getSemantics(), "1.0");
11427   if (F > One)
11428     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11429 
11430   return SDValue(CSrc, 0);
11431 }
11432 
11433 
11434 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11435                                             DAGCombinerInfo &DCI) const {
11436   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11437     return SDValue();
11438   switch (N->getOpcode()) {
11439   case ISD::ADD:
11440     return performAddCombine(N, DCI);
11441   case ISD::SUB:
11442     return performSubCombine(N, DCI);
11443   case ISD::ADDCARRY:
11444   case ISD::SUBCARRY:
11445     return performAddCarrySubCarryCombine(N, DCI);
11446   case ISD::FADD:
11447     return performFAddCombine(N, DCI);
11448   case ISD::FSUB:
11449     return performFSubCombine(N, DCI);
11450   case ISD::SETCC:
11451     return performSetCCCombine(N, DCI);
11452   case ISD::FMAXNUM:
11453   case ISD::FMINNUM:
11454   case ISD::FMAXNUM_IEEE:
11455   case ISD::FMINNUM_IEEE:
11456   case ISD::SMAX:
11457   case ISD::SMIN:
11458   case ISD::UMAX:
11459   case ISD::UMIN:
11460   case AMDGPUISD::FMIN_LEGACY:
11461   case AMDGPUISD::FMAX_LEGACY:
11462     return performMinMaxCombine(N, DCI);
11463   case ISD::FMA:
11464     return performFMACombine(N, DCI);
11465   case ISD::AND:
11466     return performAndCombine(N, DCI);
11467   case ISD::OR:
11468     return performOrCombine(N, DCI);
11469   case ISD::XOR:
11470     return performXorCombine(N, DCI);
11471   case ISD::ZERO_EXTEND:
11472     return performZeroExtendCombine(N, DCI);
11473   case ISD::SIGN_EXTEND_INREG:
11474     return performSignExtendInRegCombine(N , DCI);
11475   case AMDGPUISD::FP_CLASS:
11476     return performClassCombine(N, DCI);
11477   case ISD::FCANONICALIZE:
11478     return performFCanonicalizeCombine(N, DCI);
11479   case AMDGPUISD::RCP:
11480     return performRcpCombine(N, DCI);
11481   case AMDGPUISD::FRACT:
11482   case AMDGPUISD::RSQ:
11483   case AMDGPUISD::RCP_LEGACY:
11484   case AMDGPUISD::RCP_IFLAG:
11485   case AMDGPUISD::RSQ_CLAMP:
11486   case AMDGPUISD::LDEXP: {
11487     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11488     SDValue Src = N->getOperand(0);
11489     if (Src.isUndef())
11490       return Src;
11491     break;
11492   }
11493   case ISD::SINT_TO_FP:
11494   case ISD::UINT_TO_FP:
11495     return performUCharToFloatCombine(N, DCI);
11496   case AMDGPUISD::CVT_F32_UBYTE0:
11497   case AMDGPUISD::CVT_F32_UBYTE1:
11498   case AMDGPUISD::CVT_F32_UBYTE2:
11499   case AMDGPUISD::CVT_F32_UBYTE3:
11500     return performCvtF32UByteNCombine(N, DCI);
11501   case AMDGPUISD::FMED3:
11502     return performFMed3Combine(N, DCI);
11503   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11504     return performCvtPkRTZCombine(N, DCI);
11505   case AMDGPUISD::CLAMP:
11506     return performClampCombine(N, DCI);
11507   case ISD::SCALAR_TO_VECTOR: {
11508     SelectionDAG &DAG = DCI.DAG;
11509     EVT VT = N->getValueType(0);
11510 
11511     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11512     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11513       SDLoc SL(N);
11514       SDValue Src = N->getOperand(0);
11515       EVT EltVT = Src.getValueType();
11516       if (EltVT == MVT::f16)
11517         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11518 
11519       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11520       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11521     }
11522 
11523     break;
11524   }
11525   case ISD::EXTRACT_VECTOR_ELT:
11526     return performExtractVectorEltCombine(N, DCI);
11527   case ISD::INSERT_VECTOR_ELT:
11528     return performInsertVectorEltCombine(N, DCI);
11529   case ISD::LOAD: {
11530     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11531       return Widended;
11532     LLVM_FALLTHROUGH;
11533   }
11534   default: {
11535     if (!DCI.isBeforeLegalize()) {
11536       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11537         return performMemSDNodeCombine(MemNode, DCI);
11538     }
11539 
11540     break;
11541   }
11542   }
11543 
11544   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11545 }
11546 
11547 /// Helper function for adjustWritemask
11548 static unsigned SubIdx2Lane(unsigned Idx) {
11549   switch (Idx) {
11550   default: return ~0u;
11551   case AMDGPU::sub0: return 0;
11552   case AMDGPU::sub1: return 1;
11553   case AMDGPU::sub2: return 2;
11554   case AMDGPU::sub3: return 3;
11555   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11556   }
11557 }
11558 
11559 /// Adjust the writemask of MIMG instructions
11560 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11561                                           SelectionDAG &DAG) const {
11562   unsigned Opcode = Node->getMachineOpcode();
11563 
11564   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11565   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11566   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11567     return Node; // not implemented for D16
11568 
11569   SDNode *Users[5] = { nullptr };
11570   unsigned Lane = 0;
11571   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11572   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11573   unsigned NewDmask = 0;
11574   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11575   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11576   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11577                   Node->getConstantOperandVal(LWEIdx))
11578                      ? true
11579                      : false;
11580   unsigned TFCLane = 0;
11581   bool HasChain = Node->getNumValues() > 1;
11582 
11583   if (OldDmask == 0) {
11584     // These are folded out, but on the chance it happens don't assert.
11585     return Node;
11586   }
11587 
11588   unsigned OldBitsSet = countPopulation(OldDmask);
11589   // Work out which is the TFE/LWE lane if that is enabled.
11590   if (UsesTFC) {
11591     TFCLane = OldBitsSet;
11592   }
11593 
11594   // Try to figure out the used register components
11595   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11596        I != E; ++I) {
11597 
11598     // Don't look at users of the chain.
11599     if (I.getUse().getResNo() != 0)
11600       continue;
11601 
11602     // Abort if we can't understand the usage
11603     if (!I->isMachineOpcode() ||
11604         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11605       return Node;
11606 
11607     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11608     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11609     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11610     // set, etc.
11611     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11612     if (Lane == ~0u)
11613       return Node;
11614 
11615     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11616     if (UsesTFC && Lane == TFCLane) {
11617       Users[Lane] = *I;
11618     } else {
11619       // Set which texture component corresponds to the lane.
11620       unsigned Comp;
11621       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11622         Comp = countTrailingZeros(Dmask);
11623         Dmask &= ~(1 << Comp);
11624       }
11625 
11626       // Abort if we have more than one user per component.
11627       if (Users[Lane])
11628         return Node;
11629 
11630       Users[Lane] = *I;
11631       NewDmask |= 1 << Comp;
11632     }
11633   }
11634 
11635   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11636   bool NoChannels = !NewDmask;
11637   if (NoChannels) {
11638     if (!UsesTFC) {
11639       // No uses of the result and not using TFC. Then do nothing.
11640       return Node;
11641     }
11642     // If the original dmask has one channel - then nothing to do
11643     if (OldBitsSet == 1)
11644       return Node;
11645     // Use an arbitrary dmask - required for the instruction to work
11646     NewDmask = 1;
11647   }
11648   // Abort if there's no change
11649   if (NewDmask == OldDmask)
11650     return Node;
11651 
11652   unsigned BitsSet = countPopulation(NewDmask);
11653 
11654   // Check for TFE or LWE - increase the number of channels by one to account
11655   // for the extra return value
11656   // This will need adjustment for D16 if this is also included in
11657   // adjustWriteMask (this function) but at present D16 are excluded.
11658   unsigned NewChannels = BitsSet + UsesTFC;
11659 
11660   int NewOpcode =
11661       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11662   assert(NewOpcode != -1 &&
11663          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11664          "failed to find equivalent MIMG op");
11665 
11666   // Adjust the writemask in the node
11667   SmallVector<SDValue, 12> Ops;
11668   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11669   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11670   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11671 
11672   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11673 
11674   MVT ResultVT = NewChannels == 1 ?
11675     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11676                            NewChannels == 5 ? 8 : NewChannels);
11677   SDVTList NewVTList = HasChain ?
11678     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11679 
11680 
11681   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11682                                               NewVTList, Ops);
11683 
11684   if (HasChain) {
11685     // Update chain.
11686     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11687     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11688   }
11689 
11690   if (NewChannels == 1) {
11691     assert(Node->hasNUsesOfValue(1, 0));
11692     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11693                                       SDLoc(Node), Users[Lane]->getValueType(0),
11694                                       SDValue(NewNode, 0));
11695     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11696     return nullptr;
11697   }
11698 
11699   // Update the users of the node with the new indices
11700   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11701     SDNode *User = Users[i];
11702     if (!User) {
11703       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11704       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11705       if (i || !NoChannels)
11706         continue;
11707     } else {
11708       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11709       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11710     }
11711 
11712     switch (Idx) {
11713     default: break;
11714     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11715     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11716     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11717     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11718     }
11719   }
11720 
11721   DAG.RemoveDeadNode(Node);
11722   return nullptr;
11723 }
11724 
11725 static bool isFrameIndexOp(SDValue Op) {
11726   if (Op.getOpcode() == ISD::AssertZext)
11727     Op = Op.getOperand(0);
11728 
11729   return isa<FrameIndexSDNode>(Op);
11730 }
11731 
11732 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11733 /// with frame index operands.
11734 /// LLVM assumes that inputs are to these instructions are registers.
11735 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11736                                                         SelectionDAG &DAG) const {
11737   if (Node->getOpcode() == ISD::CopyToReg) {
11738     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11739     SDValue SrcVal = Node->getOperand(2);
11740 
11741     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11742     // to try understanding copies to physical registers.
11743     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11744       SDLoc SL(Node);
11745       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11746       SDValue VReg = DAG.getRegister(
11747         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11748 
11749       SDNode *Glued = Node->getGluedNode();
11750       SDValue ToVReg
11751         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11752                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11753       SDValue ToResultReg
11754         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11755                            VReg, ToVReg.getValue(1));
11756       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11757       DAG.RemoveDeadNode(Node);
11758       return ToResultReg.getNode();
11759     }
11760   }
11761 
11762   SmallVector<SDValue, 8> Ops;
11763   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11764     if (!isFrameIndexOp(Node->getOperand(i))) {
11765       Ops.push_back(Node->getOperand(i));
11766       continue;
11767     }
11768 
11769     SDLoc DL(Node);
11770     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11771                                      Node->getOperand(i).getValueType(),
11772                                      Node->getOperand(i)), 0));
11773   }
11774 
11775   return DAG.UpdateNodeOperands(Node, Ops);
11776 }
11777 
11778 /// Fold the instructions after selecting them.
11779 /// Returns null if users were already updated.
11780 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11781                                           SelectionDAG &DAG) const {
11782   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11783   unsigned Opcode = Node->getMachineOpcode();
11784 
11785   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11786       !TII->isGather4(Opcode) &&
11787       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11788     return adjustWritemask(Node, DAG);
11789   }
11790 
11791   if (Opcode == AMDGPU::INSERT_SUBREG ||
11792       Opcode == AMDGPU::REG_SEQUENCE) {
11793     legalizeTargetIndependentNode(Node, DAG);
11794     return Node;
11795   }
11796 
11797   switch (Opcode) {
11798   case AMDGPU::V_DIV_SCALE_F32_e64:
11799   case AMDGPU::V_DIV_SCALE_F64_e64: {
11800     // Satisfy the operand register constraint when one of the inputs is
11801     // undefined. Ordinarily each undef value will have its own implicit_def of
11802     // a vreg, so force these to use a single register.
11803     SDValue Src0 = Node->getOperand(1);
11804     SDValue Src1 = Node->getOperand(3);
11805     SDValue Src2 = Node->getOperand(5);
11806 
11807     if ((Src0.isMachineOpcode() &&
11808          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11809         (Src0 == Src1 || Src0 == Src2))
11810       break;
11811 
11812     MVT VT = Src0.getValueType().getSimpleVT();
11813     const TargetRegisterClass *RC =
11814         getRegClassFor(VT, Src0.getNode()->isDivergent());
11815 
11816     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11817     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11818 
11819     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11820                                       UndefReg, Src0, SDValue());
11821 
11822     // src0 must be the same register as src1 or src2, even if the value is
11823     // undefined, so make sure we don't violate this constraint.
11824     if (Src0.isMachineOpcode() &&
11825         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11826       if (Src1.isMachineOpcode() &&
11827           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11828         Src0 = Src1;
11829       else if (Src2.isMachineOpcode() &&
11830                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11831         Src0 = Src2;
11832       else {
11833         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11834         Src0 = UndefReg;
11835         Src1 = UndefReg;
11836       }
11837     } else
11838       break;
11839 
11840     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11841     Ops[1] = Src0;
11842     Ops[3] = Src1;
11843     Ops[5] = Src2;
11844     Ops.push_back(ImpDef.getValue(1));
11845     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11846   }
11847   default:
11848     break;
11849   }
11850 
11851   return Node;
11852 }
11853 
11854 // Any MIMG instructions that use tfe or lwe require an initialization of the
11855 // result register that will be written in the case of a memory access failure.
11856 // The required code is also added to tie this init code to the result of the
11857 // img instruction.
11858 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11859   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11860   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11861   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11862   MachineBasicBlock &MBB = *MI.getParent();
11863 
11864   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11865   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11866   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11867 
11868   if (!TFE && !LWE) // intersect_ray
11869     return;
11870 
11871   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11872   unsigned LWEVal = LWE->getImm();
11873   unsigned D16Val = D16 ? D16->getImm() : 0;
11874 
11875   if (!TFEVal && !LWEVal)
11876     return;
11877 
11878   // At least one of TFE or LWE are non-zero
11879   // We have to insert a suitable initialization of the result value and
11880   // tie this to the dest of the image instruction.
11881 
11882   const DebugLoc &DL = MI.getDebugLoc();
11883 
11884   int DstIdx =
11885       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11886 
11887   // Calculate which dword we have to initialize to 0.
11888   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11889 
11890   // check that dmask operand is found.
11891   assert(MO_Dmask && "Expected dmask operand in instruction");
11892 
11893   unsigned dmask = MO_Dmask->getImm();
11894   // Determine the number of active lanes taking into account the
11895   // Gather4 special case
11896   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11897 
11898   bool Packed = !Subtarget->hasUnpackedD16VMem();
11899 
11900   unsigned InitIdx =
11901       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11902 
11903   // Abandon attempt if the dst size isn't large enough
11904   // - this is in fact an error but this is picked up elsewhere and
11905   // reported correctly.
11906   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11907   if (DstSize < InitIdx)
11908     return;
11909 
11910   // Create a register for the initialization value.
11911   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11912   unsigned NewDst = 0; // Final initialized value will be in here
11913 
11914   // If PRTStrictNull feature is enabled (the default) then initialize
11915   // all the result registers to 0, otherwise just the error indication
11916   // register (VGPRn+1)
11917   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11918   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11919 
11920   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11921   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11922     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11923     // Initialize dword
11924     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11925     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11926       .addImm(0);
11927     // Insert into the super-reg
11928     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11929       .addReg(PrevDst)
11930       .addReg(SubReg)
11931       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11932 
11933     PrevDst = NewDst;
11934   }
11935 
11936   // Add as an implicit operand
11937   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11938 
11939   // Tie the just added implicit operand to the dst
11940   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11941 }
11942 
11943 /// Assign the register class depending on the number of
11944 /// bits set in the writemask
11945 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11946                                                      SDNode *Node) const {
11947   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11948 
11949   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11950 
11951   if (TII->isVOP3(MI.getOpcode())) {
11952     // Make sure constant bus requirements are respected.
11953     TII->legalizeOperandsVOP3(MRI, MI);
11954 
11955     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11956     // This saves a chain-copy of registers and better balance register
11957     // use between vgpr and agpr as agpr tuples tend to be big.
11958     if (MI.getDesc().OpInfo) {
11959       unsigned Opc = MI.getOpcode();
11960       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11961       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11962                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11963         if (I == -1)
11964           break;
11965         MachineOperand &Op = MI.getOperand(I);
11966         if (!Op.isReg() || !Op.getReg().isVirtual())
11967           continue;
11968         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11969         if (!TRI->hasAGPRs(RC))
11970           continue;
11971         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11972         if (!Src || !Src->isCopy() ||
11973             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11974           continue;
11975         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11976         // All uses of agpr64 and agpr32 can also accept vgpr except for
11977         // v_accvgpr_read, but we do not produce agpr reads during selection,
11978         // so no use checks are needed.
11979         MRI.setRegClass(Op.getReg(), NewRC);
11980       }
11981 
11982       // Resolve the rest of AV operands to AGPRs.
11983       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11984         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11985           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11986           if (TRI->isVectorSuperClass(RC)) {
11987             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11988             MRI.setRegClass(Src2->getReg(), NewRC);
11989             if (Src2->isTied())
11990               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11991           }
11992         }
11993       }
11994     }
11995 
11996     return;
11997   }
11998 
11999   if (TII->isMIMG(MI)) {
12000     if (!MI.mayStore())
12001       AddIMGInit(MI);
12002     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
12003   }
12004 }
12005 
12006 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
12007                               uint64_t Val) {
12008   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
12009   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
12010 }
12011 
12012 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
12013                                                 const SDLoc &DL,
12014                                                 SDValue Ptr) const {
12015   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12016 
12017   // Build the half of the subregister with the constants before building the
12018   // full 128-bit register. If we are building multiple resource descriptors,
12019   // this will allow CSEing of the 2-component register.
12020   const SDValue Ops0[] = {
12021     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
12022     buildSMovImm32(DAG, DL, 0),
12023     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12024     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
12025     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
12026   };
12027 
12028   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
12029                                                 MVT::v2i32, Ops0), 0);
12030 
12031   // Combine the constants and the pointer.
12032   const SDValue Ops1[] = {
12033     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12034     Ptr,
12035     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
12036     SubRegHi,
12037     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
12038   };
12039 
12040   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
12041 }
12042 
12043 /// Return a resource descriptor with the 'Add TID' bit enabled
12044 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
12045 ///        of the resource descriptor) to create an offset, which is added to
12046 ///        the resource pointer.
12047 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
12048                                            SDValue Ptr, uint32_t RsrcDword1,
12049                                            uint64_t RsrcDword2And3) const {
12050   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
12051   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
12052   if (RsrcDword1) {
12053     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
12054                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
12055                     0);
12056   }
12057 
12058   SDValue DataLo = buildSMovImm32(DAG, DL,
12059                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
12060   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
12061 
12062   const SDValue Ops[] = {
12063     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12064     PtrLo,
12065     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12066     PtrHi,
12067     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
12068     DataLo,
12069     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
12070     DataHi,
12071     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
12072   };
12073 
12074   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
12075 }
12076 
12077 //===----------------------------------------------------------------------===//
12078 //                         SI Inline Assembly Support
12079 //===----------------------------------------------------------------------===//
12080 
12081 std::pair<unsigned, const TargetRegisterClass *>
12082 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
12083                                                StringRef Constraint,
12084                                                MVT VT) const {
12085   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
12086 
12087   const TargetRegisterClass *RC = nullptr;
12088   if (Constraint.size() == 1) {
12089     const unsigned BitWidth = VT.getSizeInBits();
12090     switch (Constraint[0]) {
12091     default:
12092       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12093     case 's':
12094     case 'r':
12095       switch (BitWidth) {
12096       case 16:
12097         RC = &AMDGPU::SReg_32RegClass;
12098         break;
12099       case 64:
12100         RC = &AMDGPU::SGPR_64RegClass;
12101         break;
12102       default:
12103         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
12104         if (!RC)
12105           return std::make_pair(0U, nullptr);
12106         break;
12107       }
12108       break;
12109     case 'v':
12110       switch (BitWidth) {
12111       case 16:
12112         RC = &AMDGPU::VGPR_32RegClass;
12113         break;
12114       default:
12115         RC = TRI->getVGPRClassForBitWidth(BitWidth);
12116         if (!RC)
12117           return std::make_pair(0U, nullptr);
12118         break;
12119       }
12120       break;
12121     case 'a':
12122       if (!Subtarget->hasMAIInsts())
12123         break;
12124       switch (BitWidth) {
12125       case 16:
12126         RC = &AMDGPU::AGPR_32RegClass;
12127         break;
12128       default:
12129         RC = TRI->getAGPRClassForBitWidth(BitWidth);
12130         if (!RC)
12131           return std::make_pair(0U, nullptr);
12132         break;
12133       }
12134       break;
12135     }
12136     // We actually support i128, i16 and f16 as inline parameters
12137     // even if they are not reported as legal
12138     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
12139                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
12140       return std::make_pair(0U, RC);
12141   }
12142 
12143   if (Constraint.startswith("{") && Constraint.endswith("}")) {
12144     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
12145     if (RegName.consume_front("v")) {
12146       RC = &AMDGPU::VGPR_32RegClass;
12147     } else if (RegName.consume_front("s")) {
12148       RC = &AMDGPU::SGPR_32RegClass;
12149     } else if (RegName.consume_front("a")) {
12150       RC = &AMDGPU::AGPR_32RegClass;
12151     }
12152 
12153     if (RC) {
12154       uint32_t Idx;
12155       if (RegName.consume_front("[")) {
12156         uint32_t End;
12157         bool Failed = RegName.consumeInteger(10, Idx);
12158         Failed |= !RegName.consume_front(":");
12159         Failed |= RegName.consumeInteger(10, End);
12160         Failed |= !RegName.consume_back("]");
12161         if (!Failed) {
12162           uint32_t Width = (End - Idx + 1) * 32;
12163           MCRegister Reg = RC->getRegister(Idx);
12164           if (SIRegisterInfo::isVGPRClass(RC))
12165             RC = TRI->getVGPRClassForBitWidth(Width);
12166           else if (SIRegisterInfo::isSGPRClass(RC))
12167             RC = TRI->getSGPRClassForBitWidth(Width);
12168           else if (SIRegisterInfo::isAGPRClass(RC))
12169             RC = TRI->getAGPRClassForBitWidth(Width);
12170           if (RC) {
12171             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12172             return std::make_pair(Reg, RC);
12173           }
12174         }
12175       } else {
12176         bool Failed = RegName.getAsInteger(10, Idx);
12177         if (!Failed && Idx < RC->getNumRegs())
12178           return std::make_pair(RC->getRegister(Idx), RC);
12179       }
12180     }
12181   }
12182 
12183   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12184   if (Ret.first)
12185     Ret.second = TRI->getPhysRegClass(Ret.first);
12186 
12187   return Ret;
12188 }
12189 
12190 static bool isImmConstraint(StringRef Constraint) {
12191   if (Constraint.size() == 1) {
12192     switch (Constraint[0]) {
12193     default: break;
12194     case 'I':
12195     case 'J':
12196     case 'A':
12197     case 'B':
12198     case 'C':
12199       return true;
12200     }
12201   } else if (Constraint == "DA" ||
12202              Constraint == "DB") {
12203     return true;
12204   }
12205   return false;
12206 }
12207 
12208 SITargetLowering::ConstraintType
12209 SITargetLowering::getConstraintType(StringRef Constraint) const {
12210   if (Constraint.size() == 1) {
12211     switch (Constraint[0]) {
12212     default: break;
12213     case 's':
12214     case 'v':
12215     case 'a':
12216       return C_RegisterClass;
12217     }
12218   }
12219   if (isImmConstraint(Constraint)) {
12220     return C_Other;
12221   }
12222   return TargetLowering::getConstraintType(Constraint);
12223 }
12224 
12225 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12226   if (!AMDGPU::isInlinableIntLiteral(Val)) {
12227     Val = Val & maskTrailingOnes<uint64_t>(Size);
12228   }
12229   return Val;
12230 }
12231 
12232 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12233                                                     std::string &Constraint,
12234                                                     std::vector<SDValue> &Ops,
12235                                                     SelectionDAG &DAG) const {
12236   if (isImmConstraint(Constraint)) {
12237     uint64_t Val;
12238     if (getAsmOperandConstVal(Op, Val) &&
12239         checkAsmConstraintVal(Op, Constraint, Val)) {
12240       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12241       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12242     }
12243   } else {
12244     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12245   }
12246 }
12247 
12248 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12249   unsigned Size = Op.getScalarValueSizeInBits();
12250   if (Size > 64)
12251     return false;
12252 
12253   if (Size == 16 && !Subtarget->has16BitInsts())
12254     return false;
12255 
12256   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12257     Val = C->getSExtValue();
12258     return true;
12259   }
12260   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12261     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12262     return true;
12263   }
12264   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12265     if (Size != 16 || Op.getNumOperands() != 2)
12266       return false;
12267     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12268       return false;
12269     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12270       Val = C->getSExtValue();
12271       return true;
12272     }
12273     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12274       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12275       return true;
12276     }
12277   }
12278 
12279   return false;
12280 }
12281 
12282 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12283                                              const std::string &Constraint,
12284                                              uint64_t Val) const {
12285   if (Constraint.size() == 1) {
12286     switch (Constraint[0]) {
12287     case 'I':
12288       return AMDGPU::isInlinableIntLiteral(Val);
12289     case 'J':
12290       return isInt<16>(Val);
12291     case 'A':
12292       return checkAsmConstraintValA(Op, Val);
12293     case 'B':
12294       return isInt<32>(Val);
12295     case 'C':
12296       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12297              AMDGPU::isInlinableIntLiteral(Val);
12298     default:
12299       break;
12300     }
12301   } else if (Constraint.size() == 2) {
12302     if (Constraint == "DA") {
12303       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12304       int64_t LoBits = static_cast<int32_t>(Val);
12305       return checkAsmConstraintValA(Op, HiBits, 32) &&
12306              checkAsmConstraintValA(Op, LoBits, 32);
12307     }
12308     if (Constraint == "DB") {
12309       return true;
12310     }
12311   }
12312   llvm_unreachable("Invalid asm constraint");
12313 }
12314 
12315 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12316                                               uint64_t Val,
12317                                               unsigned MaxSize) const {
12318   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12319   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12320   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12321       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12322       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12323     return true;
12324   }
12325   return false;
12326 }
12327 
12328 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12329   switch (UnalignedClassID) {
12330   case AMDGPU::VReg_64RegClassID:
12331     return AMDGPU::VReg_64_Align2RegClassID;
12332   case AMDGPU::VReg_96RegClassID:
12333     return AMDGPU::VReg_96_Align2RegClassID;
12334   case AMDGPU::VReg_128RegClassID:
12335     return AMDGPU::VReg_128_Align2RegClassID;
12336   case AMDGPU::VReg_160RegClassID:
12337     return AMDGPU::VReg_160_Align2RegClassID;
12338   case AMDGPU::VReg_192RegClassID:
12339     return AMDGPU::VReg_192_Align2RegClassID;
12340   case AMDGPU::VReg_224RegClassID:
12341     return AMDGPU::VReg_224_Align2RegClassID;
12342   case AMDGPU::VReg_256RegClassID:
12343     return AMDGPU::VReg_256_Align2RegClassID;
12344   case AMDGPU::VReg_512RegClassID:
12345     return AMDGPU::VReg_512_Align2RegClassID;
12346   case AMDGPU::VReg_1024RegClassID:
12347     return AMDGPU::VReg_1024_Align2RegClassID;
12348   case AMDGPU::AReg_64RegClassID:
12349     return AMDGPU::AReg_64_Align2RegClassID;
12350   case AMDGPU::AReg_96RegClassID:
12351     return AMDGPU::AReg_96_Align2RegClassID;
12352   case AMDGPU::AReg_128RegClassID:
12353     return AMDGPU::AReg_128_Align2RegClassID;
12354   case AMDGPU::AReg_160RegClassID:
12355     return AMDGPU::AReg_160_Align2RegClassID;
12356   case AMDGPU::AReg_192RegClassID:
12357     return AMDGPU::AReg_192_Align2RegClassID;
12358   case AMDGPU::AReg_256RegClassID:
12359     return AMDGPU::AReg_256_Align2RegClassID;
12360   case AMDGPU::AReg_512RegClassID:
12361     return AMDGPU::AReg_512_Align2RegClassID;
12362   case AMDGPU::AReg_1024RegClassID:
12363     return AMDGPU::AReg_1024_Align2RegClassID;
12364   default:
12365     return -1;
12366   }
12367 }
12368 
12369 // Figure out which registers should be reserved for stack access. Only after
12370 // the function is legalized do we know all of the non-spill stack objects or if
12371 // calls are present.
12372 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12373   MachineRegisterInfo &MRI = MF.getRegInfo();
12374   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12375   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12376   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12377   const SIInstrInfo *TII = ST.getInstrInfo();
12378 
12379   if (Info->isEntryFunction()) {
12380     // Callable functions have fixed registers used for stack access.
12381     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12382   }
12383 
12384   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12385                              Info->getStackPtrOffsetReg()));
12386   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12387     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12388 
12389   // We need to worry about replacing the default register with itself in case
12390   // of MIR testcases missing the MFI.
12391   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12392     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12393 
12394   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12395     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12396 
12397   Info->limitOccupancy(MF);
12398 
12399   if (ST.isWave32() && !MF.empty()) {
12400     for (auto &MBB : MF) {
12401       for (auto &MI : MBB) {
12402         TII->fixImplicitOperands(MI);
12403       }
12404     }
12405   }
12406 
12407   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12408   // classes if required. Ideally the register class constraints would differ
12409   // per-subtarget, but there's no easy way to achieve that right now. This is
12410   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12411   // from using them as the register class for legal types.
12412   if (ST.needsAlignedVGPRs()) {
12413     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12414       const Register Reg = Register::index2VirtReg(I);
12415       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12416       if (!RC)
12417         continue;
12418       int NewClassID = getAlignedAGPRClassID(RC->getID());
12419       if (NewClassID != -1)
12420         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12421     }
12422   }
12423 
12424   TargetLoweringBase::finalizeLowering(MF);
12425 }
12426 
12427 void SITargetLowering::computeKnownBitsForFrameIndex(
12428   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12429   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12430 
12431   // Set the high bits to zero based on the maximum allowed scratch size per
12432   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12433   // calculation won't overflow, so assume the sign bit is never set.
12434   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12435 }
12436 
12437 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12438                                    KnownBits &Known, unsigned Dim) {
12439   unsigned MaxValue =
12440       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12441   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12442 }
12443 
12444 void SITargetLowering::computeKnownBitsForTargetInstr(
12445     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12446     const MachineRegisterInfo &MRI, unsigned Depth) const {
12447   const MachineInstr *MI = MRI.getVRegDef(R);
12448   switch (MI->getOpcode()) {
12449   case AMDGPU::G_INTRINSIC: {
12450     switch (MI->getIntrinsicID()) {
12451     case Intrinsic::amdgcn_workitem_id_x:
12452       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12453       break;
12454     case Intrinsic::amdgcn_workitem_id_y:
12455       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12456       break;
12457     case Intrinsic::amdgcn_workitem_id_z:
12458       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12459       break;
12460     case Intrinsic::amdgcn_mbcnt_lo:
12461     case Intrinsic::amdgcn_mbcnt_hi: {
12462       // These return at most the wavefront size - 1.
12463       unsigned Size = MRI.getType(R).getSizeInBits();
12464       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12465       break;
12466     }
12467     case Intrinsic::amdgcn_groupstaticsize: {
12468       // We can report everything over the maximum size as 0. We can't report
12469       // based on the actual size because we don't know if it's accurate or not
12470       // at any given point.
12471       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12472       break;
12473     }
12474     }
12475     break;
12476   }
12477   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12478     Known.Zero.setHighBits(24);
12479     break;
12480   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12481     Known.Zero.setHighBits(16);
12482     break;
12483   }
12484 }
12485 
12486 Align SITargetLowering::computeKnownAlignForTargetInstr(
12487   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12488   unsigned Depth) const {
12489   const MachineInstr *MI = MRI.getVRegDef(R);
12490   switch (MI->getOpcode()) {
12491   case AMDGPU::G_INTRINSIC:
12492   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12493     // FIXME: Can this move to generic code? What about the case where the call
12494     // site specifies a lower alignment?
12495     Intrinsic::ID IID = MI->getIntrinsicID();
12496     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12497     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12498     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12499       return *RetAlign;
12500     return Align(1);
12501   }
12502   default:
12503     return Align(1);
12504   }
12505 }
12506 
12507 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12508   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12509   const Align CacheLineAlign = Align(64);
12510 
12511   // Pre-GFX10 target did not benefit from loop alignment
12512   if (!ML || DisableLoopAlignment ||
12513       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12514       getSubtarget()->hasInstFwdPrefetchBug())
12515     return PrefAlign;
12516 
12517   // On GFX10 I$ is 4 x 64 bytes cache lines.
12518   // By default prefetcher keeps one cache line behind and reads two ahead.
12519   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12520   // behind and one ahead.
12521   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12522   // If loop fits 64 bytes it always spans no more than two cache lines and
12523   // does not need an alignment.
12524   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12525   // Else if loop is less or equal 192 bytes we need two lines behind.
12526 
12527   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12528   const MachineBasicBlock *Header = ML->getHeader();
12529   if (Header->getAlignment() != PrefAlign)
12530     return Header->getAlignment(); // Already processed.
12531 
12532   unsigned LoopSize = 0;
12533   for (const MachineBasicBlock *MBB : ML->blocks()) {
12534     // If inner loop block is aligned assume in average half of the alignment
12535     // size to be added as nops.
12536     if (MBB != Header)
12537       LoopSize += MBB->getAlignment().value() / 2;
12538 
12539     for (const MachineInstr &MI : *MBB) {
12540       LoopSize += TII->getInstSizeInBytes(MI);
12541       if (LoopSize > 192)
12542         return PrefAlign;
12543     }
12544   }
12545 
12546   if (LoopSize <= 64)
12547     return PrefAlign;
12548 
12549   if (LoopSize <= 128)
12550     return CacheLineAlign;
12551 
12552   // If any of parent loops is surrounded by prefetch instructions do not
12553   // insert new for inner loop, which would reset parent's settings.
12554   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12555     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12556       auto I = Exit->getFirstNonDebugInstr();
12557       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12558         return CacheLineAlign;
12559     }
12560   }
12561 
12562   MachineBasicBlock *Pre = ML->getLoopPreheader();
12563   MachineBasicBlock *Exit = ML->getExitBlock();
12564 
12565   if (Pre && Exit) {
12566     auto PreTerm = Pre->getFirstTerminator();
12567     if (PreTerm == Pre->begin() ||
12568         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12569       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12570           .addImm(1); // prefetch 2 lines behind PC
12571 
12572     auto ExitHead = Exit->getFirstNonDebugInstr();
12573     if (ExitHead == Exit->end() ||
12574         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12575       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12576           .addImm(2); // prefetch 1 line behind PC
12577   }
12578 
12579   return CacheLineAlign;
12580 }
12581 
12582 LLVM_ATTRIBUTE_UNUSED
12583 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12584   assert(N->getOpcode() == ISD::CopyFromReg);
12585   do {
12586     // Follow the chain until we find an INLINEASM node.
12587     N = N->getOperand(0).getNode();
12588     if (N->getOpcode() == ISD::INLINEASM ||
12589         N->getOpcode() == ISD::INLINEASM_BR)
12590       return true;
12591   } while (N->getOpcode() == ISD::CopyFromReg);
12592   return false;
12593 }
12594 
12595 bool SITargetLowering::isSDNodeSourceOfDivergence(
12596     const SDNode *N, FunctionLoweringInfo *FLI,
12597     LegacyDivergenceAnalysis *KDA) const {
12598   switch (N->getOpcode()) {
12599   case ISD::CopyFromReg: {
12600     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12601     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12602     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12603     Register Reg = R->getReg();
12604 
12605     // FIXME: Why does this need to consider isLiveIn?
12606     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12607       return !TRI->isSGPRReg(MRI, Reg);
12608 
12609     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12610       return KDA->isDivergent(V);
12611 
12612     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12613     return !TRI->isSGPRReg(MRI, Reg);
12614   }
12615   case ISD::LOAD: {
12616     const LoadSDNode *L = cast<LoadSDNode>(N);
12617     unsigned AS = L->getAddressSpace();
12618     // A flat load may access private memory.
12619     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12620   }
12621   case ISD::CALLSEQ_END:
12622     return true;
12623   case ISD::INTRINSIC_WO_CHAIN:
12624     return AMDGPU::isIntrinsicSourceOfDivergence(
12625         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12626   case ISD::INTRINSIC_W_CHAIN:
12627     return AMDGPU::isIntrinsicSourceOfDivergence(
12628         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12629   case AMDGPUISD::ATOMIC_CMP_SWAP:
12630   case AMDGPUISD::ATOMIC_INC:
12631   case AMDGPUISD::ATOMIC_DEC:
12632   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12633   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12634   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12635   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12636   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12637   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12638   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12639   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12640   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12641   case AMDGPUISD::BUFFER_ATOMIC_AND:
12642   case AMDGPUISD::BUFFER_ATOMIC_OR:
12643   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12644   case AMDGPUISD::BUFFER_ATOMIC_INC:
12645   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12646   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12647   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12648   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12649   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12650   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12651     // Target-specific read-modify-write atomics are sources of divergence.
12652     return true;
12653   default:
12654     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12655       // Generic read-modify-write atomics are sources of divergence.
12656       return A->readMem() && A->writeMem();
12657     }
12658     return false;
12659   }
12660 }
12661 
12662 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12663                                                EVT VT) const {
12664   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12665   case MVT::f32:
12666     return hasFP32Denormals(DAG.getMachineFunction());
12667   case MVT::f64:
12668   case MVT::f16:
12669     return hasFP64FP16Denormals(DAG.getMachineFunction());
12670   default:
12671     return false;
12672   }
12673 }
12674 
12675 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12676                                                MachineFunction &MF) const {
12677   switch (Ty.getScalarSizeInBits()) {
12678   case 32:
12679     return hasFP32Denormals(MF);
12680   case 64:
12681   case 16:
12682     return hasFP64FP16Denormals(MF);
12683   default:
12684     return false;
12685   }
12686 }
12687 
12688 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12689                                                     const SelectionDAG &DAG,
12690                                                     bool SNaN,
12691                                                     unsigned Depth) const {
12692   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12693     const MachineFunction &MF = DAG.getMachineFunction();
12694     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12695 
12696     if (Info->getMode().DX10Clamp)
12697       return true; // Clamped to 0.
12698     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12699   }
12700 
12701   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12702                                                             SNaN, Depth);
12703 }
12704 
12705 // Global FP atomic instructions have a hardcoded FP mode and do not support
12706 // FP32 denormals, and only support v2f16 denormals.
12707 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12708   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12709   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12710   if (&Flt == &APFloat::IEEEsingle())
12711     return DenormMode == DenormalMode::getPreserveSign();
12712   return DenormMode == DenormalMode::getIEEE();
12713 }
12714 
12715 TargetLowering::AtomicExpansionKind
12716 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12717   unsigned AS = RMW->getPointerAddressSpace();
12718   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12719     return AtomicExpansionKind::NotAtomic;
12720 
12721   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12722     OptimizationRemarkEmitter ORE(RMW->getFunction());
12723     LLVMContext &Ctx = RMW->getFunction()->getContext();
12724     SmallVector<StringRef> SSNs;
12725     Ctx.getSyncScopeNames(SSNs);
12726     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12727                         ? "system"
12728                         : SSNs[RMW->getSyncScopeID()];
12729     ORE.emit([&]() {
12730       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12731              << "Hardware instruction generated for atomic "
12732              << RMW->getOperationName(RMW->getOperation())
12733              << " operation at memory scope " << MemScope
12734              << " due to an unsafe request.";
12735     });
12736     return Kind;
12737   };
12738 
12739   switch (RMW->getOperation()) {
12740   case AtomicRMWInst::FAdd: {
12741     Type *Ty = RMW->getType();
12742 
12743     // We don't have a way to support 16-bit atomics now, so just leave them
12744     // as-is.
12745     if (Ty->isHalfTy())
12746       return AtomicExpansionKind::None;
12747 
12748     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12749       return AtomicExpansionKind::CmpXChg;
12750 
12751     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12752         Subtarget->hasAtomicFaddNoRtnInsts()) {
12753       if (Subtarget->hasGFX940Insts())
12754         return AtomicExpansionKind::None;
12755 
12756       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12757       // floating point atomic instructions. May generate more efficient code,
12758       // but may not respect rounding and denormal modes, and may give incorrect
12759       // results for certain memory destinations.
12760       if (RMW->getFunction()
12761               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12762               .getValueAsString() != "true")
12763         return AtomicExpansionKind::CmpXChg;
12764 
12765       if (Subtarget->hasGFX90AInsts()) {
12766         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12767           return AtomicExpansionKind::CmpXChg;
12768 
12769         auto SSID = RMW->getSyncScopeID();
12770         if (SSID == SyncScope::System ||
12771             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12772           return AtomicExpansionKind::CmpXChg;
12773 
12774         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12775       }
12776 
12777       if (AS == AMDGPUAS::FLAT_ADDRESS)
12778         return AtomicExpansionKind::CmpXChg;
12779 
12780       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12781                               : AtomicExpansionKind::CmpXChg;
12782     }
12783 
12784     // DS FP atomics do respect the denormal mode, but the rounding mode is
12785     // fixed to round-to-nearest-even.
12786     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12787     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12788       if (!Ty->isDoubleTy())
12789         return AtomicExpansionKind::None;
12790 
12791       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12792         return AtomicExpansionKind::None;
12793 
12794       return RMW->getFunction()
12795                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12796                          .getValueAsString() == "true"
12797                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12798                  : AtomicExpansionKind::CmpXChg;
12799     }
12800 
12801     return AtomicExpansionKind::CmpXChg;
12802   }
12803   default:
12804     break;
12805   }
12806 
12807   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12808 }
12809 
12810 TargetLowering::AtomicExpansionKind
12811 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12812   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12813              ? AtomicExpansionKind::NotAtomic
12814              : AtomicExpansionKind::None;
12815 }
12816 
12817 TargetLowering::AtomicExpansionKind
12818 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12819   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12820              ? AtomicExpansionKind::NotAtomic
12821              : AtomicExpansionKind::None;
12822 }
12823 
12824 TargetLowering::AtomicExpansionKind
12825 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12826   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12827              ? AtomicExpansionKind::NotAtomic
12828              : AtomicExpansionKind::None;
12829 }
12830 
12831 const TargetRegisterClass *
12832 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12833   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12834   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12835   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12836     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12837                                                : &AMDGPU::SReg_32RegClass;
12838   if (!TRI->isSGPRClass(RC) && !isDivergent)
12839     return TRI->getEquivalentSGPRClass(RC);
12840   else if (TRI->isSGPRClass(RC) && isDivergent)
12841     return TRI->getEquivalentVGPRClass(RC);
12842 
12843   return RC;
12844 }
12845 
12846 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12847 // uniform values (as produced by the mask results of control flow intrinsics)
12848 // used outside of divergent blocks. The phi users need to also be treated as
12849 // always uniform.
12850 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12851                       unsigned WaveSize) {
12852   // FIXME: We assume we never cast the mask results of a control flow
12853   // intrinsic.
12854   // Early exit if the type won't be consistent as a compile time hack.
12855   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12856   if (!IT || IT->getBitWidth() != WaveSize)
12857     return false;
12858 
12859   if (!isa<Instruction>(V))
12860     return false;
12861   if (!Visited.insert(V).second)
12862     return false;
12863   bool Result = false;
12864   for (auto U : V->users()) {
12865     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12866       if (V == U->getOperand(1)) {
12867         switch (Intrinsic->getIntrinsicID()) {
12868         default:
12869           Result = false;
12870           break;
12871         case Intrinsic::amdgcn_if_break:
12872         case Intrinsic::amdgcn_if:
12873         case Intrinsic::amdgcn_else:
12874           Result = true;
12875           break;
12876         }
12877       }
12878       if (V == U->getOperand(0)) {
12879         switch (Intrinsic->getIntrinsicID()) {
12880         default:
12881           Result = false;
12882           break;
12883         case Intrinsic::amdgcn_end_cf:
12884         case Intrinsic::amdgcn_loop:
12885           Result = true;
12886           break;
12887         }
12888       }
12889     } else {
12890       Result = hasCFUser(U, Visited, WaveSize);
12891     }
12892     if (Result)
12893       break;
12894   }
12895   return Result;
12896 }
12897 
12898 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12899                                                const Value *V) const {
12900   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12901     if (CI->isInlineAsm()) {
12902       // FIXME: This cannot give a correct answer. This should only trigger in
12903       // the case where inline asm returns mixed SGPR and VGPR results, used
12904       // outside the defining block. We don't have a specific result to
12905       // consider, so this assumes if any value is SGPR, the overall register
12906       // also needs to be SGPR.
12907       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12908       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12909           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12910       for (auto &TC : TargetConstraints) {
12911         if (TC.Type == InlineAsm::isOutput) {
12912           ComputeConstraintToUse(TC, SDValue());
12913           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12914               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12915           if (RC && SIRI->isSGPRClass(RC))
12916             return true;
12917         }
12918       }
12919     }
12920   }
12921   SmallPtrSet<const Value *, 16> Visited;
12922   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12923 }
12924 
12925 std::pair<InstructionCost, MVT>
12926 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12927                                           Type *Ty) const {
12928   std::pair<InstructionCost, MVT> Cost =
12929       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12930   auto Size = DL.getTypeSizeInBits(Ty);
12931   // Maximum load or store can handle 8 dwords for scalar and 4 for
12932   // vector ALU. Let's assume anything above 8 dwords is expensive
12933   // even if legal.
12934   if (Size <= 256)
12935     return Cost;
12936 
12937   Cost.first += (Size + 255) / 256;
12938   return Cost;
12939 }
12940 
12941 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12942   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12943   for (; I != E; ++I) {
12944     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12945       if (getBasePtrIndex(M) == I.getOperandNo())
12946         return true;
12947     }
12948   }
12949   return false;
12950 }
12951 
12952 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12953                                            SDValue N1) const {
12954   if (!N0.hasOneUse())
12955     return false;
12956   // Take care of the opportunity to keep N0 uniform
12957   if (N0->isDivergent() || !N1->isDivergent())
12958     return true;
12959   // Check if we have a good chance to form the memory access pattern with the
12960   // base and offset
12961   return (DAG.isBaseWithConstantOffset(N0) &&
12962           hasMemSDNodeUser(*N0->use_begin()));
12963 }
12964 
12965 MachineMemOperand::Flags
12966 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12967   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12968   if (I.getMetadata("amdgpu.noclobber"))
12969     return MONoClobber;
12970   return MachineMemOperand::MONone;
12971 }
12972