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   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD,
157                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
158                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
159                       MVT::v32i32},
160                      Custom);
161 
162   setOperationAction(ISD::STORE,
163                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
164                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
165                       MVT::v32i32},
166                      Custom);
167 
168   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
169   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
170   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
171   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
172   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
173   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
174   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
175   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
176   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
177   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
178   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
179   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
180   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
181   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
182   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
183   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
184 
185   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
186   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
187   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
188   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
189   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
190   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
191   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
192 
193   setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
194 
195   setOperationAction(ISD::SELECT, MVT::i1, Promote);
196   setOperationAction(ISD::SELECT, MVT::i64, Custom);
197   setOperationAction(ISD::SELECT, MVT::f64, Promote);
198   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
199 
200   setOperationAction(ISD::SELECT_CC,
201                      {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
202 
203   setOperationAction(ISD::SETCC, MVT::i1, Promote);
204   setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
205   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
206 
207   setOperationAction(ISD::TRUNCATE,
208                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
209                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32},
210                      Expand);
211   setOperationAction(ISD::FP_ROUND,
212                      {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
213                       MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32},
214                      Expand);
215 
216   setOperationAction(ISD::SIGN_EXTEND_INREG,
217                      {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
218                       MVT::v3i16, MVT::v4i16, MVT::Other},
219                      Custom);
220 
221   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222   setOperationAction(ISD::BR_CC,
223                      {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
224 
225   setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
226 
227   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal);
228 
229   setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
230                      Expand);
231 
232 #if 0
233   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i64, Legal);
234 #endif
235 
236   // We only support LOAD/STORE and vector manipulation ops for vectors
237   // with > 4 elements.
238   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
239                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
240                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
241                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
242                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
243                   MVT::v32i32, MVT::v32f32 }) {
244     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245       switch (Op) {
246       case ISD::LOAD:
247       case ISD::STORE:
248       case ISD::BUILD_VECTOR:
249       case ISD::BITCAST:
250       case ISD::EXTRACT_VECTOR_ELT:
251       case ISD::INSERT_VECTOR_ELT:
252       case ISD::EXTRACT_SUBVECTOR:
253       case ISD::SCALAR_TO_VECTOR:
254         break;
255       case ISD::INSERT_SUBVECTOR:
256       case ISD::CONCAT_VECTORS:
257         setOperationAction(Op, VT, Custom);
258         break;
259       default:
260         setOperationAction(Op, VT, Expand);
261         break;
262       }
263     }
264   }
265 
266   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
267 
268   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269   // is expanded to avoid having two separate loops in case the index is a VGPR.
270 
271   // Most operations are naturally 32-bit vector operations. We only support
272   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
276 
277     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
279 
280     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
285   }
286 
287   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
288     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
289     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
290 
291     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
292     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
293 
294     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
295     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
296 
297     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
298     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
299   }
300 
301   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
302     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
303     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
304 
305     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
306     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
307 
308     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
309     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
310 
311     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
312     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
313   }
314 
315   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
316     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
318 
319     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
320     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
321 
322     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
323     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
324 
325     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
327   }
328 
329   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
330     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
332 
333     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
334     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
335 
336     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
337     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
338 
339     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
341   }
342 
343   setOperationAction(ISD::VECTOR_SHUFFLE,
344                      {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
345                      Expand);
346 
347   setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
348 
349   // Avoid stack access for these.
350   // TODO: Generalize to more vector types.
351   setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
352                      {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
353                       MVT::v4i16, MVT::v4f16},
354                      Custom);
355 
356   // Deal with vec3 vector operations when widened to vec4.
357   setOperationAction(ISD::INSERT_SUBVECTOR,
358                      {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
359 
360   // Deal with vec5/6/7 vector operations when widened to vec8.
361   setOperationAction(ISD::INSERT_SUBVECTOR,
362                      {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
363                       MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32},
364                      Custom);
365 
366   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
367   // and output demarshalling
368   setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
369 
370   // We can't return success/failure, only the old value,
371   // let LLVM add the comparison
372   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
373                      Expand);
374 
375   if (Subtarget->hasFlatAddressSpace())
376     setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
377 
378   setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
379 
380   // FIXME: This should be narrowed to i32, but that only happens if i64 is
381   // illegal.
382   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
383   setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
384 
385   // On SI this is s_memtime and s_memrealtime on VI.
386   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
387   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
388 
389   if (Subtarget->has16BitInsts()) {
390     setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
391     setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
392   }
393 
394   if (Subtarget->hasMadMacF32Insts())
395     setOperationAction(ISD::FMAD, MVT::f32, Legal);
396 
397   if (!Subtarget->hasBFI())
398     // fcopysign can be done in a single instruction with BFI.
399     setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
400 
401   if (!Subtarget->hasBCNT(32))
402     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
403 
404   if (!Subtarget->hasBCNT(64))
405     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
406 
407   if (Subtarget->hasFFBH())
408     setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
409 
410   if (Subtarget->hasFFBL())
411     setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
412 
413   // We only really have 32-bit BFE instructions (and 16-bit on VI).
414   //
415   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
416   // effort to match them now. We want this to be false for i64 cases when the
417   // extraction isn't restricted to the upper or lower half. Ideally we would
418   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
419   // span the midpoint are probably relatively rare, so don't worry about them
420   // for now.
421   if (Subtarget->hasBFE())
422     setHasExtractBitsInsn(true);
423 
424   // Clamp modifier on add/sub
425   if (Subtarget->hasIntClamp())
426     setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
427 
428   if (Subtarget->hasAddNoCarry())
429     setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
430                        Legal);
431 
432   setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
433                      Custom);
434 
435   // These are really only legal for ieee_mode functions. We should be avoiding
436   // them for functions that don't have ieee_mode enabled, so just say they are
437   // legal.
438   setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
439                      {MVT::f32, MVT::f64}, Legal);
440 
441   if (Subtarget->haveRoundOpsF64())
442     setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal);
443   else
444     setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR},
445                        MVT::f64, Custom);
446 
447   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
448 
449   setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
450   setOperationAction(ISD::FDIV, MVT::f64, Custom);
451 
452   if (Subtarget->has16BitInsts()) {
453     setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
454                         ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
455                        MVT::i16, Legal);
456 
457     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
458 
459     setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
460                        MVT::i16, Expand);
461 
462     setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
463                         ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
464                         ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
465                         ISD::CTPOP},
466                        MVT::i16, Promote);
467 
468     setOperationAction(ISD::LOAD, MVT::i16, Custom);
469 
470     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
471 
472     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
473     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
474     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
475     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
476 
477     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
478 
479     // F16 - Constant Actions.
480     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
481 
482     // F16 - Load/Store Actions.
483     setOperationAction(ISD::LOAD, MVT::f16, Promote);
484     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
485     setOperationAction(ISD::STORE, MVT::f16, Promote);
486     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
487 
488     // F16 - VOP1 Actions.
489     setOperationAction(
490         {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
491         MVT::f16, Custom);
492 
493     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
494 
495     setOperationAction(
496         {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP},
497         MVT::f16, Promote);
498 
499     // F16 - VOP2 Actions.
500     setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand);
501 
502     setOperationAction(ISD::FDIV, MVT::f16, Custom);
503 
504     // F16 - VOP3 Actions.
505     setOperationAction(ISD::FMA, MVT::f16, Legal);
506     if (STI.hasMadF16())
507       setOperationAction(ISD::FMAD, MVT::f16, Legal);
508 
509     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
510                    MVT::v8f16}) {
511       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
512         switch (Op) {
513         case ISD::LOAD:
514         case ISD::STORE:
515         case ISD::BUILD_VECTOR:
516         case ISD::BITCAST:
517         case ISD::EXTRACT_VECTOR_ELT:
518         case ISD::INSERT_VECTOR_ELT:
519         case ISD::INSERT_SUBVECTOR:
520         case ISD::EXTRACT_SUBVECTOR:
521         case ISD::SCALAR_TO_VECTOR:
522           break;
523         case ISD::CONCAT_VECTORS:
524           setOperationAction(Op, VT, Custom);
525           break;
526         default:
527           setOperationAction(Op, VT, Expand);
528           break;
529         }
530       }
531     }
532 
533     // v_perm_b32 can handle either of these.
534     setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
535     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
536 
537     // XXX - Do these do anything? Vector constants turn into build_vector.
538     setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
539 
540     setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
541 
542     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
543     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
544     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
545     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
546 
547     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
548     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
549     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
550     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
551 
552     setOperationAction(ISD::AND, MVT::v2i16, Promote);
553     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
554     setOperationAction(ISD::OR, MVT::v2i16, Promote);
555     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
556     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
558 
559     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
560     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
561     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
562     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
563 
564     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
565     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
566     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
568 
569     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
570     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
571     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
573 
574     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
575     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
576     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
577     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
578 
579     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
580     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
581     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
582     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
583 
584     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
585                        MVT::v2i32, Expand);
586     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
587 
588     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
589                        MVT::v4i32, Expand);
590 
591     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
592                        MVT::v8i32, Expand);
593 
594     if (!Subtarget->hasVOP3PInsts())
595       setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
596 
597     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
598     // This isn't really legal, but this avoids the legalizer unrolling it (and
599     // allows matching fneg (fabs x) patterns)
600     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
601 
602     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
603     setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
604 
605     setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
606                        {MVT::v4f16, MVT::v8f16}, Custom);
607 
608     setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::v4f16, MVT::v8f16},
609                        Expand);
610 
611     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
612       setOperationAction(
613           {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
614           Vec16, Custom);
615       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
616     }
617   }
618 
619   if (Subtarget->hasVOP3PInsts()) {
620     setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
621                         ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
622                         ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
623                        MVT::v2i16, Legal);
624 
625     setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
626                         ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
627                        MVT::v2f16, Legal);
628 
629     setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
630                        Custom);
631 
632     setOperationAction(ISD::VECTOR_SHUFFLE,
633                        {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16},
634                        Custom);
635 
636     for (MVT VT : {MVT::v4i16, MVT::v8i16})
637       // Split vector operations.
638       setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
639                           ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
640                           ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
641                           ISD::SSUBSAT},
642                          VT, Custom);
643 
644     for (MVT VT : {MVT::v4f16, MVT::v8f16})
645       // Split vector operations.
646       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
647                          VT, Custom);
648 
649     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
650                        Custom);
651 
652     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
653     setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
654 
655     if (Subtarget->hasPackedFP32Ops()) {
656       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
657                          MVT::v2f32, Legal);
658       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
659                          {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
660                          Custom);
661     }
662   }
663 
664   setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
665 
666   if (Subtarget->has16BitInsts()) {
667     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
669     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
670     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
671   } else {
672     // Legalization hack.
673     setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
674 
675     setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
676   }
677 
678   setOperationAction(ISD::SELECT,
679                      {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
680                       MVT::v8i16, MVT::v8f16},
681                      Custom);
682 
683   setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
684 
685   if (Subtarget->hasMad64_32())
686     setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
687 
688   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
689                      {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
690                       MVT::v2i16, MVT::v2f16},
691                      Custom);
692 
693   setOperationAction(ISD::INTRINSIC_W_CHAIN,
694                      {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
695                       MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
696                       MVT::i16, MVT::i8},
697                      Custom);
698 
699   setOperationAction(ISD::INTRINSIC_VOID,
700                      {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
701                       MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
702                       MVT::i8},
703                      Custom);
704 
705   setTargetDAGCombine({ISD::ADD,
706                        ISD::ADDCARRY,
707                        ISD::SUB,
708                        ISD::SUBCARRY,
709                        ISD::FADD,
710                        ISD::FSUB,
711                        ISD::FMINNUM,
712                        ISD::FMAXNUM,
713                        ISD::FMINNUM_IEEE,
714                        ISD::FMAXNUM_IEEE,
715                        ISD::FMA,
716                        ISD::SMIN,
717                        ISD::SMAX,
718                        ISD::UMIN,
719                        ISD::UMAX,
720                        ISD::SETCC,
721                        ISD::AND,
722                        ISD::OR,
723                        ISD::XOR,
724                        ISD::SINT_TO_FP,
725                        ISD::UINT_TO_FP,
726                        ISD::FCANONICALIZE,
727                        ISD::SCALAR_TO_VECTOR,
728                        ISD::ZERO_EXTEND,
729                        ISD::SIGN_EXTEND_INREG,
730                        ISD::EXTRACT_VECTOR_ELT,
731                        ISD::INSERT_VECTOR_ELT});
732 
733   // All memory operations. Some folding on the pointer operand is done to help
734   // matching the constant offsets in the addressing modes.
735   setTargetDAGCombine({ISD::LOAD,
736                        ISD::STORE,
737                        ISD::ATOMIC_LOAD,
738                        ISD::ATOMIC_STORE,
739                        ISD::ATOMIC_CMP_SWAP,
740                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
741                        ISD::ATOMIC_SWAP,
742                        ISD::ATOMIC_LOAD_ADD,
743                        ISD::ATOMIC_LOAD_SUB,
744                        ISD::ATOMIC_LOAD_AND,
745                        ISD::ATOMIC_LOAD_OR,
746                        ISD::ATOMIC_LOAD_XOR,
747                        ISD::ATOMIC_LOAD_NAND,
748                        ISD::ATOMIC_LOAD_MIN,
749                        ISD::ATOMIC_LOAD_MAX,
750                        ISD::ATOMIC_LOAD_UMIN,
751                        ISD::ATOMIC_LOAD_UMAX,
752                        ISD::ATOMIC_LOAD_FADD,
753                        ISD::INTRINSIC_VOID,
754                        ISD::INTRINSIC_W_CHAIN});
755 
756   // FIXME: In other contexts we pretend this is a per-function property.
757   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
758 
759   setSchedulingPreference(Sched::RegPressure);
760 }
761 
762 const GCNSubtarget *SITargetLowering::getSubtarget() const {
763   return Subtarget;
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // TargetLowering queries
768 //===----------------------------------------------------------------------===//
769 
770 // v_mad_mix* support a conversion from f16 to f32.
771 //
772 // There is only one special case when denormals are enabled we don't currently,
773 // where this is OK to use.
774 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
775                                        EVT DestVT, EVT SrcVT) const {
776   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
777           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
778     DestVT.getScalarType() == MVT::f32 &&
779     SrcVT.getScalarType() == MVT::f16 &&
780     // TODO: This probably only requires no input flushing?
781     !hasFP32Denormals(DAG.getMachineFunction());
782 }
783 
784 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
785                                        LLT DestTy, LLT SrcTy) const {
786   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
787           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
788          DestTy.getScalarSizeInBits() == 32 &&
789          SrcTy.getScalarSizeInBits() == 16 &&
790          // TODO: This probably only requires no input flushing?
791          !hasFP32Denormals(*MI.getMF());
792 }
793 
794 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
795   // SI has some legal vector types, but no legal vector operations. Say no
796   // shuffles are legal in order to prefer scalarizing some vector operations.
797   return false;
798 }
799 
800 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
801                                                     CallingConv::ID CC,
802                                                     EVT VT) const {
803   if (CC == CallingConv::AMDGPU_KERNEL)
804     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
805 
806   if (VT.isVector()) {
807     EVT ScalarVT = VT.getScalarType();
808     unsigned Size = ScalarVT.getSizeInBits();
809     if (Size == 16) {
810       if (Subtarget->has16BitInsts())
811         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
812       return VT.isInteger() ? MVT::i32 : MVT::f32;
813     }
814 
815     if (Size < 16)
816       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
817     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
818   }
819 
820   if (VT.getSizeInBits() > 32)
821     return MVT::i32;
822 
823   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
824 }
825 
826 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
827                                                          CallingConv::ID CC,
828                                                          EVT VT) const {
829   if (CC == CallingConv::AMDGPU_KERNEL)
830     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
831 
832   if (VT.isVector()) {
833     unsigned NumElts = VT.getVectorNumElements();
834     EVT ScalarVT = VT.getScalarType();
835     unsigned Size = ScalarVT.getSizeInBits();
836 
837     // FIXME: Should probably promote 8-bit vectors to i16.
838     if (Size == 16 && Subtarget->has16BitInsts())
839       return (NumElts + 1) / 2;
840 
841     if (Size <= 32)
842       return NumElts;
843 
844     if (Size > 32)
845       return NumElts * ((Size + 31) / 32);
846   } else if (VT.getSizeInBits() > 32)
847     return (VT.getSizeInBits() + 31) / 32;
848 
849   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
850 }
851 
852 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
853   LLVMContext &Context, CallingConv::ID CC,
854   EVT VT, EVT &IntermediateVT,
855   unsigned &NumIntermediates, MVT &RegisterVT) const {
856   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
857     unsigned NumElts = VT.getVectorNumElements();
858     EVT ScalarVT = VT.getScalarType();
859     unsigned Size = ScalarVT.getSizeInBits();
860     // FIXME: We should fix the ABI to be the same on targets without 16-bit
861     // support, but unless we can properly handle 3-vectors, it will be still be
862     // inconsistent.
863     if (Size == 16 && Subtarget->has16BitInsts()) {
864       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
865       IntermediateVT = RegisterVT;
866       NumIntermediates = (NumElts + 1) / 2;
867       return NumIntermediates;
868     }
869 
870     if (Size == 32) {
871       RegisterVT = ScalarVT.getSimpleVT();
872       IntermediateVT = RegisterVT;
873       NumIntermediates = NumElts;
874       return NumIntermediates;
875     }
876 
877     if (Size < 16 && Subtarget->has16BitInsts()) {
878       // FIXME: Should probably form v2i16 pieces
879       RegisterVT = MVT::i16;
880       IntermediateVT = ScalarVT;
881       NumIntermediates = NumElts;
882       return NumIntermediates;
883     }
884 
885 
886     if (Size != 16 && Size <= 32) {
887       RegisterVT = MVT::i32;
888       IntermediateVT = ScalarVT;
889       NumIntermediates = NumElts;
890       return NumIntermediates;
891     }
892 
893     if (Size > 32) {
894       RegisterVT = MVT::i32;
895       IntermediateVT = RegisterVT;
896       NumIntermediates = NumElts * ((Size + 31) / 32);
897       return NumIntermediates;
898     }
899   }
900 
901   return TargetLowering::getVectorTypeBreakdownForCallingConv(
902     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
903 }
904 
905 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
906   assert(DMaskLanes != 0);
907 
908   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
909     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
910     return EVT::getVectorVT(Ty->getContext(),
911                             EVT::getEVT(VT->getElementType()),
912                             NumElts);
913   }
914 
915   return EVT::getEVT(Ty);
916 }
917 
918 // Peek through TFE struct returns to only use the data size.
919 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
920   auto *ST = dyn_cast<StructType>(Ty);
921   if (!ST)
922     return memVTFromImageData(Ty, DMaskLanes);
923 
924   // Some intrinsics return an aggregate type - special case to work out the
925   // correct memVT.
926   //
927   // Only limited forms of aggregate type currently expected.
928   if (ST->getNumContainedTypes() != 2 ||
929       !ST->getContainedType(1)->isIntegerTy(32))
930     return EVT();
931   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
932 }
933 
934 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
935                                           const CallInst &CI,
936                                           MachineFunction &MF,
937                                           unsigned IntrID) const {
938   Info.flags = MachineMemOperand::MONone;
939   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
940     Info.flags |= MachineMemOperand::MOInvariant;
941 
942   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
943           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
944     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
945                                                   (Intrinsic::ID)IntrID);
946     if (Attr.hasFnAttr(Attribute::ReadNone))
947       return false;
948 
949     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
950 
951     const GCNTargetMachine &TM =
952         static_cast<const GCNTargetMachine &>(getTargetMachine());
953 
954     if (RsrcIntr->IsImage) {
955       Info.ptrVal = MFI->getImagePSV(TM);
956       Info.align.reset();
957     } else {
958       Info.ptrVal = MFI->getBufferPSV(TM);
959     }
960 
961     Info.flags |= MachineMemOperand::MODereferenceable;
962     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
963       unsigned DMaskLanes = 4;
964 
965       if (RsrcIntr->IsImage) {
966         const AMDGPU::ImageDimIntrinsicInfo *Intr
967           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
968         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
969           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
970 
971         if (!BaseOpcode->Gather4) {
972           // If this isn't a gather, we may have excess loaded elements in the
973           // IR type. Check the dmask for the real number of elements loaded.
974           unsigned DMask
975             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
976           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
977         }
978 
979         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
980       } else
981         Info.memVT = EVT::getEVT(CI.getType());
982 
983       // FIXME: What does alignment mean for an image?
984       Info.opc = ISD::INTRINSIC_W_CHAIN;
985       Info.flags |= MachineMemOperand::MOLoad;
986     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
987       Info.opc = ISD::INTRINSIC_VOID;
988 
989       Type *DataTy = CI.getArgOperand(0)->getType();
990       if (RsrcIntr->IsImage) {
991         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
992         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
993         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
994       } else
995         Info.memVT = EVT::getEVT(DataTy);
996 
997       Info.flags |= MachineMemOperand::MOStore;
998     } else {
999       // Atomic
1000       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1001                                             ISD::INTRINSIC_W_CHAIN;
1002       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1003       Info.flags |= MachineMemOperand::MOLoad |
1004                     MachineMemOperand::MOStore |
1005                     MachineMemOperand::MODereferenceable;
1006 
1007       // XXX - Should this be volatile without known ordering?
1008       Info.flags |= MachineMemOperand::MOVolatile;
1009 
1010       switch (IntrID) {
1011       default:
1012         break;
1013       case Intrinsic::amdgcn_raw_buffer_load_lds:
1014       case Intrinsic::amdgcn_struct_buffer_load_lds: {
1015         unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1016         Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1017         return true;
1018       }
1019       }
1020     }
1021     return true;
1022   }
1023 
1024   switch (IntrID) {
1025   case Intrinsic::amdgcn_atomic_inc:
1026   case Intrinsic::amdgcn_atomic_dec:
1027   case Intrinsic::amdgcn_ds_ordered_add:
1028   case Intrinsic::amdgcn_ds_ordered_swap:
1029   case Intrinsic::amdgcn_ds_fadd:
1030   case Intrinsic::amdgcn_ds_fmin:
1031   case Intrinsic::amdgcn_ds_fmax: {
1032     Info.opc = ISD::INTRINSIC_W_CHAIN;
1033     Info.memVT = MVT::getVT(CI.getType());
1034     Info.ptrVal = CI.getOperand(0);
1035     Info.align.reset();
1036     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1037 
1038     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1039     if (!Vol->isZero())
1040       Info.flags |= MachineMemOperand::MOVolatile;
1041 
1042     return true;
1043   }
1044   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1045     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1046 
1047     const GCNTargetMachine &TM =
1048         static_cast<const GCNTargetMachine &>(getTargetMachine());
1049 
1050     Info.opc = ISD::INTRINSIC_W_CHAIN;
1051     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1052     Info.ptrVal = MFI->getBufferPSV(TM);
1053     Info.align.reset();
1054     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1055 
1056     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1057     if (!Vol || !Vol->isZero())
1058       Info.flags |= MachineMemOperand::MOVolatile;
1059 
1060     return true;
1061   }
1062   case Intrinsic::amdgcn_ds_append:
1063   case Intrinsic::amdgcn_ds_consume: {
1064     Info.opc = ISD::INTRINSIC_W_CHAIN;
1065     Info.memVT = MVT::getVT(CI.getType());
1066     Info.ptrVal = CI.getOperand(0);
1067     Info.align.reset();
1068     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1069 
1070     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1071     if (!Vol->isZero())
1072       Info.flags |= MachineMemOperand::MOVolatile;
1073 
1074     return true;
1075   }
1076   case Intrinsic::amdgcn_global_atomic_csub: {
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 |
1082                   MachineMemOperand::MOStore |
1083                   MachineMemOperand::MOVolatile;
1084     return true;
1085   }
1086   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1087     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1088     Info.opc = ISD::INTRINSIC_W_CHAIN;
1089     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1090 
1091     const GCNTargetMachine &TM =
1092         static_cast<const GCNTargetMachine &>(getTargetMachine());
1093 
1094     Info.ptrVal = MFI->getImagePSV(TM);
1095     Info.align.reset();
1096     Info.flags |= MachineMemOperand::MOLoad |
1097                   MachineMemOperand::MODereferenceable;
1098     return true;
1099   }
1100   case Intrinsic::amdgcn_global_atomic_fadd:
1101   case Intrinsic::amdgcn_global_atomic_fmin:
1102   case Intrinsic::amdgcn_global_atomic_fmax:
1103   case Intrinsic::amdgcn_flat_atomic_fadd:
1104   case Intrinsic::amdgcn_flat_atomic_fmin:
1105   case Intrinsic::amdgcn_flat_atomic_fmax:
1106   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1107   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1108     Info.opc = ISD::INTRINSIC_W_CHAIN;
1109     Info.memVT = MVT::getVT(CI.getType());
1110     Info.ptrVal = CI.getOperand(0);
1111     Info.align.reset();
1112     Info.flags |= MachineMemOperand::MOLoad |
1113                   MachineMemOperand::MOStore |
1114                   MachineMemOperand::MODereferenceable |
1115                   MachineMemOperand::MOVolatile;
1116     return true;
1117   }
1118   case Intrinsic::amdgcn_ds_gws_init:
1119   case Intrinsic::amdgcn_ds_gws_barrier:
1120   case Intrinsic::amdgcn_ds_gws_sema_v:
1121   case Intrinsic::amdgcn_ds_gws_sema_br:
1122   case Intrinsic::amdgcn_ds_gws_sema_p:
1123   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1124     Info.opc = ISD::INTRINSIC_VOID;
1125 
1126     const GCNTargetMachine &TM =
1127         static_cast<const GCNTargetMachine &>(getTargetMachine());
1128 
1129     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1130     Info.ptrVal = MFI->getGWSPSV(TM);
1131 
1132     // This is an abstract access, but we need to specify a type and size.
1133     Info.memVT = MVT::i32;
1134     Info.size = 4;
1135     Info.align = Align(4);
1136 
1137     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1138       Info.flags |= MachineMemOperand::MOLoad;
1139     else
1140       Info.flags |= MachineMemOperand::MOStore;
1141     return true;
1142   }
1143   case Intrinsic::amdgcn_global_load_lds: {
1144     Info.opc = ISD::INTRINSIC_VOID;
1145     unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1146     Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1147     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1148                   MachineMemOperand::MOVolatile;
1149     return true;
1150   }
1151   default:
1152     return false;
1153   }
1154 }
1155 
1156 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1157                                             SmallVectorImpl<Value*> &Ops,
1158                                             Type *&AccessTy) const {
1159   switch (II->getIntrinsicID()) {
1160   case Intrinsic::amdgcn_atomic_inc:
1161   case Intrinsic::amdgcn_atomic_dec:
1162   case Intrinsic::amdgcn_ds_ordered_add:
1163   case Intrinsic::amdgcn_ds_ordered_swap:
1164   case Intrinsic::amdgcn_ds_append:
1165   case Intrinsic::amdgcn_ds_consume:
1166   case Intrinsic::amdgcn_ds_fadd:
1167   case Intrinsic::amdgcn_ds_fmin:
1168   case Intrinsic::amdgcn_ds_fmax:
1169   case Intrinsic::amdgcn_global_atomic_fadd:
1170   case Intrinsic::amdgcn_flat_atomic_fadd:
1171   case Intrinsic::amdgcn_flat_atomic_fmin:
1172   case Intrinsic::amdgcn_flat_atomic_fmax:
1173   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1174   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1175   case Intrinsic::amdgcn_global_atomic_csub: {
1176     Value *Ptr = II->getArgOperand(0);
1177     AccessTy = II->getType();
1178     Ops.push_back(Ptr);
1179     return true;
1180   }
1181   default:
1182     return false;
1183   }
1184 }
1185 
1186 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1187   if (!Subtarget->hasFlatInstOffsets()) {
1188     // Flat instructions do not have offsets, and only have the register
1189     // address.
1190     return AM.BaseOffs == 0 && AM.Scale == 0;
1191   }
1192 
1193   return AM.Scale == 0 &&
1194          (AM.BaseOffs == 0 ||
1195           Subtarget->getInstrInfo()->isLegalFLATOffset(
1196               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1197 }
1198 
1199 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1200   if (Subtarget->hasFlatGlobalInsts())
1201     return AM.Scale == 0 &&
1202            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1203                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1204                                     SIInstrFlags::FlatGlobal));
1205 
1206   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1207       // Assume the we will use FLAT for all global memory accesses
1208       // on VI.
1209       // FIXME: This assumption is currently wrong.  On VI we still use
1210       // MUBUF instructions for the r + i addressing mode.  As currently
1211       // implemented, the MUBUF instructions only work on buffer < 4GB.
1212       // It may be possible to support > 4GB buffers with MUBUF instructions,
1213       // by setting the stride value in the resource descriptor which would
1214       // increase the size limit to (stride * 4GB).  However, this is risky,
1215       // because it has never been validated.
1216     return isLegalFlatAddressingMode(AM);
1217   }
1218 
1219   return isLegalMUBUFAddressingMode(AM);
1220 }
1221 
1222 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1223   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1224   // additionally can do r + r + i with addr64. 32-bit has more addressing
1225   // mode options. Depending on the resource constant, it can also do
1226   // (i64 r0) + (i32 r1) * (i14 i).
1227   //
1228   // Private arrays end up using a scratch buffer most of the time, so also
1229   // assume those use MUBUF instructions. Scratch loads / stores are currently
1230   // implemented as mubuf instructions with offen bit set, so slightly
1231   // different than the normal addr64.
1232   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1233     return false;
1234 
1235   // FIXME: Since we can split immediate into soffset and immediate offset,
1236   // would it make sense to allow any immediate?
1237 
1238   switch (AM.Scale) {
1239   case 0: // r + i or just i, depending on HasBaseReg.
1240     return true;
1241   case 1:
1242     return true; // We have r + r or r + i.
1243   case 2:
1244     if (AM.HasBaseReg) {
1245       // Reject 2 * r + r.
1246       return false;
1247     }
1248 
1249     // Allow 2 * r as r + r
1250     // Or  2 * r + i is allowed as r + r + i.
1251     return true;
1252   default: // Don't allow n * r
1253     return false;
1254   }
1255 }
1256 
1257 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1258                                              const AddrMode &AM, Type *Ty,
1259                                              unsigned AS, Instruction *I) const {
1260   // No global is ever allowed as a base.
1261   if (AM.BaseGV)
1262     return false;
1263 
1264   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1265     return isLegalGlobalAddressingMode(AM);
1266 
1267   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1268       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1269       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1270     // If the offset isn't a multiple of 4, it probably isn't going to be
1271     // correctly aligned.
1272     // FIXME: Can we get the real alignment here?
1273     if (AM.BaseOffs % 4 != 0)
1274       return isLegalMUBUFAddressingMode(AM);
1275 
1276     // There are no SMRD extloads, so if we have to do a small type access we
1277     // will use a MUBUF load.
1278     // FIXME?: We also need to do this if unaligned, but we don't know the
1279     // alignment here.
1280     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1281       return isLegalGlobalAddressingMode(AM);
1282 
1283     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1284       // SMRD instructions have an 8-bit, dword offset on SI.
1285       if (!isUInt<8>(AM.BaseOffs / 4))
1286         return false;
1287     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1288       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1289       // in 8-bits, it can use a smaller encoding.
1290       if (!isUInt<32>(AM.BaseOffs / 4))
1291         return false;
1292     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1293       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1294       if (!isUInt<20>(AM.BaseOffs))
1295         return false;
1296     } else
1297       llvm_unreachable("unhandled generation");
1298 
1299     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1300       return true;
1301 
1302     if (AM.Scale == 1 && AM.HasBaseReg)
1303       return true;
1304 
1305     return false;
1306 
1307   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1308     return isLegalMUBUFAddressingMode(AM);
1309   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1310              AS == AMDGPUAS::REGION_ADDRESS) {
1311     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1312     // field.
1313     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1314     // an 8-bit dword offset but we don't know the alignment here.
1315     if (!isUInt<16>(AM.BaseOffs))
1316       return false;
1317 
1318     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1319       return true;
1320 
1321     if (AM.Scale == 1 && AM.HasBaseReg)
1322       return true;
1323 
1324     return false;
1325   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1326              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1327     // For an unknown address space, this usually means that this is for some
1328     // reason being used for pure arithmetic, and not based on some addressing
1329     // computation. We don't have instructions that compute pointers with any
1330     // addressing modes, so treat them as having no offset like flat
1331     // instructions.
1332     return isLegalFlatAddressingMode(AM);
1333   }
1334 
1335   // Assume a user alias of global for unknown address spaces.
1336   return isLegalGlobalAddressingMode(AM);
1337 }
1338 
1339 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1340                                         const MachineFunction &MF) const {
1341   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1342     return (MemVT.getSizeInBits() <= 4 * 32);
1343   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1344     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1345     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1346   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1347     return (MemVT.getSizeInBits() <= 2 * 32);
1348   }
1349   return true;
1350 }
1351 
1352 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1353     unsigned Size, unsigned AddrSpace, Align Alignment,
1354     MachineMemOperand::Flags Flags, bool *IsFast) const {
1355   if (IsFast)
1356     *IsFast = false;
1357 
1358   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1359       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1360     // Check if alignment requirements for ds_read/write instructions are
1361     // disabled.
1362     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1363       return false;
1364 
1365     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1366     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1367         Alignment < RequiredAlignment)
1368       return false;
1369 
1370     // Either, the alignment requirements are "enabled", or there is an
1371     // unaligned LDS access related hardware bug though alignment requirements
1372     // are "disabled". In either case, we need to check for proper alignment
1373     // requirements.
1374     //
1375     switch (Size) {
1376     case 64:
1377       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1378       // address is negative, then the instruction is incorrectly treated as
1379       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1380       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1381       // load later in the SILoadStoreOptimizer.
1382       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1383         return false;
1384 
1385       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1386       // can do a 4 byte aligned, 8 byte access in a single operation using
1387       // ds_read2/write2_b32 with adjacent offsets.
1388       RequiredAlignment = Align(4);
1389 
1390       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1391         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1392         // ds_write2_b32 depending on the alignment. In either case with either
1393         // alignment there is no faster way of doing this.
1394         if (IsFast)
1395           *IsFast = true;
1396         return true;
1397       }
1398 
1399       break;
1400     case 96:
1401       if (!Subtarget->hasDS96AndDS128())
1402         return false;
1403 
1404       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1405       // gfx8 and older.
1406 
1407       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1408         // Naturally aligned access is fastest. However, also report it is Fast
1409         // if memory is aligned less than DWORD. A narrow load or store will be
1410         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1411         // be more of them, so overall we will pay less penalty issuing a single
1412         // instruction.
1413         if (IsFast)
1414           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1415         return true;
1416       }
1417 
1418       break;
1419     case 128:
1420       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1421         return false;
1422 
1423       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1424       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1425       // single operation using ds_read2/write2_b64.
1426       RequiredAlignment = Align(8);
1427 
1428       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1429         // Naturally aligned access is fastest. However, also report it is Fast
1430         // if memory is aligned less than DWORD. A narrow load or store will be
1431         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1432         // will be more of them, so overall we will pay less penalty issuing a
1433         // single instruction.
1434         if (IsFast)
1435           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1436         return true;
1437       }
1438 
1439       break;
1440     default:
1441       if (Size > 32)
1442         return false;
1443 
1444       break;
1445     }
1446 
1447     if (IsFast)
1448       *IsFast = Alignment >= RequiredAlignment;
1449 
1450     return Alignment >= RequiredAlignment ||
1451            Subtarget->hasUnalignedDSAccessEnabled();
1452   }
1453 
1454   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1455     bool AlignedBy4 = Alignment >= Align(4);
1456     if (IsFast)
1457       *IsFast = AlignedBy4;
1458 
1459     return AlignedBy4 ||
1460            Subtarget->enableFlatScratch() ||
1461            Subtarget->hasUnalignedScratchAccess();
1462   }
1463 
1464   // FIXME: We have to be conservative here and assume that flat operations
1465   // will access scratch.  If we had access to the IR function, then we
1466   // could determine if any private memory was used in the function.
1467   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1468       !Subtarget->hasUnalignedScratchAccess()) {
1469     bool AlignedBy4 = Alignment >= Align(4);
1470     if (IsFast)
1471       *IsFast = AlignedBy4;
1472 
1473     return AlignedBy4;
1474   }
1475 
1476   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1477     // If we have a uniform constant load, it still requires using a slow
1478     // buffer instruction if unaligned.
1479     if (IsFast) {
1480       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1481       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1482       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1483                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1484         Alignment >= Align(4) : Alignment != Align(2);
1485     }
1486 
1487     return true;
1488   }
1489 
1490   // Smaller than dword value must be aligned.
1491   if (Size < 32)
1492     return false;
1493 
1494   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1495   // byte-address are ignored, thus forcing Dword alignment.
1496   // This applies to private, global, and constant memory.
1497   if (IsFast)
1498     *IsFast = true;
1499 
1500   return Size >= 32 && Alignment >= Align(4);
1501 }
1502 
1503 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1504     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1505     bool *IsFast) const {
1506   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1507                                                   Alignment, Flags, IsFast);
1508 
1509   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1510       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1511        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1512     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1513     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1514     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1515     // which would be equally misaligned.
1516     // This is only used by the common passes, selection always calls the
1517     // allowsMisalignedMemoryAccessesImpl version.
1518     *IsFast = true;
1519   }
1520 
1521   return Allow;
1522 }
1523 
1524 EVT SITargetLowering::getOptimalMemOpType(
1525     const MemOp &Op, const AttributeList &FuncAttributes) const {
1526   // FIXME: Should account for address space here.
1527 
1528   // The default fallback uses the private pointer size as a guess for a type to
1529   // use. Make sure we switch these to 64-bit accesses.
1530 
1531   if (Op.size() >= 16 &&
1532       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1533     return MVT::v4i32;
1534 
1535   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1536     return MVT::v2i32;
1537 
1538   // Use the default.
1539   return MVT::Other;
1540 }
1541 
1542 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1543   const MemSDNode *MemNode = cast<MemSDNode>(N);
1544   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1545 }
1546 
1547 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1548   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1549          AS == AMDGPUAS::PRIVATE_ADDRESS;
1550 }
1551 
1552 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1553                                            unsigned DestAS) const {
1554   // Flat -> private/local is a simple truncate.
1555   // Flat -> global is no-op
1556   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1557     return true;
1558 
1559   const GCNTargetMachine &TM =
1560       static_cast<const GCNTargetMachine &>(getTargetMachine());
1561   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1562 }
1563 
1564 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1565   const MemSDNode *MemNode = cast<MemSDNode>(N);
1566 
1567   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1568 }
1569 
1570 TargetLoweringBase::LegalizeTypeAction
1571 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1572   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1573       VT.getScalarType().bitsLE(MVT::i16))
1574     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1575   return TargetLoweringBase::getPreferredVectorAction(VT);
1576 }
1577 
1578 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1579                                                          Type *Ty) const {
1580   // FIXME: Could be smarter if called for vector constants.
1581   return true;
1582 }
1583 
1584 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1585   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1586     switch (Op) {
1587     case ISD::LOAD:
1588     case ISD::STORE:
1589 
1590     // These operations are done with 32-bit instructions anyway.
1591     case ISD::AND:
1592     case ISD::OR:
1593     case ISD::XOR:
1594     case ISD::SELECT:
1595       // TODO: Extensions?
1596       return true;
1597     default:
1598       return false;
1599     }
1600   }
1601 
1602   // SimplifySetCC uses this function to determine whether or not it should
1603   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1604   if (VT == MVT::i1 && Op == ISD::SETCC)
1605     return false;
1606 
1607   return TargetLowering::isTypeDesirableForOp(Op, VT);
1608 }
1609 
1610 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1611                                                    const SDLoc &SL,
1612                                                    SDValue Chain,
1613                                                    uint64_t Offset) const {
1614   const DataLayout &DL = DAG.getDataLayout();
1615   MachineFunction &MF = DAG.getMachineFunction();
1616   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1617 
1618   const ArgDescriptor *InputPtrReg;
1619   const TargetRegisterClass *RC;
1620   LLT ArgTy;
1621   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1622 
1623   std::tie(InputPtrReg, RC, ArgTy) =
1624       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1625 
1626   // We may not have the kernarg segment argument if we have no kernel
1627   // arguments.
1628   if (!InputPtrReg)
1629     return DAG.getConstant(0, SL, PtrVT);
1630 
1631   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1632   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1633     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1634 
1635   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1636 }
1637 
1638 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1639                                             const SDLoc &SL) const {
1640   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1641                                                FIRST_IMPLICIT);
1642   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1643 }
1644 
1645 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1646                                          const SDLoc &SL, SDValue Val,
1647                                          bool Signed,
1648                                          const ISD::InputArg *Arg) const {
1649   // First, if it is a widened vector, narrow it.
1650   if (VT.isVector() &&
1651       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1652     EVT NarrowedVT =
1653         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1654                          VT.getVectorNumElements());
1655     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1656                       DAG.getConstant(0, SL, MVT::i32));
1657   }
1658 
1659   // Then convert the vector elements or scalar value.
1660   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1661       VT.bitsLT(MemVT)) {
1662     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1663     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1664   }
1665 
1666   if (MemVT.isFloatingPoint())
1667     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1668   else if (Signed)
1669     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1670   else
1671     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1672 
1673   return Val;
1674 }
1675 
1676 SDValue SITargetLowering::lowerKernargMemParameter(
1677     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1678     uint64_t Offset, Align Alignment, bool Signed,
1679     const ISD::InputArg *Arg) const {
1680   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1681 
1682   // Try to avoid using an extload by loading earlier than the argument address,
1683   // and extracting the relevant bits. The load should hopefully be merged with
1684   // the previous argument.
1685   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1686     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1687     int64_t AlignDownOffset = alignDown(Offset, 4);
1688     int64_t OffsetDiff = Offset - AlignDownOffset;
1689 
1690     EVT IntVT = MemVT.changeTypeToInteger();
1691 
1692     // TODO: If we passed in the base kernel offset we could have a better
1693     // alignment than 4, but we don't really need it.
1694     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1695     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1696                                MachineMemOperand::MODereferenceable |
1697                                    MachineMemOperand::MOInvariant);
1698 
1699     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1700     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1701 
1702     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1703     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1704     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1705 
1706 
1707     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1708   }
1709 
1710   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1711   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1712                              MachineMemOperand::MODereferenceable |
1713                                  MachineMemOperand::MOInvariant);
1714 
1715   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1716   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1717 }
1718 
1719 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1720                                               const SDLoc &SL, SDValue Chain,
1721                                               const ISD::InputArg &Arg) const {
1722   MachineFunction &MF = DAG.getMachineFunction();
1723   MachineFrameInfo &MFI = MF.getFrameInfo();
1724 
1725   if (Arg.Flags.isByVal()) {
1726     unsigned Size = Arg.Flags.getByValSize();
1727     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1728     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1729   }
1730 
1731   unsigned ArgOffset = VA.getLocMemOffset();
1732   unsigned ArgSize = VA.getValVT().getStoreSize();
1733 
1734   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1735 
1736   // Create load nodes to retrieve arguments from the stack.
1737   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1738   SDValue ArgValue;
1739 
1740   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1741   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1742   MVT MemVT = VA.getValVT();
1743 
1744   switch (VA.getLocInfo()) {
1745   default:
1746     break;
1747   case CCValAssign::BCvt:
1748     MemVT = VA.getLocVT();
1749     break;
1750   case CCValAssign::SExt:
1751     ExtType = ISD::SEXTLOAD;
1752     break;
1753   case CCValAssign::ZExt:
1754     ExtType = ISD::ZEXTLOAD;
1755     break;
1756   case CCValAssign::AExt:
1757     ExtType = ISD::EXTLOAD;
1758     break;
1759   }
1760 
1761   ArgValue = DAG.getExtLoad(
1762     ExtType, SL, VA.getLocVT(), Chain, FIN,
1763     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1764     MemVT);
1765   return ArgValue;
1766 }
1767 
1768 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1769   const SIMachineFunctionInfo &MFI,
1770   EVT VT,
1771   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1772   const ArgDescriptor *Reg;
1773   const TargetRegisterClass *RC;
1774   LLT Ty;
1775 
1776   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1777   if (!Reg) {
1778     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1779       // It's possible for a kernarg intrinsic call to appear in a kernel with
1780       // no allocated segment, in which case we do not add the user sgpr
1781       // argument, so just return null.
1782       return DAG.getConstant(0, SDLoc(), VT);
1783     }
1784 
1785     // It's undefined behavior if a function marked with the amdgpu-no-*
1786     // attributes uses the corresponding intrinsic.
1787     return DAG.getUNDEF(VT);
1788   }
1789 
1790   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1791 }
1792 
1793 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1794                                CallingConv::ID CallConv,
1795                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1796                                FunctionType *FType,
1797                                SIMachineFunctionInfo *Info) {
1798   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1799     const ISD::InputArg *Arg = &Ins[I];
1800 
1801     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1802            "vector type argument should have been split");
1803 
1804     // First check if it's a PS input addr.
1805     if (CallConv == CallingConv::AMDGPU_PS &&
1806         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1807       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1808 
1809       // Inconveniently only the first part of the split is marked as isSplit,
1810       // so skip to the end. We only want to increment PSInputNum once for the
1811       // entire split argument.
1812       if (Arg->Flags.isSplit()) {
1813         while (!Arg->Flags.isSplitEnd()) {
1814           assert((!Arg->VT.isVector() ||
1815                   Arg->VT.getScalarSizeInBits() == 16) &&
1816                  "unexpected vector split in ps argument type");
1817           if (!SkipArg)
1818             Splits.push_back(*Arg);
1819           Arg = &Ins[++I];
1820         }
1821       }
1822 
1823       if (SkipArg) {
1824         // We can safely skip PS inputs.
1825         Skipped.set(Arg->getOrigArgIndex());
1826         ++PSInputNum;
1827         continue;
1828       }
1829 
1830       Info->markPSInputAllocated(PSInputNum);
1831       if (Arg->Used)
1832         Info->markPSInputEnabled(PSInputNum);
1833 
1834       ++PSInputNum;
1835     }
1836 
1837     Splits.push_back(*Arg);
1838   }
1839 }
1840 
1841 // Allocate special inputs passed in VGPRs.
1842 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1843                                                       MachineFunction &MF,
1844                                                       const SIRegisterInfo &TRI,
1845                                                       SIMachineFunctionInfo &Info) const {
1846   const LLT S32 = LLT::scalar(32);
1847   MachineRegisterInfo &MRI = MF.getRegInfo();
1848 
1849   if (Info.hasWorkItemIDX()) {
1850     Register Reg = AMDGPU::VGPR0;
1851     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1852 
1853     CCInfo.AllocateReg(Reg);
1854     unsigned Mask = (Subtarget->hasPackedTID() &&
1855                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1856     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1857   }
1858 
1859   if (Info.hasWorkItemIDY()) {
1860     assert(Info.hasWorkItemIDX());
1861     if (Subtarget->hasPackedTID()) {
1862       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1863                                                         0x3ff << 10));
1864     } else {
1865       unsigned Reg = AMDGPU::VGPR1;
1866       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1867 
1868       CCInfo.AllocateReg(Reg);
1869       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1870     }
1871   }
1872 
1873   if (Info.hasWorkItemIDZ()) {
1874     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1875     if (Subtarget->hasPackedTID()) {
1876       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1877                                                         0x3ff << 20));
1878     } else {
1879       unsigned Reg = AMDGPU::VGPR2;
1880       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1881 
1882       CCInfo.AllocateReg(Reg);
1883       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1884     }
1885   }
1886 }
1887 
1888 // Try to allocate a VGPR at the end of the argument list, or if no argument
1889 // VGPRs are left allocating a stack slot.
1890 // If \p Mask is is given it indicates bitfield position in the register.
1891 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1892 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1893                                          ArgDescriptor Arg = ArgDescriptor()) {
1894   if (Arg.isSet())
1895     return ArgDescriptor::createArg(Arg, Mask);
1896 
1897   ArrayRef<MCPhysReg> ArgVGPRs
1898     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1899   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1900   if (RegIdx == ArgVGPRs.size()) {
1901     // Spill to stack required.
1902     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1903 
1904     return ArgDescriptor::createStack(Offset, Mask);
1905   }
1906 
1907   unsigned Reg = ArgVGPRs[RegIdx];
1908   Reg = CCInfo.AllocateReg(Reg);
1909   assert(Reg != AMDGPU::NoRegister);
1910 
1911   MachineFunction &MF = CCInfo.getMachineFunction();
1912   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1913   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1914   return ArgDescriptor::createRegister(Reg, Mask);
1915 }
1916 
1917 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1918                                              const TargetRegisterClass *RC,
1919                                              unsigned NumArgRegs) {
1920   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1921   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1922   if (RegIdx == ArgSGPRs.size())
1923     report_fatal_error("ran out of SGPRs for arguments");
1924 
1925   unsigned Reg = ArgSGPRs[RegIdx];
1926   Reg = CCInfo.AllocateReg(Reg);
1927   assert(Reg != AMDGPU::NoRegister);
1928 
1929   MachineFunction &MF = CCInfo.getMachineFunction();
1930   MF.addLiveIn(Reg, RC);
1931   return ArgDescriptor::createRegister(Reg);
1932 }
1933 
1934 // If this has a fixed position, we still should allocate the register in the
1935 // CCInfo state. Technically we could get away with this for values passed
1936 // outside of the normal argument range.
1937 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1938                                        const TargetRegisterClass *RC,
1939                                        MCRegister Reg) {
1940   Reg = CCInfo.AllocateReg(Reg);
1941   assert(Reg != AMDGPU::NoRegister);
1942   MachineFunction &MF = CCInfo.getMachineFunction();
1943   MF.addLiveIn(Reg, RC);
1944 }
1945 
1946 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1947   if (Arg) {
1948     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1949                                Arg.getRegister());
1950   } else
1951     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1952 }
1953 
1954 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1955   if (Arg) {
1956     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1957                                Arg.getRegister());
1958   } else
1959     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1960 }
1961 
1962 /// Allocate implicit function VGPR arguments at the end of allocated user
1963 /// arguments.
1964 void SITargetLowering::allocateSpecialInputVGPRs(
1965   CCState &CCInfo, MachineFunction &MF,
1966   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1967   const unsigned Mask = 0x3ff;
1968   ArgDescriptor Arg;
1969 
1970   if (Info.hasWorkItemIDX()) {
1971     Arg = allocateVGPR32Input(CCInfo, Mask);
1972     Info.setWorkItemIDX(Arg);
1973   }
1974 
1975   if (Info.hasWorkItemIDY()) {
1976     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1977     Info.setWorkItemIDY(Arg);
1978   }
1979 
1980   if (Info.hasWorkItemIDZ())
1981     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1982 }
1983 
1984 /// Allocate implicit function VGPR arguments in fixed registers.
1985 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1986   CCState &CCInfo, MachineFunction &MF,
1987   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1988   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1989   if (!Reg)
1990     report_fatal_error("failed to allocated VGPR for implicit arguments");
1991 
1992   const unsigned Mask = 0x3ff;
1993   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1994   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1995   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1996 }
1997 
1998 void SITargetLowering::allocateSpecialInputSGPRs(
1999   CCState &CCInfo,
2000   MachineFunction &MF,
2001   const SIRegisterInfo &TRI,
2002   SIMachineFunctionInfo &Info) const {
2003   auto &ArgInfo = Info.getArgInfo();
2004 
2005   // TODO: Unify handling with private memory pointers.
2006   if (Info.hasDispatchPtr())
2007     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2008 
2009   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2010     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2011 
2012   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2013   // constant offset from the kernarg segment.
2014   if (Info.hasImplicitArgPtr())
2015     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2016 
2017   if (Info.hasDispatchID())
2018     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2019 
2020   // flat_scratch_init is not applicable for non-kernel functions.
2021 
2022   if (Info.hasWorkGroupIDX())
2023     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2024 
2025   if (Info.hasWorkGroupIDY())
2026     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2027 
2028   if (Info.hasWorkGroupIDZ())
2029     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2030 }
2031 
2032 // Allocate special inputs passed in user SGPRs.
2033 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2034                                             MachineFunction &MF,
2035                                             const SIRegisterInfo &TRI,
2036                                             SIMachineFunctionInfo &Info) const {
2037   if (Info.hasImplicitBufferPtr()) {
2038     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2039     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2040     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2041   }
2042 
2043   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2044   if (Info.hasPrivateSegmentBuffer()) {
2045     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2046     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2047     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2048   }
2049 
2050   if (Info.hasDispatchPtr()) {
2051     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2052     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2053     CCInfo.AllocateReg(DispatchPtrReg);
2054   }
2055 
2056   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2057     Register QueuePtrReg = Info.addQueuePtr(TRI);
2058     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2059     CCInfo.AllocateReg(QueuePtrReg);
2060   }
2061 
2062   if (Info.hasKernargSegmentPtr()) {
2063     MachineRegisterInfo &MRI = MF.getRegInfo();
2064     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2065     CCInfo.AllocateReg(InputPtrReg);
2066 
2067     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2068     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2069   }
2070 
2071   if (Info.hasDispatchID()) {
2072     Register DispatchIDReg = Info.addDispatchID(TRI);
2073     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2074     CCInfo.AllocateReg(DispatchIDReg);
2075   }
2076 
2077   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2078     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2079     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2080     CCInfo.AllocateReg(FlatScratchInitReg);
2081   }
2082 
2083   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2084   // these from the dispatch pointer.
2085 }
2086 
2087 // Allocate special input registers that are initialized per-wave.
2088 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2089                                            MachineFunction &MF,
2090                                            SIMachineFunctionInfo &Info,
2091                                            CallingConv::ID CallConv,
2092                                            bool IsShader) const {
2093   if (Info.hasWorkGroupIDX()) {
2094     Register Reg = Info.addWorkGroupIDX();
2095     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2096     CCInfo.AllocateReg(Reg);
2097   }
2098 
2099   if (Info.hasWorkGroupIDY()) {
2100     Register Reg = Info.addWorkGroupIDY();
2101     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2102     CCInfo.AllocateReg(Reg);
2103   }
2104 
2105   if (Info.hasWorkGroupIDZ()) {
2106     Register Reg = Info.addWorkGroupIDZ();
2107     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2108     CCInfo.AllocateReg(Reg);
2109   }
2110 
2111   if (Info.hasWorkGroupInfo()) {
2112     Register Reg = Info.addWorkGroupInfo();
2113     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2114     CCInfo.AllocateReg(Reg);
2115   }
2116 
2117   if (Info.hasPrivateSegmentWaveByteOffset()) {
2118     // Scratch wave offset passed in system SGPR.
2119     unsigned PrivateSegmentWaveByteOffsetReg;
2120 
2121     if (IsShader) {
2122       PrivateSegmentWaveByteOffsetReg =
2123         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2124 
2125       // This is true if the scratch wave byte offset doesn't have a fixed
2126       // location.
2127       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2128         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2129         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2130       }
2131     } else
2132       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2133 
2134     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2135     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2136   }
2137 }
2138 
2139 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2140                                      MachineFunction &MF,
2141                                      const SIRegisterInfo &TRI,
2142                                      SIMachineFunctionInfo &Info) {
2143   // Now that we've figured out where the scratch register inputs are, see if
2144   // should reserve the arguments and use them directly.
2145   MachineFrameInfo &MFI = MF.getFrameInfo();
2146   bool HasStackObjects = MFI.hasStackObjects();
2147   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2148 
2149   // Record that we know we have non-spill stack objects so we don't need to
2150   // check all stack objects later.
2151   if (HasStackObjects)
2152     Info.setHasNonSpillStackObjects(true);
2153 
2154   // Everything live out of a block is spilled with fast regalloc, so it's
2155   // almost certain that spilling will be required.
2156   if (TM.getOptLevel() == CodeGenOpt::None)
2157     HasStackObjects = true;
2158 
2159   // For now assume stack access is needed in any callee functions, so we need
2160   // the scratch registers to pass in.
2161   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2162 
2163   if (!ST.enableFlatScratch()) {
2164     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2165       // If we have stack objects, we unquestionably need the private buffer
2166       // resource. For the Code Object V2 ABI, this will be the first 4 user
2167       // SGPR inputs. We can reserve those and use them directly.
2168 
2169       Register PrivateSegmentBufferReg =
2170           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2171       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2172     } else {
2173       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2174       // We tentatively reserve the last registers (skipping the last registers
2175       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2176       // we'll replace these with the ones immediately after those which were
2177       // really allocated. In the prologue copies will be inserted from the
2178       // argument to these reserved registers.
2179 
2180       // Without HSA, relocations are used for the scratch pointer and the
2181       // buffer resource setup is always inserted in the prologue. Scratch wave
2182       // offset is still in an input SGPR.
2183       Info.setScratchRSrcReg(ReservedBufferReg);
2184     }
2185   }
2186 
2187   MachineRegisterInfo &MRI = MF.getRegInfo();
2188 
2189   // For entry functions we have to set up the stack pointer if we use it,
2190   // whereas non-entry functions get this "for free". This means there is no
2191   // intrinsic advantage to using S32 over S34 in cases where we do not have
2192   // calls but do need a frame pointer (i.e. if we are requested to have one
2193   // because frame pointer elimination is disabled). To keep things simple we
2194   // only ever use S32 as the call ABI stack pointer, and so using it does not
2195   // imply we need a separate frame pointer.
2196   //
2197   // Try to use s32 as the SP, but move it if it would interfere with input
2198   // arguments. This won't work with calls though.
2199   //
2200   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2201   // registers.
2202   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2203     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2204   } else {
2205     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2206 
2207     if (MFI.hasCalls())
2208       report_fatal_error("call in graphics shader with too many input SGPRs");
2209 
2210     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2211       if (!MRI.isLiveIn(Reg)) {
2212         Info.setStackPtrOffsetReg(Reg);
2213         break;
2214       }
2215     }
2216 
2217     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2218       report_fatal_error("failed to find register for SP");
2219   }
2220 
2221   // hasFP should be accurate for entry functions even before the frame is
2222   // finalized, because it does not rely on the known stack size, only
2223   // properties like whether variable sized objects are present.
2224   if (ST.getFrameLowering()->hasFP(MF)) {
2225     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2226   }
2227 }
2228 
2229 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2230   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2231   return !Info->isEntryFunction();
2232 }
2233 
2234 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2235 
2236 }
2237 
2238 void SITargetLowering::insertCopiesSplitCSR(
2239   MachineBasicBlock *Entry,
2240   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2241   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2242 
2243   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2244   if (!IStart)
2245     return;
2246 
2247   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2248   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2249   MachineBasicBlock::iterator MBBI = Entry->begin();
2250   for (const MCPhysReg *I = IStart; *I; ++I) {
2251     const TargetRegisterClass *RC = nullptr;
2252     if (AMDGPU::SReg_64RegClass.contains(*I))
2253       RC = &AMDGPU::SGPR_64RegClass;
2254     else if (AMDGPU::SReg_32RegClass.contains(*I))
2255       RC = &AMDGPU::SGPR_32RegClass;
2256     else
2257       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2258 
2259     Register NewVR = MRI->createVirtualRegister(RC);
2260     // Create copy from CSR to a virtual register.
2261     Entry->addLiveIn(*I);
2262     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2263       .addReg(*I);
2264 
2265     // Insert the copy-back instructions right before the terminator.
2266     for (auto *Exit : Exits)
2267       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2268               TII->get(TargetOpcode::COPY), *I)
2269         .addReg(NewVR);
2270   }
2271 }
2272 
2273 SDValue SITargetLowering::LowerFormalArguments(
2274     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2275     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2276     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2277   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2278 
2279   MachineFunction &MF = DAG.getMachineFunction();
2280   const Function &Fn = MF.getFunction();
2281   FunctionType *FType = MF.getFunction().getFunctionType();
2282   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2283 
2284   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2285     DiagnosticInfoUnsupported NoGraphicsHSA(
2286         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2287     DAG.getContext()->diagnose(NoGraphicsHSA);
2288     return DAG.getEntryNode();
2289   }
2290 
2291   Info->allocateModuleLDSGlobal(Fn);
2292 
2293   SmallVector<ISD::InputArg, 16> Splits;
2294   SmallVector<CCValAssign, 16> ArgLocs;
2295   BitVector Skipped(Ins.size());
2296   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2297                  *DAG.getContext());
2298 
2299   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2300   bool IsKernel = AMDGPU::isKernel(CallConv);
2301   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2302 
2303   if (IsGraphics) {
2304     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2305            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2306            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2307            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2308            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2309            !Info->hasWorkItemIDZ());
2310   }
2311 
2312   if (CallConv == CallingConv::AMDGPU_PS) {
2313     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2314 
2315     // At least one interpolation mode must be enabled or else the GPU will
2316     // hang.
2317     //
2318     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2319     // set PSInputAddr, the user wants to enable some bits after the compilation
2320     // based on run-time states. Since we can't know what the final PSInputEna
2321     // will look like, so we shouldn't do anything here and the user should take
2322     // responsibility for the correct programming.
2323     //
2324     // Otherwise, the following restrictions apply:
2325     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2326     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2327     //   enabled too.
2328     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2329         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2330       CCInfo.AllocateReg(AMDGPU::VGPR0);
2331       CCInfo.AllocateReg(AMDGPU::VGPR1);
2332       Info->markPSInputAllocated(0);
2333       Info->markPSInputEnabled(0);
2334     }
2335     if (Subtarget->isAmdPalOS()) {
2336       // For isAmdPalOS, the user does not enable some bits after compilation
2337       // based on run-time states; the register values being generated here are
2338       // the final ones set in hardware. Therefore we need to apply the
2339       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2340       // a bit is set in PSInputAddr but not PSInputEnable is where the
2341       // frontend set up an input arg for a particular interpolation mode, but
2342       // nothing uses that input arg. Really we should have an earlier pass
2343       // that removes such an arg.)
2344       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2345       if ((PsInputBits & 0x7F) == 0 ||
2346           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2347         Info->markPSInputEnabled(
2348             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2349     }
2350   } else if (IsKernel) {
2351     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2352   } else {
2353     Splits.append(Ins.begin(), Ins.end());
2354   }
2355 
2356   if (IsEntryFunc) {
2357     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2358     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2359   } else if (!IsGraphics) {
2360     // For the fixed ABI, pass workitem IDs in the last argument register.
2361     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2362   }
2363 
2364   if (IsKernel) {
2365     analyzeFormalArgumentsCompute(CCInfo, Ins);
2366   } else {
2367     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2368     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2369   }
2370 
2371   SmallVector<SDValue, 16> Chains;
2372 
2373   // FIXME: This is the minimum kernel argument alignment. We should improve
2374   // this to the maximum alignment of the arguments.
2375   //
2376   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2377   // kern arg offset.
2378   const Align KernelArgBaseAlign = Align(16);
2379 
2380   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2381     const ISD::InputArg &Arg = Ins[i];
2382     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2383       InVals.push_back(DAG.getUNDEF(Arg.VT));
2384       continue;
2385     }
2386 
2387     CCValAssign &VA = ArgLocs[ArgIdx++];
2388     MVT VT = VA.getLocVT();
2389 
2390     if (IsEntryFunc && VA.isMemLoc()) {
2391       VT = Ins[i].VT;
2392       EVT MemVT = VA.getLocVT();
2393 
2394       const uint64_t Offset = VA.getLocMemOffset();
2395       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2396 
2397       if (Arg.Flags.isByRef()) {
2398         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2399 
2400         const GCNTargetMachine &TM =
2401             static_cast<const GCNTargetMachine &>(getTargetMachine());
2402         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2403                                     Arg.Flags.getPointerAddrSpace())) {
2404           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2405                                      Arg.Flags.getPointerAddrSpace());
2406         }
2407 
2408         InVals.push_back(Ptr);
2409         continue;
2410       }
2411 
2412       SDValue Arg = lowerKernargMemParameter(
2413         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2414       Chains.push_back(Arg.getValue(1));
2415 
2416       auto *ParamTy =
2417         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2418       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2419           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2420                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2421         // On SI local pointers are just offsets into LDS, so they are always
2422         // less than 16-bits.  On CI and newer they could potentially be
2423         // real pointers, so we can't guarantee their size.
2424         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2425                           DAG.getValueType(MVT::i16));
2426       }
2427 
2428       InVals.push_back(Arg);
2429       continue;
2430     } else if (!IsEntryFunc && VA.isMemLoc()) {
2431       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2432       InVals.push_back(Val);
2433       if (!Arg.Flags.isByVal())
2434         Chains.push_back(Val.getValue(1));
2435       continue;
2436     }
2437 
2438     assert(VA.isRegLoc() && "Parameter must be in a register!");
2439 
2440     Register Reg = VA.getLocReg();
2441     const TargetRegisterClass *RC = nullptr;
2442     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2443       RC = &AMDGPU::VGPR_32RegClass;
2444     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2445       RC = &AMDGPU::SGPR_32RegClass;
2446     else
2447       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2448     EVT ValVT = VA.getValVT();
2449 
2450     Reg = MF.addLiveIn(Reg, RC);
2451     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2452 
2453     if (Arg.Flags.isSRet()) {
2454       // The return object should be reasonably addressable.
2455 
2456       // FIXME: This helps when the return is a real sret. If it is a
2457       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2458       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2459       unsigned NumBits
2460         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2461       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2462         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2463     }
2464 
2465     // If this is an 8 or 16-bit value, it is really passed promoted
2466     // to 32 bits. Insert an assert[sz]ext to capture this, then
2467     // truncate to the right size.
2468     switch (VA.getLocInfo()) {
2469     case CCValAssign::Full:
2470       break;
2471     case CCValAssign::BCvt:
2472       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2473       break;
2474     case CCValAssign::SExt:
2475       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2476                         DAG.getValueType(ValVT));
2477       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2478       break;
2479     case CCValAssign::ZExt:
2480       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2481                         DAG.getValueType(ValVT));
2482       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2483       break;
2484     case CCValAssign::AExt:
2485       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2486       break;
2487     default:
2488       llvm_unreachable("Unknown loc info!");
2489     }
2490 
2491     InVals.push_back(Val);
2492   }
2493 
2494   // Start adding system SGPRs.
2495   if (IsEntryFunc) {
2496     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2497   } else {
2498     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2499     if (!IsGraphics)
2500       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2501   }
2502 
2503   auto &ArgUsageInfo =
2504     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2505   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2506 
2507   unsigned StackArgSize = CCInfo.getNextStackOffset();
2508   Info->setBytesInStackArgArea(StackArgSize);
2509 
2510   return Chains.empty() ? Chain :
2511     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2512 }
2513 
2514 // TODO: If return values can't fit in registers, we should return as many as
2515 // possible in registers before passing on stack.
2516 bool SITargetLowering::CanLowerReturn(
2517   CallingConv::ID CallConv,
2518   MachineFunction &MF, bool IsVarArg,
2519   const SmallVectorImpl<ISD::OutputArg> &Outs,
2520   LLVMContext &Context) const {
2521   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2522   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2523   // for shaders. Vector types should be explicitly handled by CC.
2524   if (AMDGPU::isEntryFunctionCC(CallConv))
2525     return true;
2526 
2527   SmallVector<CCValAssign, 16> RVLocs;
2528   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2529   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2530 }
2531 
2532 SDValue
2533 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2534                               bool isVarArg,
2535                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2536                               const SmallVectorImpl<SDValue> &OutVals,
2537                               const SDLoc &DL, SelectionDAG &DAG) const {
2538   MachineFunction &MF = DAG.getMachineFunction();
2539   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2540 
2541   if (AMDGPU::isKernel(CallConv)) {
2542     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2543                                              OutVals, DL, DAG);
2544   }
2545 
2546   bool IsShader = AMDGPU::isShader(CallConv);
2547 
2548   Info->setIfReturnsVoid(Outs.empty());
2549   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2550 
2551   // CCValAssign - represent the assignment of the return value to a location.
2552   SmallVector<CCValAssign, 48> RVLocs;
2553   SmallVector<ISD::OutputArg, 48> Splits;
2554 
2555   // CCState - Info about the registers and stack slots.
2556   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2557                  *DAG.getContext());
2558 
2559   // Analyze outgoing return values.
2560   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2561 
2562   SDValue Flag;
2563   SmallVector<SDValue, 48> RetOps;
2564   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2565 
2566   // Copy the result values into the output registers.
2567   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2568        ++I, ++RealRVLocIdx) {
2569     CCValAssign &VA = RVLocs[I];
2570     assert(VA.isRegLoc() && "Can only return in registers!");
2571     // TODO: Partially return in registers if return values don't fit.
2572     SDValue Arg = OutVals[RealRVLocIdx];
2573 
2574     // Copied from other backends.
2575     switch (VA.getLocInfo()) {
2576     case CCValAssign::Full:
2577       break;
2578     case CCValAssign::BCvt:
2579       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2580       break;
2581     case CCValAssign::SExt:
2582       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2583       break;
2584     case CCValAssign::ZExt:
2585       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2586       break;
2587     case CCValAssign::AExt:
2588       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2589       break;
2590     default:
2591       llvm_unreachable("Unknown loc info!");
2592     }
2593 
2594     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2595     Flag = Chain.getValue(1);
2596     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2597   }
2598 
2599   // FIXME: Does sret work properly?
2600   if (!Info->isEntryFunction()) {
2601     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2602     const MCPhysReg *I =
2603       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2604     if (I) {
2605       for (; *I; ++I) {
2606         if (AMDGPU::SReg_64RegClass.contains(*I))
2607           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2608         else if (AMDGPU::SReg_32RegClass.contains(*I))
2609           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2610         else
2611           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2612       }
2613     }
2614   }
2615 
2616   // Update chain and glue.
2617   RetOps[0] = Chain;
2618   if (Flag.getNode())
2619     RetOps.push_back(Flag);
2620 
2621   unsigned Opc = AMDGPUISD::ENDPGM;
2622   if (!IsWaveEnd)
2623     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2624   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2625 }
2626 
2627 SDValue SITargetLowering::LowerCallResult(
2628     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2629     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2630     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2631     SDValue ThisVal) const {
2632   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2633 
2634   // Assign locations to each value returned by this call.
2635   SmallVector<CCValAssign, 16> RVLocs;
2636   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2637                  *DAG.getContext());
2638   CCInfo.AnalyzeCallResult(Ins, RetCC);
2639 
2640   // Copy all of the result registers out of their specified physreg.
2641   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2642     CCValAssign VA = RVLocs[i];
2643     SDValue Val;
2644 
2645     if (VA.isRegLoc()) {
2646       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2647       Chain = Val.getValue(1);
2648       InFlag = Val.getValue(2);
2649     } else if (VA.isMemLoc()) {
2650       report_fatal_error("TODO: return values in memory");
2651     } else
2652       llvm_unreachable("unknown argument location type");
2653 
2654     switch (VA.getLocInfo()) {
2655     case CCValAssign::Full:
2656       break;
2657     case CCValAssign::BCvt:
2658       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2659       break;
2660     case CCValAssign::ZExt:
2661       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2662                         DAG.getValueType(VA.getValVT()));
2663       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2664       break;
2665     case CCValAssign::SExt:
2666       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2667                         DAG.getValueType(VA.getValVT()));
2668       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2669       break;
2670     case CCValAssign::AExt:
2671       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2672       break;
2673     default:
2674       llvm_unreachable("Unknown loc info!");
2675     }
2676 
2677     InVals.push_back(Val);
2678   }
2679 
2680   return Chain;
2681 }
2682 
2683 // Add code to pass special inputs required depending on used features separate
2684 // from the explicit user arguments present in the IR.
2685 void SITargetLowering::passSpecialInputs(
2686     CallLoweringInfo &CLI,
2687     CCState &CCInfo,
2688     const SIMachineFunctionInfo &Info,
2689     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2690     SmallVectorImpl<SDValue> &MemOpChains,
2691     SDValue Chain) const {
2692   // If we don't have a call site, this was a call inserted by
2693   // legalization. These can never use special inputs.
2694   if (!CLI.CB)
2695     return;
2696 
2697   SelectionDAG &DAG = CLI.DAG;
2698   const SDLoc &DL = CLI.DL;
2699   const Function &F = DAG.getMachineFunction().getFunction();
2700 
2701   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2702   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2703 
2704   const AMDGPUFunctionArgInfo *CalleeArgInfo
2705     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2706   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2707     auto &ArgUsageInfo =
2708       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2709     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2710   }
2711 
2712   // TODO: Unify with private memory register handling. This is complicated by
2713   // the fact that at least in kernels, the input argument is not necessarily
2714   // in the same location as the input.
2715   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2716                              StringLiteral> ImplicitAttrs[] = {
2717     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2718     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2719     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2720     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2721     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2722     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2723     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2724   };
2725 
2726   for (auto Attr : ImplicitAttrs) {
2727     const ArgDescriptor *OutgoingArg;
2728     const TargetRegisterClass *ArgRC;
2729     LLT ArgTy;
2730 
2731     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2732 
2733     // If the callee does not use the attribute value, skip copying the value.
2734     if (CLI.CB->hasFnAttr(Attr.second))
2735       continue;
2736 
2737     std::tie(OutgoingArg, ArgRC, ArgTy) =
2738         CalleeArgInfo->getPreloadedValue(InputID);
2739     if (!OutgoingArg)
2740       continue;
2741 
2742     const ArgDescriptor *IncomingArg;
2743     const TargetRegisterClass *IncomingArgRC;
2744     LLT Ty;
2745     std::tie(IncomingArg, IncomingArgRC, Ty) =
2746         CallerArgInfo.getPreloadedValue(InputID);
2747     assert(IncomingArgRC == ArgRC);
2748 
2749     // All special arguments are ints for now.
2750     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2751     SDValue InputReg;
2752 
2753     if (IncomingArg) {
2754       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2755     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2756       // The implicit arg ptr is special because it doesn't have a corresponding
2757       // input for kernels, and is computed from the kernarg segment pointer.
2758       InputReg = getImplicitArgPtr(DAG, DL);
2759     } else {
2760       // We may have proven the input wasn't needed, although the ABI is
2761       // requiring it. We just need to allocate the register appropriately.
2762       InputReg = DAG.getUNDEF(ArgVT);
2763     }
2764 
2765     if (OutgoingArg->isRegister()) {
2766       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2767       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2768         report_fatal_error("failed to allocate implicit input argument");
2769     } else {
2770       unsigned SpecialArgOffset =
2771           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2772       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2773                                               SpecialArgOffset);
2774       MemOpChains.push_back(ArgStore);
2775     }
2776   }
2777 
2778   // Pack workitem IDs into a single register or pass it as is if already
2779   // packed.
2780   const ArgDescriptor *OutgoingArg;
2781   const TargetRegisterClass *ArgRC;
2782   LLT Ty;
2783 
2784   std::tie(OutgoingArg, ArgRC, Ty) =
2785       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2786   if (!OutgoingArg)
2787     std::tie(OutgoingArg, ArgRC, Ty) =
2788         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2789   if (!OutgoingArg)
2790     std::tie(OutgoingArg, ArgRC, Ty) =
2791         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2792   if (!OutgoingArg)
2793     return;
2794 
2795   const ArgDescriptor *IncomingArgX = std::get<0>(
2796       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2797   const ArgDescriptor *IncomingArgY = std::get<0>(
2798       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2799   const ArgDescriptor *IncomingArgZ = std::get<0>(
2800       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2801 
2802   SDValue InputReg;
2803   SDLoc SL;
2804 
2805   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2806   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2807   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2808 
2809   // If incoming ids are not packed we need to pack them.
2810   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2811       NeedWorkItemIDX) {
2812     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2813       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2814     } else {
2815       InputReg = DAG.getConstant(0, DL, MVT::i32);
2816     }
2817   }
2818 
2819   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2820       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2821     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2822     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2823                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2824     InputReg = InputReg.getNode() ?
2825                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2826   }
2827 
2828   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2829       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2830     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2831     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2832                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2833     InputReg = InputReg.getNode() ?
2834                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2835   }
2836 
2837   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2838     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2839       // We're in a situation where the outgoing function requires the workitem
2840       // ID, but the calling function does not have it (e.g a graphics function
2841       // calling a C calling convention function). This is illegal, but we need
2842       // to produce something.
2843       InputReg = DAG.getUNDEF(MVT::i32);
2844     } else {
2845       // Workitem ids are already packed, any of present incoming arguments
2846       // will carry all required fields.
2847       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2848         IncomingArgX ? *IncomingArgX :
2849         IncomingArgY ? *IncomingArgY :
2850         *IncomingArgZ, ~0u);
2851       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2852     }
2853   }
2854 
2855   if (OutgoingArg->isRegister()) {
2856     if (InputReg)
2857       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2858 
2859     CCInfo.AllocateReg(OutgoingArg->getRegister());
2860   } else {
2861     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2862     if (InputReg) {
2863       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2864                                               SpecialArgOffset);
2865       MemOpChains.push_back(ArgStore);
2866     }
2867   }
2868 }
2869 
2870 static bool canGuaranteeTCO(CallingConv::ID CC) {
2871   return CC == CallingConv::Fast;
2872 }
2873 
2874 /// Return true if we might ever do TCO for calls with this calling convention.
2875 static bool mayTailCallThisCC(CallingConv::ID CC) {
2876   switch (CC) {
2877   case CallingConv::C:
2878   case CallingConv::AMDGPU_Gfx:
2879     return true;
2880   default:
2881     return canGuaranteeTCO(CC);
2882   }
2883 }
2884 
2885 bool SITargetLowering::isEligibleForTailCallOptimization(
2886     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2887     const SmallVectorImpl<ISD::OutputArg> &Outs,
2888     const SmallVectorImpl<SDValue> &OutVals,
2889     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2890   if (!mayTailCallThisCC(CalleeCC))
2891     return false;
2892 
2893   // For a divergent call target, we need to do a waterfall loop over the
2894   // possible callees which precludes us from using a simple jump.
2895   if (Callee->isDivergent())
2896     return false;
2897 
2898   MachineFunction &MF = DAG.getMachineFunction();
2899   const Function &CallerF = MF.getFunction();
2900   CallingConv::ID CallerCC = CallerF.getCallingConv();
2901   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2902   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2903 
2904   // Kernels aren't callable, and don't have a live in return address so it
2905   // doesn't make sense to do a tail call with entry functions.
2906   if (!CallerPreserved)
2907     return false;
2908 
2909   bool CCMatch = CallerCC == CalleeCC;
2910 
2911   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2912     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2913       return true;
2914     return false;
2915   }
2916 
2917   // TODO: Can we handle var args?
2918   if (IsVarArg)
2919     return false;
2920 
2921   for (const Argument &Arg : CallerF.args()) {
2922     if (Arg.hasByValAttr())
2923       return false;
2924   }
2925 
2926   LLVMContext &Ctx = *DAG.getContext();
2927 
2928   // Check that the call results are passed in the same way.
2929   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2930                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2931                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2932     return false;
2933 
2934   // The callee has to preserve all registers the caller needs to preserve.
2935   if (!CCMatch) {
2936     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2937     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2938       return false;
2939   }
2940 
2941   // Nothing more to check if the callee is taking no arguments.
2942   if (Outs.empty())
2943     return true;
2944 
2945   SmallVector<CCValAssign, 16> ArgLocs;
2946   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2947 
2948   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2949 
2950   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2951   // If the stack arguments for this call do not fit into our own save area then
2952   // the call cannot be made tail.
2953   // TODO: Is this really necessary?
2954   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2955     return false;
2956 
2957   const MachineRegisterInfo &MRI = MF.getRegInfo();
2958   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2959 }
2960 
2961 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2962   if (!CI->isTailCall())
2963     return false;
2964 
2965   const Function *ParentFn = CI->getParent()->getParent();
2966   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2967     return false;
2968   return true;
2969 }
2970 
2971 // The wave scratch offset register is used as the global base pointer.
2972 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2973                                     SmallVectorImpl<SDValue> &InVals) const {
2974   SelectionDAG &DAG = CLI.DAG;
2975   const SDLoc &DL = CLI.DL;
2976   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2977   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2978   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2979   SDValue Chain = CLI.Chain;
2980   SDValue Callee = CLI.Callee;
2981   bool &IsTailCall = CLI.IsTailCall;
2982   CallingConv::ID CallConv = CLI.CallConv;
2983   bool IsVarArg = CLI.IsVarArg;
2984   bool IsSibCall = false;
2985   bool IsThisReturn = false;
2986   MachineFunction &MF = DAG.getMachineFunction();
2987 
2988   if (Callee.isUndef() || isNullConstant(Callee)) {
2989     if (!CLI.IsTailCall) {
2990       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2991         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2992     }
2993 
2994     return Chain;
2995   }
2996 
2997   if (IsVarArg) {
2998     return lowerUnhandledCall(CLI, InVals,
2999                               "unsupported call to variadic function ");
3000   }
3001 
3002   if (!CLI.CB)
3003     report_fatal_error("unsupported libcall legalization");
3004 
3005   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3006     return lowerUnhandledCall(CLI, InVals,
3007                               "unsupported required tail call to function ");
3008   }
3009 
3010   if (AMDGPU::isShader(CallConv)) {
3011     // Note the issue is with the CC of the called function, not of the call
3012     // itself.
3013     return lowerUnhandledCall(CLI, InVals,
3014                               "unsupported call to a shader function ");
3015   }
3016 
3017   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3018       CallConv != CallingConv::AMDGPU_Gfx) {
3019     // Only allow calls with specific calling conventions.
3020     return lowerUnhandledCall(CLI, InVals,
3021                               "unsupported calling convention for call from "
3022                               "graphics shader of function ");
3023   }
3024 
3025   if (IsTailCall) {
3026     IsTailCall = isEligibleForTailCallOptimization(
3027       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3028     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3029       report_fatal_error("failed to perform tail call elimination on a call "
3030                          "site marked musttail");
3031     }
3032 
3033     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3034 
3035     // A sibling call is one where we're under the usual C ABI and not planning
3036     // to change that but can still do a tail call:
3037     if (!TailCallOpt && IsTailCall)
3038       IsSibCall = true;
3039 
3040     if (IsTailCall)
3041       ++NumTailCalls;
3042   }
3043 
3044   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3045   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3046   SmallVector<SDValue, 8> MemOpChains;
3047 
3048   // Analyze operands of the call, assigning locations to each operand.
3049   SmallVector<CCValAssign, 16> ArgLocs;
3050   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3051   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3052 
3053   if (CallConv != CallingConv::AMDGPU_Gfx) {
3054     // With a fixed ABI, allocate fixed registers before user arguments.
3055     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3056   }
3057 
3058   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3059 
3060   // Get a count of how many bytes are to be pushed on the stack.
3061   unsigned NumBytes = CCInfo.getNextStackOffset();
3062 
3063   if (IsSibCall) {
3064     // Since we're not changing the ABI to make this a tail call, the memory
3065     // operands are already available in the caller's incoming argument space.
3066     NumBytes = 0;
3067   }
3068 
3069   // FPDiff is the byte offset of the call's argument area from the callee's.
3070   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3071   // by this amount for a tail call. In a sibling call it must be 0 because the
3072   // caller will deallocate the entire stack and the callee still expects its
3073   // arguments to begin at SP+0. Completely unused for non-tail calls.
3074   int32_t FPDiff = 0;
3075   MachineFrameInfo &MFI = MF.getFrameInfo();
3076 
3077   // Adjust the stack pointer for the new arguments...
3078   // These operations are automatically eliminated by the prolog/epilog pass
3079   if (!IsSibCall) {
3080     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3081 
3082     if (!Subtarget->enableFlatScratch()) {
3083       SmallVector<SDValue, 4> CopyFromChains;
3084 
3085       // In the HSA case, this should be an identity copy.
3086       SDValue ScratchRSrcReg
3087         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3088       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3089       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3090       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3091     }
3092   }
3093 
3094   MVT PtrVT = MVT::i32;
3095 
3096   // Walk the register/memloc assignments, inserting copies/loads.
3097   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3098     CCValAssign &VA = ArgLocs[i];
3099     SDValue Arg = OutVals[i];
3100 
3101     // Promote the value if needed.
3102     switch (VA.getLocInfo()) {
3103     case CCValAssign::Full:
3104       break;
3105     case CCValAssign::BCvt:
3106       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3107       break;
3108     case CCValAssign::ZExt:
3109       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3110       break;
3111     case CCValAssign::SExt:
3112       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3113       break;
3114     case CCValAssign::AExt:
3115       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3116       break;
3117     case CCValAssign::FPExt:
3118       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3119       break;
3120     default:
3121       llvm_unreachable("Unknown loc info!");
3122     }
3123 
3124     if (VA.isRegLoc()) {
3125       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3126     } else {
3127       assert(VA.isMemLoc());
3128 
3129       SDValue DstAddr;
3130       MachinePointerInfo DstInfo;
3131 
3132       unsigned LocMemOffset = VA.getLocMemOffset();
3133       int32_t Offset = LocMemOffset;
3134 
3135       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3136       MaybeAlign Alignment;
3137 
3138       if (IsTailCall) {
3139         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3140         unsigned OpSize = Flags.isByVal() ?
3141           Flags.getByValSize() : VA.getValVT().getStoreSize();
3142 
3143         // FIXME: We can have better than the minimum byval required alignment.
3144         Alignment =
3145             Flags.isByVal()
3146                 ? Flags.getNonZeroByValAlign()
3147                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3148 
3149         Offset = Offset + FPDiff;
3150         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3151 
3152         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3153         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3154 
3155         // Make sure any stack arguments overlapping with where we're storing
3156         // are loaded before this eventual operation. Otherwise they'll be
3157         // clobbered.
3158 
3159         // FIXME: Why is this really necessary? This seems to just result in a
3160         // lot of code to copy the stack and write them back to the same
3161         // locations, which are supposed to be immutable?
3162         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3163       } else {
3164         // Stores to the argument stack area are relative to the stack pointer.
3165         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3166                                         MVT::i32);
3167         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3168         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3169         Alignment =
3170             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3171       }
3172 
3173       if (Outs[i].Flags.isByVal()) {
3174         SDValue SizeNode =
3175             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3176         SDValue Cpy =
3177             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3178                           Outs[i].Flags.getNonZeroByValAlign(),
3179                           /*isVol = */ false, /*AlwaysInline = */ true,
3180                           /*isTailCall = */ false, DstInfo,
3181                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3182 
3183         MemOpChains.push_back(Cpy);
3184       } else {
3185         SDValue Store =
3186             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3187         MemOpChains.push_back(Store);
3188       }
3189     }
3190   }
3191 
3192   if (!MemOpChains.empty())
3193     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3194 
3195   // Build a sequence of copy-to-reg nodes chained together with token chain
3196   // and flag operands which copy the outgoing args into the appropriate regs.
3197   SDValue InFlag;
3198   for (auto &RegToPass : RegsToPass) {
3199     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3200                              RegToPass.second, InFlag);
3201     InFlag = Chain.getValue(1);
3202   }
3203 
3204 
3205   // We don't usually want to end the call-sequence here because we would tidy
3206   // the frame up *after* the call, however in the ABI-changing tail-call case
3207   // we've carefully laid out the parameters so that when sp is reset they'll be
3208   // in the correct location.
3209   if (IsTailCall && !IsSibCall) {
3210     Chain = DAG.getCALLSEQ_END(Chain,
3211                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3212                                DAG.getTargetConstant(0, DL, MVT::i32),
3213                                InFlag, DL);
3214     InFlag = Chain.getValue(1);
3215   }
3216 
3217   std::vector<SDValue> Ops;
3218   Ops.push_back(Chain);
3219   Ops.push_back(Callee);
3220   // Add a redundant copy of the callee global which will not be legalized, as
3221   // we need direct access to the callee later.
3222   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3223     const GlobalValue *GV = GSD->getGlobal();
3224     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3225   } else {
3226     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3227   }
3228 
3229   if (IsTailCall) {
3230     // Each tail call may have to adjust the stack by a different amount, so
3231     // this information must travel along with the operation for eventual
3232     // consumption by emitEpilogue.
3233     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3234   }
3235 
3236   // Add argument registers to the end of the list so that they are known live
3237   // into the call.
3238   for (auto &RegToPass : RegsToPass) {
3239     Ops.push_back(DAG.getRegister(RegToPass.first,
3240                                   RegToPass.second.getValueType()));
3241   }
3242 
3243   // Add a register mask operand representing the call-preserved registers.
3244 
3245   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3246   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3247   assert(Mask && "Missing call preserved mask for calling convention");
3248   Ops.push_back(DAG.getRegisterMask(Mask));
3249 
3250   if (InFlag.getNode())
3251     Ops.push_back(InFlag);
3252 
3253   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3254 
3255   // If we're doing a tall call, use a TC_RETURN here rather than an
3256   // actual call instruction.
3257   if (IsTailCall) {
3258     MFI.setHasTailCall();
3259     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3260   }
3261 
3262   // Returns a chain and a flag for retval copy to use.
3263   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3264   Chain = Call.getValue(0);
3265   InFlag = Call.getValue(1);
3266 
3267   uint64_t CalleePopBytes = NumBytes;
3268   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3269                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3270                              InFlag, DL);
3271   if (!Ins.empty())
3272     InFlag = Chain.getValue(1);
3273 
3274   // Handle result values, copying them out of physregs into vregs that we
3275   // return.
3276   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3277                          InVals, IsThisReturn,
3278                          IsThisReturn ? OutVals[0] : SDValue());
3279 }
3280 
3281 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3282 // except for applying the wave size scale to the increment amount.
3283 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3284     SDValue Op, SelectionDAG &DAG) const {
3285   const MachineFunction &MF = DAG.getMachineFunction();
3286   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3287 
3288   SDLoc dl(Op);
3289   EVT VT = Op.getValueType();
3290   SDValue Tmp1 = Op;
3291   SDValue Tmp2 = Op.getValue(1);
3292   SDValue Tmp3 = Op.getOperand(2);
3293   SDValue Chain = Tmp1.getOperand(0);
3294 
3295   Register SPReg = Info->getStackPtrOffsetReg();
3296 
3297   // Chain the dynamic stack allocation so that it doesn't modify the stack
3298   // pointer when other instructions are using the stack.
3299   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3300 
3301   SDValue Size  = Tmp2.getOperand(1);
3302   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3303   Chain = SP.getValue(1);
3304   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3305   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3306   const TargetFrameLowering *TFL = ST.getFrameLowering();
3307   unsigned Opc =
3308     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3309     ISD::ADD : ISD::SUB;
3310 
3311   SDValue ScaledSize = DAG.getNode(
3312       ISD::SHL, dl, VT, Size,
3313       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3314 
3315   Align StackAlign = TFL->getStackAlign();
3316   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3317   if (Alignment && *Alignment > StackAlign) {
3318     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3319                        DAG.getConstant(-(uint64_t)Alignment->value()
3320                                            << ST.getWavefrontSizeLog2(),
3321                                        dl, VT));
3322   }
3323 
3324   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3325   Tmp2 = DAG.getCALLSEQ_END(
3326       Chain, DAG.getIntPtrConstant(0, dl, true),
3327       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3328 
3329   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3330 }
3331 
3332 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3333                                                   SelectionDAG &DAG) const {
3334   // We only handle constant sizes here to allow non-entry block, static sized
3335   // allocas. A truly dynamic value is more difficult to support because we
3336   // don't know if the size value is uniform or not. If the size isn't uniform,
3337   // we would need to do a wave reduction to get the maximum size to know how
3338   // much to increment the uniform stack pointer.
3339   SDValue Size = Op.getOperand(1);
3340   if (isa<ConstantSDNode>(Size))
3341       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3342 
3343   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3344 }
3345 
3346 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3347                                              const MachineFunction &MF) const {
3348   Register Reg = StringSwitch<Register>(RegName)
3349     .Case("m0", AMDGPU::M0)
3350     .Case("exec", AMDGPU::EXEC)
3351     .Case("exec_lo", AMDGPU::EXEC_LO)
3352     .Case("exec_hi", AMDGPU::EXEC_HI)
3353     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3354     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3355     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3356     .Default(Register());
3357 
3358   if (Reg == AMDGPU::NoRegister) {
3359     report_fatal_error(Twine("invalid register name \""
3360                              + StringRef(RegName)  + "\"."));
3361 
3362   }
3363 
3364   if (!Subtarget->hasFlatScrRegister() &&
3365        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3366     report_fatal_error(Twine("invalid register \""
3367                              + StringRef(RegName)  + "\" for subtarget."));
3368   }
3369 
3370   switch (Reg) {
3371   case AMDGPU::M0:
3372   case AMDGPU::EXEC_LO:
3373   case AMDGPU::EXEC_HI:
3374   case AMDGPU::FLAT_SCR_LO:
3375   case AMDGPU::FLAT_SCR_HI:
3376     if (VT.getSizeInBits() == 32)
3377       return Reg;
3378     break;
3379   case AMDGPU::EXEC:
3380   case AMDGPU::FLAT_SCR:
3381     if (VT.getSizeInBits() == 64)
3382       return Reg;
3383     break;
3384   default:
3385     llvm_unreachable("missing register type checking");
3386   }
3387 
3388   report_fatal_error(Twine("invalid type for register \""
3389                            + StringRef(RegName) + "\"."));
3390 }
3391 
3392 // If kill is not the last instruction, split the block so kill is always a
3393 // proper terminator.
3394 MachineBasicBlock *
3395 SITargetLowering::splitKillBlock(MachineInstr &MI,
3396                                  MachineBasicBlock *BB) const {
3397   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3398   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3399   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3400   return SplitBB;
3401 }
3402 
3403 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3404 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3405 // be the first instruction in the remainder block.
3406 //
3407 /// \returns { LoopBody, Remainder }
3408 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3409 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3410   MachineFunction *MF = MBB.getParent();
3411   MachineBasicBlock::iterator I(&MI);
3412 
3413   // To insert the loop we need to split the block. Move everything after this
3414   // point to a new block, and insert a new empty block between the two.
3415   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3416   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3417   MachineFunction::iterator MBBI(MBB);
3418   ++MBBI;
3419 
3420   MF->insert(MBBI, LoopBB);
3421   MF->insert(MBBI, RemainderBB);
3422 
3423   LoopBB->addSuccessor(LoopBB);
3424   LoopBB->addSuccessor(RemainderBB);
3425 
3426   // Move the rest of the block into a new block.
3427   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3428 
3429   if (InstInLoop) {
3430     auto Next = std::next(I);
3431 
3432     // Move instruction to loop body.
3433     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3434 
3435     // Move the rest of the block.
3436     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3437   } else {
3438     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3439   }
3440 
3441   MBB.addSuccessor(LoopBB);
3442 
3443   return std::make_pair(LoopBB, RemainderBB);
3444 }
3445 
3446 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3447 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3448   MachineBasicBlock *MBB = MI.getParent();
3449   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3450   auto I = MI.getIterator();
3451   auto E = std::next(I);
3452 
3453   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3454     .addImm(0);
3455 
3456   MIBundleBuilder Bundler(*MBB, I, E);
3457   finalizeBundle(*MBB, Bundler.begin());
3458 }
3459 
3460 MachineBasicBlock *
3461 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3462                                          MachineBasicBlock *BB) const {
3463   const DebugLoc &DL = MI.getDebugLoc();
3464 
3465   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3466 
3467   MachineBasicBlock *LoopBB;
3468   MachineBasicBlock *RemainderBB;
3469   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3470 
3471   // Apparently kill flags are only valid if the def is in the same block?
3472   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3473     Src->setIsKill(false);
3474 
3475   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3476 
3477   MachineBasicBlock::iterator I = LoopBB->end();
3478 
3479   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3480     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3481 
3482   // Clear TRAP_STS.MEM_VIOL
3483   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3484     .addImm(0)
3485     .addImm(EncodedReg);
3486 
3487   bundleInstWithWaitcnt(MI);
3488 
3489   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3490 
3491   // Load and check TRAP_STS.MEM_VIOL
3492   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3493     .addImm(EncodedReg);
3494 
3495   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3496   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3497     .addReg(Reg, RegState::Kill)
3498     .addImm(0);
3499   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3500     .addMBB(LoopBB);
3501 
3502   return RemainderBB;
3503 }
3504 
3505 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3506 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3507 // will only do one iteration. In the worst case, this will loop 64 times.
3508 //
3509 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3510 static MachineBasicBlock::iterator
3511 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3512                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3513                        const DebugLoc &DL, const MachineOperand &Idx,
3514                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3515                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3516                        Register &SGPRIdxReg) {
3517 
3518   MachineFunction *MF = OrigBB.getParent();
3519   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3520   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3521   MachineBasicBlock::iterator I = LoopBB.begin();
3522 
3523   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3524   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3525   Register NewExec = MRI.createVirtualRegister(BoolRC);
3526   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3527   Register CondReg = MRI.createVirtualRegister(BoolRC);
3528 
3529   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3530     .addReg(InitReg)
3531     .addMBB(&OrigBB)
3532     .addReg(ResultReg)
3533     .addMBB(&LoopBB);
3534 
3535   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3536     .addReg(InitSaveExecReg)
3537     .addMBB(&OrigBB)
3538     .addReg(NewExec)
3539     .addMBB(&LoopBB);
3540 
3541   // Read the next variant <- also loop target.
3542   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3543       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3544 
3545   // Compare the just read M0 value to all possible Idx values.
3546   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3547       .addReg(CurrentIdxReg)
3548       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3549 
3550   // Update EXEC, save the original EXEC value to VCC.
3551   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3552                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3553           NewExec)
3554     .addReg(CondReg, RegState::Kill);
3555 
3556   MRI.setSimpleHint(NewExec, CondReg);
3557 
3558   if (UseGPRIdxMode) {
3559     if (Offset == 0) {
3560       SGPRIdxReg = CurrentIdxReg;
3561     } else {
3562       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3563       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3564           .addReg(CurrentIdxReg, RegState::Kill)
3565           .addImm(Offset);
3566     }
3567   } else {
3568     // Move index from VCC into M0
3569     if (Offset == 0) {
3570       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3571         .addReg(CurrentIdxReg, RegState::Kill);
3572     } else {
3573       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3574         .addReg(CurrentIdxReg, RegState::Kill)
3575         .addImm(Offset);
3576     }
3577   }
3578 
3579   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3580   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3581   MachineInstr *InsertPt =
3582     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3583                                                   : AMDGPU::S_XOR_B64_term), Exec)
3584       .addReg(Exec)
3585       .addReg(NewExec);
3586 
3587   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3588   // s_cbranch_scc0?
3589 
3590   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3591   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3592     .addMBB(&LoopBB);
3593 
3594   return InsertPt->getIterator();
3595 }
3596 
3597 // This has slightly sub-optimal regalloc when the source vector is killed by
3598 // the read. The register allocator does not understand that the kill is
3599 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3600 // subregister from it, using 1 more VGPR than necessary. This was saved when
3601 // this was expanded after register allocation.
3602 static MachineBasicBlock::iterator
3603 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3604                unsigned InitResultReg, unsigned PhiReg, int Offset,
3605                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3606   MachineFunction *MF = MBB.getParent();
3607   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3608   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3609   MachineRegisterInfo &MRI = MF->getRegInfo();
3610   const DebugLoc &DL = MI.getDebugLoc();
3611   MachineBasicBlock::iterator I(&MI);
3612 
3613   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3614   Register DstReg = MI.getOperand(0).getReg();
3615   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3616   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3617   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3618   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3619 
3620   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3621 
3622   // Save the EXEC mask
3623   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3624     .addReg(Exec);
3625 
3626   MachineBasicBlock *LoopBB;
3627   MachineBasicBlock *RemainderBB;
3628   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3629 
3630   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3631 
3632   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3633                                       InitResultReg, DstReg, PhiReg, TmpExec,
3634                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3635 
3636   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3637   MachineFunction::iterator MBBI(LoopBB);
3638   ++MBBI;
3639   MF->insert(MBBI, LandingPad);
3640   LoopBB->removeSuccessor(RemainderBB);
3641   LandingPad->addSuccessor(RemainderBB);
3642   LoopBB->addSuccessor(LandingPad);
3643   MachineBasicBlock::iterator First = LandingPad->begin();
3644   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3645     .addReg(SaveExec);
3646 
3647   return InsPt;
3648 }
3649 
3650 // Returns subreg index, offset
3651 static std::pair<unsigned, int>
3652 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3653                             const TargetRegisterClass *SuperRC,
3654                             unsigned VecReg,
3655                             int Offset) {
3656   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3657 
3658   // Skip out of bounds offsets, or else we would end up using an undefined
3659   // register.
3660   if (Offset >= NumElts || Offset < 0)
3661     return std::make_pair(AMDGPU::sub0, Offset);
3662 
3663   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3664 }
3665 
3666 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3667                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3668                                  int Offset) {
3669   MachineBasicBlock *MBB = MI.getParent();
3670   const DebugLoc &DL = MI.getDebugLoc();
3671   MachineBasicBlock::iterator I(&MI);
3672 
3673   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3674 
3675   assert(Idx->getReg() != AMDGPU::NoRegister);
3676 
3677   if (Offset == 0) {
3678     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3679   } else {
3680     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3681         .add(*Idx)
3682         .addImm(Offset);
3683   }
3684 }
3685 
3686 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3687                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3688                                    int Offset) {
3689   MachineBasicBlock *MBB = MI.getParent();
3690   const DebugLoc &DL = MI.getDebugLoc();
3691   MachineBasicBlock::iterator I(&MI);
3692 
3693   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3694 
3695   if (Offset == 0)
3696     return Idx->getReg();
3697 
3698   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3699   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3700       .add(*Idx)
3701       .addImm(Offset);
3702   return Tmp;
3703 }
3704 
3705 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3706                                           MachineBasicBlock &MBB,
3707                                           const GCNSubtarget &ST) {
3708   const SIInstrInfo *TII = ST.getInstrInfo();
3709   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3710   MachineFunction *MF = MBB.getParent();
3711   MachineRegisterInfo &MRI = MF->getRegInfo();
3712 
3713   Register Dst = MI.getOperand(0).getReg();
3714   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3715   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3716   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3717 
3718   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3719   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3720 
3721   unsigned SubReg;
3722   std::tie(SubReg, Offset)
3723     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3724 
3725   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3726 
3727   // Check for a SGPR index.
3728   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3729     MachineBasicBlock::iterator I(&MI);
3730     const DebugLoc &DL = MI.getDebugLoc();
3731 
3732     if (UseGPRIdxMode) {
3733       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3734       // to avoid interfering with other uses, so probably requires a new
3735       // optimization pass.
3736       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3737 
3738       const MCInstrDesc &GPRIDXDesc =
3739           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3740       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3741           .addReg(SrcReg)
3742           .addReg(Idx)
3743           .addImm(SubReg);
3744     } else {
3745       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3746 
3747       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3748         .addReg(SrcReg, 0, SubReg)
3749         .addReg(SrcReg, RegState::Implicit);
3750     }
3751 
3752     MI.eraseFromParent();
3753 
3754     return &MBB;
3755   }
3756 
3757   // Control flow needs to be inserted if indexing with a VGPR.
3758   const DebugLoc &DL = MI.getDebugLoc();
3759   MachineBasicBlock::iterator I(&MI);
3760 
3761   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3762   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3763 
3764   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3765 
3766   Register SGPRIdxReg;
3767   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3768                               UseGPRIdxMode, SGPRIdxReg);
3769 
3770   MachineBasicBlock *LoopBB = InsPt->getParent();
3771 
3772   if (UseGPRIdxMode) {
3773     const MCInstrDesc &GPRIDXDesc =
3774         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3775 
3776     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3777         .addReg(SrcReg)
3778         .addReg(SGPRIdxReg)
3779         .addImm(SubReg);
3780   } else {
3781     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3782       .addReg(SrcReg, 0, SubReg)
3783       .addReg(SrcReg, RegState::Implicit);
3784   }
3785 
3786   MI.eraseFromParent();
3787 
3788   return LoopBB;
3789 }
3790 
3791 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3792                                           MachineBasicBlock &MBB,
3793                                           const GCNSubtarget &ST) {
3794   const SIInstrInfo *TII = ST.getInstrInfo();
3795   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3796   MachineFunction *MF = MBB.getParent();
3797   MachineRegisterInfo &MRI = MF->getRegInfo();
3798 
3799   Register Dst = MI.getOperand(0).getReg();
3800   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3801   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3802   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3803   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3804   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3805   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3806 
3807   // This can be an immediate, but will be folded later.
3808   assert(Val->getReg());
3809 
3810   unsigned SubReg;
3811   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3812                                                          SrcVec->getReg(),
3813                                                          Offset);
3814   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3815 
3816   if (Idx->getReg() == AMDGPU::NoRegister) {
3817     MachineBasicBlock::iterator I(&MI);
3818     const DebugLoc &DL = MI.getDebugLoc();
3819 
3820     assert(Offset == 0);
3821 
3822     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3823         .add(*SrcVec)
3824         .add(*Val)
3825         .addImm(SubReg);
3826 
3827     MI.eraseFromParent();
3828     return &MBB;
3829   }
3830 
3831   // Check for a SGPR index.
3832   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3833     MachineBasicBlock::iterator I(&MI);
3834     const DebugLoc &DL = MI.getDebugLoc();
3835 
3836     if (UseGPRIdxMode) {
3837       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3838 
3839       const MCInstrDesc &GPRIDXDesc =
3840           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3841       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3842           .addReg(SrcVec->getReg())
3843           .add(*Val)
3844           .addReg(Idx)
3845           .addImm(SubReg);
3846     } else {
3847       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3848 
3849       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3850           TRI.getRegSizeInBits(*VecRC), 32, false);
3851       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3852           .addReg(SrcVec->getReg())
3853           .add(*Val)
3854           .addImm(SubReg);
3855     }
3856     MI.eraseFromParent();
3857     return &MBB;
3858   }
3859 
3860   // Control flow needs to be inserted if indexing with a VGPR.
3861   if (Val->isReg())
3862     MRI.clearKillFlags(Val->getReg());
3863 
3864   const DebugLoc &DL = MI.getDebugLoc();
3865 
3866   Register PhiReg = MRI.createVirtualRegister(VecRC);
3867 
3868   Register SGPRIdxReg;
3869   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3870                               UseGPRIdxMode, SGPRIdxReg);
3871   MachineBasicBlock *LoopBB = InsPt->getParent();
3872 
3873   if (UseGPRIdxMode) {
3874     const MCInstrDesc &GPRIDXDesc =
3875         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3876 
3877     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3878         .addReg(PhiReg)
3879         .add(*Val)
3880         .addReg(SGPRIdxReg)
3881         .addImm(AMDGPU::sub0);
3882   } else {
3883     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3884         TRI.getRegSizeInBits(*VecRC), 32, false);
3885     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3886         .addReg(PhiReg)
3887         .add(*Val)
3888         .addImm(AMDGPU::sub0);
3889   }
3890 
3891   MI.eraseFromParent();
3892   return LoopBB;
3893 }
3894 
3895 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3896   MachineInstr &MI, MachineBasicBlock *BB) const {
3897 
3898   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3899   MachineFunction *MF = BB->getParent();
3900   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3901 
3902   switch (MI.getOpcode()) {
3903   case AMDGPU::S_UADDO_PSEUDO:
3904   case AMDGPU::S_USUBO_PSEUDO: {
3905     const DebugLoc &DL = MI.getDebugLoc();
3906     MachineOperand &Dest0 = MI.getOperand(0);
3907     MachineOperand &Dest1 = MI.getOperand(1);
3908     MachineOperand &Src0 = MI.getOperand(2);
3909     MachineOperand &Src1 = MI.getOperand(3);
3910 
3911     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3912                        ? AMDGPU::S_ADD_I32
3913                        : AMDGPU::S_SUB_I32;
3914     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3915 
3916     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3917         .addImm(1)
3918         .addImm(0);
3919 
3920     MI.eraseFromParent();
3921     return BB;
3922   }
3923   case AMDGPU::S_ADD_U64_PSEUDO:
3924   case AMDGPU::S_SUB_U64_PSEUDO: {
3925     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3926     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3927     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3928     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3929     const DebugLoc &DL = MI.getDebugLoc();
3930 
3931     MachineOperand &Dest = MI.getOperand(0);
3932     MachineOperand &Src0 = MI.getOperand(1);
3933     MachineOperand &Src1 = MI.getOperand(2);
3934 
3935     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3936     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3937 
3938     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3939         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3940     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3941         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3942 
3943     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3944         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3945     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3946         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3947 
3948     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3949 
3950     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3951     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3952     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3953     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3954     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3955         .addReg(DestSub0)
3956         .addImm(AMDGPU::sub0)
3957         .addReg(DestSub1)
3958         .addImm(AMDGPU::sub1);
3959     MI.eraseFromParent();
3960     return BB;
3961   }
3962   case AMDGPU::V_ADD_U64_PSEUDO:
3963   case AMDGPU::V_SUB_U64_PSEUDO: {
3964     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3965     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3966     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3967     const DebugLoc &DL = MI.getDebugLoc();
3968 
3969     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3970 
3971     MachineOperand &Dest = MI.getOperand(0);
3972     MachineOperand &Src0 = MI.getOperand(1);
3973     MachineOperand &Src1 = MI.getOperand(2);
3974 
3975     if (IsAdd && ST.hasLshlAddB64()) {
3976       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
3977                          Dest.getReg())
3978                      .add(Src0)
3979                      .addImm(0)
3980                      .add(Src1);
3981       TII->legalizeOperands(*Add);
3982       MI.eraseFromParent();
3983       return BB;
3984     }
3985 
3986     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3987 
3988     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3989     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3990 
3991     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3992     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3993 
3994     const TargetRegisterClass *Src0RC = Src0.isReg()
3995                                             ? MRI.getRegClass(Src0.getReg())
3996                                             : &AMDGPU::VReg_64RegClass;
3997     const TargetRegisterClass *Src1RC = Src1.isReg()
3998                                             ? MRI.getRegClass(Src1.getReg())
3999                                             : &AMDGPU::VReg_64RegClass;
4000 
4001     const TargetRegisterClass *Src0SubRC =
4002         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4003     const TargetRegisterClass *Src1SubRC =
4004         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4005 
4006     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4007         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4008     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4009         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4010 
4011     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4012         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4013     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4014         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4015 
4016     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4017     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4018                                .addReg(CarryReg, RegState::Define)
4019                                .add(SrcReg0Sub0)
4020                                .add(SrcReg1Sub0)
4021                                .addImm(0); // clamp bit
4022 
4023     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4024     MachineInstr *HiHalf =
4025         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4026             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4027             .add(SrcReg0Sub1)
4028             .add(SrcReg1Sub1)
4029             .addReg(CarryReg, RegState::Kill)
4030             .addImm(0); // clamp bit
4031 
4032     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4033         .addReg(DestSub0)
4034         .addImm(AMDGPU::sub0)
4035         .addReg(DestSub1)
4036         .addImm(AMDGPU::sub1);
4037     TII->legalizeOperands(*LoHalf);
4038     TII->legalizeOperands(*HiHalf);
4039     MI.eraseFromParent();
4040     return BB;
4041   }
4042   case AMDGPU::S_ADD_CO_PSEUDO:
4043   case AMDGPU::S_SUB_CO_PSEUDO: {
4044     // This pseudo has a chance to be selected
4045     // only from uniform add/subcarry node. All the VGPR operands
4046     // therefore assumed to be splat vectors.
4047     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4048     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4049     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4050     MachineBasicBlock::iterator MII = MI;
4051     const DebugLoc &DL = MI.getDebugLoc();
4052     MachineOperand &Dest = MI.getOperand(0);
4053     MachineOperand &CarryDest = MI.getOperand(1);
4054     MachineOperand &Src0 = MI.getOperand(2);
4055     MachineOperand &Src1 = MI.getOperand(3);
4056     MachineOperand &Src2 = MI.getOperand(4);
4057     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4058                        ? AMDGPU::S_ADDC_U32
4059                        : AMDGPU::S_SUBB_U32;
4060     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4061       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4062       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4063           .addReg(Src0.getReg());
4064       Src0.setReg(RegOp0);
4065     }
4066     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4067       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4068       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4069           .addReg(Src1.getReg());
4070       Src1.setReg(RegOp1);
4071     }
4072     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4073     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4074       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4075           .addReg(Src2.getReg());
4076       Src2.setReg(RegOp2);
4077     }
4078 
4079     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4080     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4081     assert(WaveSize == 64 || WaveSize == 32);
4082 
4083     if (WaveSize == 64) {
4084       if (ST.hasScalarCompareEq64()) {
4085         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4086             .addReg(Src2.getReg())
4087             .addImm(0);
4088       } else {
4089         const TargetRegisterClass *SubRC =
4090             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4091         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4092             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4093         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4094             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4095         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4096 
4097         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4098             .add(Src2Sub0)
4099             .add(Src2Sub1);
4100 
4101         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4102             .addReg(Src2_32, RegState::Kill)
4103             .addImm(0);
4104       }
4105     } else {
4106       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4107           .addReg(Src2.getReg())
4108           .addImm(0);
4109     }
4110 
4111     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4112 
4113     unsigned SelOpc =
4114         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4115 
4116     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4117         .addImm(-1)
4118         .addImm(0);
4119 
4120     MI.eraseFromParent();
4121     return BB;
4122   }
4123   case AMDGPU::SI_INIT_M0: {
4124     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4125             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4126         .add(MI.getOperand(0));
4127     MI.eraseFromParent();
4128     return BB;
4129   }
4130   case AMDGPU::GET_GROUPSTATICSIZE: {
4131     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4132            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4133     DebugLoc DL = MI.getDebugLoc();
4134     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4135         .add(MI.getOperand(0))
4136         .addImm(MFI->getLDSSize());
4137     MI.eraseFromParent();
4138     return BB;
4139   }
4140   case AMDGPU::SI_INDIRECT_SRC_V1:
4141   case AMDGPU::SI_INDIRECT_SRC_V2:
4142   case AMDGPU::SI_INDIRECT_SRC_V4:
4143   case AMDGPU::SI_INDIRECT_SRC_V8:
4144   case AMDGPU::SI_INDIRECT_SRC_V16:
4145   case AMDGPU::SI_INDIRECT_SRC_V32:
4146     return emitIndirectSrc(MI, *BB, *getSubtarget());
4147   case AMDGPU::SI_INDIRECT_DST_V1:
4148   case AMDGPU::SI_INDIRECT_DST_V2:
4149   case AMDGPU::SI_INDIRECT_DST_V4:
4150   case AMDGPU::SI_INDIRECT_DST_V8:
4151   case AMDGPU::SI_INDIRECT_DST_V16:
4152   case AMDGPU::SI_INDIRECT_DST_V32:
4153     return emitIndirectDst(MI, *BB, *getSubtarget());
4154   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4155   case AMDGPU::SI_KILL_I1_PSEUDO:
4156     return splitKillBlock(MI, BB);
4157   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4158     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4159     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4160     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4161 
4162     Register Dst = MI.getOperand(0).getReg();
4163     Register Src0 = MI.getOperand(1).getReg();
4164     Register Src1 = MI.getOperand(2).getReg();
4165     const DebugLoc &DL = MI.getDebugLoc();
4166     Register SrcCond = MI.getOperand(3).getReg();
4167 
4168     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4169     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4170     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4171     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4172 
4173     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4174       .addReg(SrcCond);
4175     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4176       .addImm(0)
4177       .addReg(Src0, 0, AMDGPU::sub0)
4178       .addImm(0)
4179       .addReg(Src1, 0, AMDGPU::sub0)
4180       .addReg(SrcCondCopy);
4181     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4182       .addImm(0)
4183       .addReg(Src0, 0, AMDGPU::sub1)
4184       .addImm(0)
4185       .addReg(Src1, 0, AMDGPU::sub1)
4186       .addReg(SrcCondCopy);
4187 
4188     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4189       .addReg(DstLo)
4190       .addImm(AMDGPU::sub0)
4191       .addReg(DstHi)
4192       .addImm(AMDGPU::sub1);
4193     MI.eraseFromParent();
4194     return BB;
4195   }
4196   case AMDGPU::SI_BR_UNDEF: {
4197     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4198     const DebugLoc &DL = MI.getDebugLoc();
4199     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4200                            .add(MI.getOperand(0));
4201     Br->getOperand(1).setIsUndef(true); // read undef SCC
4202     MI.eraseFromParent();
4203     return BB;
4204   }
4205   case AMDGPU::ADJCALLSTACKUP:
4206   case AMDGPU::ADJCALLSTACKDOWN: {
4207     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4208     MachineInstrBuilder MIB(*MF, &MI);
4209     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4210        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4211     return BB;
4212   }
4213   case AMDGPU::SI_CALL_ISEL: {
4214     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4215     const DebugLoc &DL = MI.getDebugLoc();
4216 
4217     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4218 
4219     MachineInstrBuilder MIB;
4220     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4221 
4222     for (const MachineOperand &MO : MI.operands())
4223       MIB.add(MO);
4224 
4225     MIB.cloneMemRefs(MI);
4226     MI.eraseFromParent();
4227     return BB;
4228   }
4229   case AMDGPU::V_ADD_CO_U32_e32:
4230   case AMDGPU::V_SUB_CO_U32_e32:
4231   case AMDGPU::V_SUBREV_CO_U32_e32: {
4232     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4233     const DebugLoc &DL = MI.getDebugLoc();
4234     unsigned Opc = MI.getOpcode();
4235 
4236     bool NeedClampOperand = false;
4237     if (TII->pseudoToMCOpcode(Opc) == -1) {
4238       Opc = AMDGPU::getVOPe64(Opc);
4239       NeedClampOperand = true;
4240     }
4241 
4242     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4243     if (TII->isVOP3(*I)) {
4244       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4245       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4246       I.addReg(TRI->getVCC(), RegState::Define);
4247     }
4248     I.add(MI.getOperand(1))
4249      .add(MI.getOperand(2));
4250     if (NeedClampOperand)
4251       I.addImm(0); // clamp bit for e64 encoding
4252 
4253     TII->legalizeOperands(*I);
4254 
4255     MI.eraseFromParent();
4256     return BB;
4257   }
4258   case AMDGPU::V_ADDC_U32_e32:
4259   case AMDGPU::V_SUBB_U32_e32:
4260   case AMDGPU::V_SUBBREV_U32_e32:
4261     // These instructions have an implicit use of vcc which counts towards the
4262     // constant bus limit.
4263     TII->legalizeOperands(MI);
4264     return BB;
4265   case AMDGPU::DS_GWS_INIT:
4266   case AMDGPU::DS_GWS_SEMA_BR:
4267   case AMDGPU::DS_GWS_BARRIER:
4268     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
4269     LLVM_FALLTHROUGH;
4270   case AMDGPU::DS_GWS_SEMA_V:
4271   case AMDGPU::DS_GWS_SEMA_P:
4272   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4273     // A s_waitcnt 0 is required to be the instruction immediately following.
4274     if (getSubtarget()->hasGWSAutoReplay()) {
4275       bundleInstWithWaitcnt(MI);
4276       return BB;
4277     }
4278 
4279     return emitGWSMemViolTestLoop(MI, BB);
4280   case AMDGPU::S_SETREG_B32: {
4281     // Try to optimize cases that only set the denormal mode or rounding mode.
4282     //
4283     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4284     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4285     // instead.
4286     //
4287     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4288     // allow you to have a no side effect instruction in the output of a
4289     // sideeffecting pattern.
4290     unsigned ID, Offset, Width;
4291     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4292     if (ID != AMDGPU::Hwreg::ID_MODE)
4293       return BB;
4294 
4295     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4296     const unsigned SetMask = WidthMask << Offset;
4297 
4298     if (getSubtarget()->hasDenormModeInst()) {
4299       unsigned SetDenormOp = 0;
4300       unsigned SetRoundOp = 0;
4301 
4302       // The dedicated instructions can only set the whole denorm or round mode
4303       // at once, not a subset of bits in either.
4304       if (SetMask ==
4305           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4306         // If this fully sets both the round and denorm mode, emit the two
4307         // dedicated instructions for these.
4308         SetRoundOp = AMDGPU::S_ROUND_MODE;
4309         SetDenormOp = AMDGPU::S_DENORM_MODE;
4310       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4311         SetRoundOp = AMDGPU::S_ROUND_MODE;
4312       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4313         SetDenormOp = AMDGPU::S_DENORM_MODE;
4314       }
4315 
4316       if (SetRoundOp || SetDenormOp) {
4317         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4318         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4319         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4320           unsigned ImmVal = Def->getOperand(1).getImm();
4321           if (SetRoundOp) {
4322             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4323                 .addImm(ImmVal & 0xf);
4324 
4325             // If we also have the denorm mode, get just the denorm mode bits.
4326             ImmVal >>= 4;
4327           }
4328 
4329           if (SetDenormOp) {
4330             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4331                 .addImm(ImmVal & 0xf);
4332           }
4333 
4334           MI.eraseFromParent();
4335           return BB;
4336         }
4337       }
4338     }
4339 
4340     // If only FP bits are touched, used the no side effects pseudo.
4341     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4342                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4343       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4344 
4345     return BB;
4346   }
4347   default:
4348     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4349   }
4350 }
4351 
4352 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4353   return isTypeLegal(VT.getScalarType());
4354 }
4355 
4356 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4357   // This currently forces unfolding various combinations of fsub into fma with
4358   // free fneg'd operands. As long as we have fast FMA (controlled by
4359   // isFMAFasterThanFMulAndFAdd), we should perform these.
4360 
4361   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4362   // most of these combines appear to be cycle neutral but save on instruction
4363   // count / code size.
4364   return true;
4365 }
4366 
4367 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4368 
4369 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4370                                          EVT VT) const {
4371   if (!VT.isVector()) {
4372     return MVT::i1;
4373   }
4374   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4375 }
4376 
4377 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4378   // TODO: Should i16 be used always if legal? For now it would force VALU
4379   // shifts.
4380   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4381 }
4382 
4383 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4384   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4385              ? Ty.changeElementSize(16)
4386              : Ty.changeElementSize(32);
4387 }
4388 
4389 // Answering this is somewhat tricky and depends on the specific device which
4390 // have different rates for fma or all f64 operations.
4391 //
4392 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4393 // regardless of which device (although the number of cycles differs between
4394 // devices), so it is always profitable for f64.
4395 //
4396 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4397 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4398 // which we can always do even without fused FP ops since it returns the same
4399 // result as the separate operations and since it is always full
4400 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4401 // however does not support denormals, so we do report fma as faster if we have
4402 // a fast fma device and require denormals.
4403 //
4404 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4405                                                   EVT VT) const {
4406   VT = VT.getScalarType();
4407 
4408   switch (VT.getSimpleVT().SimpleTy) {
4409   case MVT::f32: {
4410     // If mad is not available this depends only on if f32 fma is full rate.
4411     if (!Subtarget->hasMadMacF32Insts())
4412       return Subtarget->hasFastFMAF32();
4413 
4414     // Otherwise f32 mad is always full rate and returns the same result as
4415     // the separate operations so should be preferred over fma.
4416     // However does not support denormals.
4417     if (hasFP32Denormals(MF))
4418       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4419 
4420     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4421     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4422   }
4423   case MVT::f64:
4424     return true;
4425   case MVT::f16:
4426     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4427   default:
4428     break;
4429   }
4430 
4431   return false;
4432 }
4433 
4434 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4435                                                   LLT Ty) const {
4436   switch (Ty.getScalarSizeInBits()) {
4437   case 16:
4438     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4439   case 32:
4440     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4441   case 64:
4442     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4443   default:
4444     break;
4445   }
4446 
4447   return false;
4448 }
4449 
4450 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4451   if (!Ty.isScalar())
4452     return false;
4453 
4454   if (Ty.getScalarSizeInBits() == 16)
4455     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4456   if (Ty.getScalarSizeInBits() == 32)
4457     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4458 
4459   return false;
4460 }
4461 
4462 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4463                                    const SDNode *N) const {
4464   // TODO: Check future ftz flag
4465   // v_mad_f32/v_mac_f32 do not support denormals.
4466   EVT VT = N->getValueType(0);
4467   if (VT == MVT::f32)
4468     return Subtarget->hasMadMacF32Insts() &&
4469            !hasFP32Denormals(DAG.getMachineFunction());
4470   if (VT == MVT::f16) {
4471     return Subtarget->hasMadF16() &&
4472            !hasFP64FP16Denormals(DAG.getMachineFunction());
4473   }
4474 
4475   return false;
4476 }
4477 
4478 //===----------------------------------------------------------------------===//
4479 // Custom DAG Lowering Operations
4480 //===----------------------------------------------------------------------===//
4481 
4482 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4483 // wider vector type is legal.
4484 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4485                                              SelectionDAG &DAG) const {
4486   unsigned Opc = Op.getOpcode();
4487   EVT VT = Op.getValueType();
4488   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4489 
4490   SDValue Lo, Hi;
4491   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4492 
4493   SDLoc SL(Op);
4494   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4495                              Op->getFlags());
4496   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4497                              Op->getFlags());
4498 
4499   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4500 }
4501 
4502 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4503 // wider vector type is legal.
4504 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4505                                               SelectionDAG &DAG) const {
4506   unsigned Opc = Op.getOpcode();
4507   EVT VT = Op.getValueType();
4508   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4509          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4510          VT == MVT::v16f32 || VT == MVT::v32f32);
4511 
4512   SDValue Lo0, Hi0;
4513   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4514   SDValue Lo1, Hi1;
4515   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4516 
4517   SDLoc SL(Op);
4518 
4519   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4520                              Op->getFlags());
4521   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4522                              Op->getFlags());
4523 
4524   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4525 }
4526 
4527 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4528                                               SelectionDAG &DAG) const {
4529   unsigned Opc = Op.getOpcode();
4530   EVT VT = Op.getValueType();
4531   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4532          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4533          VT == MVT::v16f32 || VT == MVT::v32f32);
4534 
4535   SDValue Lo0, Hi0;
4536   SDValue Op0 = Op.getOperand(0);
4537   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4538                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4539                          : std::make_pair(Op0, Op0);
4540   SDValue Lo1, Hi1;
4541   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4542   SDValue Lo2, Hi2;
4543   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4544 
4545   SDLoc SL(Op);
4546   auto ResVT = DAG.GetSplitDestVTs(VT);
4547 
4548   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4549                              Op->getFlags());
4550   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4551                              Op->getFlags());
4552 
4553   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4554 }
4555 
4556 
4557 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4558   switch (Op.getOpcode()) {
4559   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4560   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4561   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4562   case ISD::LOAD: {
4563     SDValue Result = LowerLOAD(Op, DAG);
4564     assert((!Result.getNode() ||
4565             Result.getNode()->getNumValues() == 2) &&
4566            "Load should return a value and a chain");
4567     return Result;
4568   }
4569 
4570   case ISD::FSIN:
4571   case ISD::FCOS:
4572     return LowerTrig(Op, DAG);
4573   case ISD::SELECT: return LowerSELECT(Op, DAG);
4574   case ISD::FDIV: return LowerFDIV(Op, DAG);
4575   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4576   case ISD::STORE: return LowerSTORE(Op, DAG);
4577   case ISD::GlobalAddress: {
4578     MachineFunction &MF = DAG.getMachineFunction();
4579     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4580     return LowerGlobalAddress(MFI, Op, DAG);
4581   }
4582   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4583   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4584   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4585   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4586   case ISD::INSERT_SUBVECTOR:
4587     return lowerINSERT_SUBVECTOR(Op, DAG);
4588   case ISD::INSERT_VECTOR_ELT:
4589     return lowerINSERT_VECTOR_ELT(Op, DAG);
4590   case ISD::EXTRACT_VECTOR_ELT:
4591     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4592   case ISD::VECTOR_SHUFFLE:
4593     return lowerVECTOR_SHUFFLE(Op, DAG);
4594   case ISD::SCALAR_TO_VECTOR:
4595     return lowerSCALAR_TO_VECTOR(Op, DAG);
4596   case ISD::BUILD_VECTOR:
4597     return lowerBUILD_VECTOR(Op, DAG);
4598   case ISD::FP_ROUND:
4599     return lowerFP_ROUND(Op, DAG);
4600   case ISD::FPTRUNC_ROUND: {
4601     unsigned Opc;
4602     SDLoc DL(Op);
4603 
4604     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4605       return SDValue();
4606 
4607     // Get the rounding mode from the last operand
4608     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4609     if (RoundMode == (int)RoundingMode::TowardPositive)
4610       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4611     else if (RoundMode == (int)RoundingMode::TowardNegative)
4612       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4613     else
4614       return SDValue();
4615 
4616     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4617   }
4618   case ISD::TRAP:
4619     return lowerTRAP(Op, DAG);
4620   case ISD::DEBUGTRAP:
4621     return lowerDEBUGTRAP(Op, DAG);
4622   case ISD::FABS:
4623   case ISD::FNEG:
4624   case ISD::FCANONICALIZE:
4625   case ISD::BSWAP:
4626     return splitUnaryVectorOp(Op, DAG);
4627   case ISD::FMINNUM:
4628   case ISD::FMAXNUM:
4629     return lowerFMINNUM_FMAXNUM(Op, DAG);
4630   case ISD::FMA:
4631     return splitTernaryVectorOp(Op, DAG);
4632   case ISD::FP_TO_SINT:
4633   case ISD::FP_TO_UINT:
4634     return LowerFP_TO_INT(Op, DAG);
4635   case ISD::SHL:
4636   case ISD::SRA:
4637   case ISD::SRL:
4638   case ISD::ADD:
4639   case ISD::SUB:
4640   case ISD::MUL:
4641   case ISD::SMIN:
4642   case ISD::SMAX:
4643   case ISD::UMIN:
4644   case ISD::UMAX:
4645   case ISD::FADD:
4646   case ISD::FMUL:
4647   case ISD::FMINNUM_IEEE:
4648   case ISD::FMAXNUM_IEEE:
4649   case ISD::UADDSAT:
4650   case ISD::USUBSAT:
4651   case ISD::SADDSAT:
4652   case ISD::SSUBSAT:
4653     return splitBinaryVectorOp(Op, DAG);
4654   case ISD::SMULO:
4655   case ISD::UMULO:
4656     return lowerXMULO(Op, DAG);
4657   case ISD::SMUL_LOHI:
4658   case ISD::UMUL_LOHI:
4659     return lowerXMUL_LOHI(Op, DAG);
4660   case ISD::DYNAMIC_STACKALLOC:
4661     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4662   }
4663   return SDValue();
4664 }
4665 
4666 // Used for D16: Casts the result of an instruction into the right vector,
4667 // packs values if loads return unpacked values.
4668 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4669                                        const SDLoc &DL,
4670                                        SelectionDAG &DAG, bool Unpacked) {
4671   if (!LoadVT.isVector())
4672     return Result;
4673 
4674   // Cast back to the original packed type or to a larger type that is a
4675   // multiple of 32 bit for D16. Widening the return type is a required for
4676   // legalization.
4677   EVT FittingLoadVT = LoadVT;
4678   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4679     FittingLoadVT =
4680         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4681                          LoadVT.getVectorNumElements() + 1);
4682   }
4683 
4684   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4685     // Truncate to v2i16/v4i16.
4686     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4687 
4688     // Workaround legalizer not scalarizing truncate after vector op
4689     // legalization but not creating intermediate vector trunc.
4690     SmallVector<SDValue, 4> Elts;
4691     DAG.ExtractVectorElements(Result, Elts);
4692     for (SDValue &Elt : Elts)
4693       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4694 
4695     // Pad illegal v1i16/v3fi6 to v4i16
4696     if ((LoadVT.getVectorNumElements() % 2) == 1)
4697       Elts.push_back(DAG.getUNDEF(MVT::i16));
4698 
4699     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4700 
4701     // Bitcast to original type (v2f16/v4f16).
4702     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4703   }
4704 
4705   // Cast back to the original packed type.
4706   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4707 }
4708 
4709 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4710                                               MemSDNode *M,
4711                                               SelectionDAG &DAG,
4712                                               ArrayRef<SDValue> Ops,
4713                                               bool IsIntrinsic) const {
4714   SDLoc DL(M);
4715 
4716   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4717   EVT LoadVT = M->getValueType(0);
4718 
4719   EVT EquivLoadVT = LoadVT;
4720   if (LoadVT.isVector()) {
4721     if (Unpacked) {
4722       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4723                                      LoadVT.getVectorNumElements());
4724     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4725       // Widen v3f16 to legal type
4726       EquivLoadVT =
4727           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4728                            LoadVT.getVectorNumElements() + 1);
4729     }
4730   }
4731 
4732   // Change from v4f16/v2f16 to EquivLoadVT.
4733   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4734 
4735   SDValue Load
4736     = DAG.getMemIntrinsicNode(
4737       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4738       VTList, Ops, M->getMemoryVT(),
4739       M->getMemOperand());
4740 
4741   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4742 
4743   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4744 }
4745 
4746 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4747                                              SelectionDAG &DAG,
4748                                              ArrayRef<SDValue> Ops) const {
4749   SDLoc DL(M);
4750   EVT LoadVT = M->getValueType(0);
4751   EVT EltType = LoadVT.getScalarType();
4752   EVT IntVT = LoadVT.changeTypeToInteger();
4753 
4754   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4755 
4756   unsigned Opc =
4757       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4758 
4759   if (IsD16) {
4760     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4761   }
4762 
4763   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4764   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4765     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4766 
4767   if (isTypeLegal(LoadVT)) {
4768     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4769                                M->getMemOperand(), DAG);
4770   }
4771 
4772   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4773   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4774   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4775                                         M->getMemOperand(), DAG);
4776   return DAG.getMergeValues(
4777       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4778       DL);
4779 }
4780 
4781 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4782                                   SDNode *N, SelectionDAG &DAG) {
4783   EVT VT = N->getValueType(0);
4784   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4785   unsigned CondCode = CD->getZExtValue();
4786   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4787     return DAG.getUNDEF(VT);
4788 
4789   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4790 
4791   SDValue LHS = N->getOperand(1);
4792   SDValue RHS = N->getOperand(2);
4793 
4794   SDLoc DL(N);
4795 
4796   EVT CmpVT = LHS.getValueType();
4797   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4798     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4799       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4800     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4801     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4802   }
4803 
4804   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4805 
4806   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4807   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4808 
4809   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4810                               DAG.getCondCode(CCOpcode));
4811   if (VT.bitsEq(CCVT))
4812     return SetCC;
4813   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4814 }
4815 
4816 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4817                                   SDNode *N, SelectionDAG &DAG) {
4818   EVT VT = N->getValueType(0);
4819   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4820 
4821   unsigned CondCode = CD->getZExtValue();
4822   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4823     return DAG.getUNDEF(VT);
4824 
4825   SDValue Src0 = N->getOperand(1);
4826   SDValue Src1 = N->getOperand(2);
4827   EVT CmpVT = Src0.getValueType();
4828   SDLoc SL(N);
4829 
4830   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4831     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4832     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4833   }
4834 
4835   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4836   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4837   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4838   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4839   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4840                               Src1, DAG.getCondCode(CCOpcode));
4841   if (VT.bitsEq(CCVT))
4842     return SetCC;
4843   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4844 }
4845 
4846 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4847                                     SelectionDAG &DAG) {
4848   EVT VT = N->getValueType(0);
4849   SDValue Src = N->getOperand(1);
4850   SDLoc SL(N);
4851 
4852   if (Src.getOpcode() == ISD::SETCC) {
4853     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4854     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4855                        Src.getOperand(1), Src.getOperand(2));
4856   }
4857   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4858     // (ballot 0) -> 0
4859     if (Arg->isZero())
4860       return DAG.getConstant(0, SL, VT);
4861 
4862     // (ballot 1) -> EXEC/EXEC_LO
4863     if (Arg->isOne()) {
4864       Register Exec;
4865       if (VT.getScalarSizeInBits() == 32)
4866         Exec = AMDGPU::EXEC_LO;
4867       else if (VT.getScalarSizeInBits() == 64)
4868         Exec = AMDGPU::EXEC;
4869       else
4870         return SDValue();
4871 
4872       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4873     }
4874   }
4875 
4876   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4877   // ISD::SETNE)
4878   return DAG.getNode(
4879       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4880       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4881 }
4882 
4883 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4884                                           SmallVectorImpl<SDValue> &Results,
4885                                           SelectionDAG &DAG) const {
4886   switch (N->getOpcode()) {
4887   case ISD::INSERT_VECTOR_ELT: {
4888     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4889       Results.push_back(Res);
4890     return;
4891   }
4892   case ISD::EXTRACT_VECTOR_ELT: {
4893     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4894       Results.push_back(Res);
4895     return;
4896   }
4897   case ISD::INTRINSIC_WO_CHAIN: {
4898     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4899     switch (IID) {
4900     case Intrinsic::amdgcn_cvt_pkrtz: {
4901       SDValue Src0 = N->getOperand(1);
4902       SDValue Src1 = N->getOperand(2);
4903       SDLoc SL(N);
4904       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4905                                 Src0, Src1);
4906       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4907       return;
4908     }
4909     case Intrinsic::amdgcn_cvt_pknorm_i16:
4910     case Intrinsic::amdgcn_cvt_pknorm_u16:
4911     case Intrinsic::amdgcn_cvt_pk_i16:
4912     case Intrinsic::amdgcn_cvt_pk_u16: {
4913       SDValue Src0 = N->getOperand(1);
4914       SDValue Src1 = N->getOperand(2);
4915       SDLoc SL(N);
4916       unsigned Opcode;
4917 
4918       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4919         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4920       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4921         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4922       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4923         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4924       else
4925         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4926 
4927       EVT VT = N->getValueType(0);
4928       if (isTypeLegal(VT))
4929         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4930       else {
4931         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4932         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4933       }
4934       return;
4935     }
4936     }
4937     break;
4938   }
4939   case ISD::INTRINSIC_W_CHAIN: {
4940     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4941       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4942         // FIXME: Hacky
4943         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4944           Results.push_back(Res.getOperand(I));
4945         }
4946       } else {
4947         Results.push_back(Res);
4948         Results.push_back(Res.getValue(1));
4949       }
4950       return;
4951     }
4952 
4953     break;
4954   }
4955   case ISD::SELECT: {
4956     SDLoc SL(N);
4957     EVT VT = N->getValueType(0);
4958     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4959     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4960     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4961 
4962     EVT SelectVT = NewVT;
4963     if (NewVT.bitsLT(MVT::i32)) {
4964       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4965       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4966       SelectVT = MVT::i32;
4967     }
4968 
4969     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4970                                     N->getOperand(0), LHS, RHS);
4971 
4972     if (NewVT != SelectVT)
4973       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4974     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4975     return;
4976   }
4977   case ISD::FNEG: {
4978     if (N->getValueType(0) != MVT::v2f16)
4979       break;
4980 
4981     SDLoc SL(N);
4982     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4983 
4984     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4985                              BC,
4986                              DAG.getConstant(0x80008000, SL, MVT::i32));
4987     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4988     return;
4989   }
4990   case ISD::FABS: {
4991     if (N->getValueType(0) != MVT::v2f16)
4992       break;
4993 
4994     SDLoc SL(N);
4995     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4996 
4997     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4998                              BC,
4999                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5000     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5001     return;
5002   }
5003   default:
5004     break;
5005   }
5006 }
5007 
5008 /// Helper function for LowerBRCOND
5009 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5010 
5011   SDNode *Parent = Value.getNode();
5012   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5013        I != E; ++I) {
5014 
5015     if (I.getUse().get() != Value)
5016       continue;
5017 
5018     if (I->getOpcode() == Opcode)
5019       return *I;
5020   }
5021   return nullptr;
5022 }
5023 
5024 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5025   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5026     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5027     case Intrinsic::amdgcn_if:
5028       return AMDGPUISD::IF;
5029     case Intrinsic::amdgcn_else:
5030       return AMDGPUISD::ELSE;
5031     case Intrinsic::amdgcn_loop:
5032       return AMDGPUISD::LOOP;
5033     case Intrinsic::amdgcn_end_cf:
5034       llvm_unreachable("should not occur");
5035     default:
5036       return 0;
5037     }
5038   }
5039 
5040   // break, if_break, else_break are all only used as inputs to loop, not
5041   // directly as branch conditions.
5042   return 0;
5043 }
5044 
5045 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5046   const Triple &TT = getTargetMachine().getTargetTriple();
5047   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5048           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5049          AMDGPU::shouldEmitConstantsToTextSection(TT);
5050 }
5051 
5052 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5053   // FIXME: Either avoid relying on address space here or change the default
5054   // address space for functions to avoid the explicit check.
5055   return (GV->getValueType()->isFunctionTy() ||
5056           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5057          !shouldEmitFixup(GV) &&
5058          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5059 }
5060 
5061 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5062   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5063 }
5064 
5065 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5066   if (!GV->hasExternalLinkage())
5067     return true;
5068 
5069   const auto OS = getTargetMachine().getTargetTriple().getOS();
5070   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5071 }
5072 
5073 /// This transforms the control flow intrinsics to get the branch destination as
5074 /// last parameter, also switches branch target with BR if the need arise
5075 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5076                                       SelectionDAG &DAG) const {
5077   SDLoc DL(BRCOND);
5078 
5079   SDNode *Intr = BRCOND.getOperand(1).getNode();
5080   SDValue Target = BRCOND.getOperand(2);
5081   SDNode *BR = nullptr;
5082   SDNode *SetCC = nullptr;
5083 
5084   if (Intr->getOpcode() == ISD::SETCC) {
5085     // As long as we negate the condition everything is fine
5086     SetCC = Intr;
5087     Intr = SetCC->getOperand(0).getNode();
5088 
5089   } else {
5090     // Get the target from BR if we don't negate the condition
5091     BR = findUser(BRCOND, ISD::BR);
5092     assert(BR && "brcond missing unconditional branch user");
5093     Target = BR->getOperand(1);
5094   }
5095 
5096   unsigned CFNode = isCFIntrinsic(Intr);
5097   if (CFNode == 0) {
5098     // This is a uniform branch so we don't need to legalize.
5099     return BRCOND;
5100   }
5101 
5102   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5103                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5104 
5105   assert(!SetCC ||
5106         (SetCC->getConstantOperandVal(1) == 1 &&
5107          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5108                                                              ISD::SETNE));
5109 
5110   // operands of the new intrinsic call
5111   SmallVector<SDValue, 4> Ops;
5112   if (HaveChain)
5113     Ops.push_back(BRCOND.getOperand(0));
5114 
5115   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5116   Ops.push_back(Target);
5117 
5118   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5119 
5120   // build the new intrinsic call
5121   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5122 
5123   if (!HaveChain) {
5124     SDValue Ops[] =  {
5125       SDValue(Result, 0),
5126       BRCOND.getOperand(0)
5127     };
5128 
5129     Result = DAG.getMergeValues(Ops, DL).getNode();
5130   }
5131 
5132   if (BR) {
5133     // Give the branch instruction our target
5134     SDValue Ops[] = {
5135       BR->getOperand(0),
5136       BRCOND.getOperand(2)
5137     };
5138     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5139     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5140   }
5141 
5142   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5143 
5144   // Copy the intrinsic results to registers
5145   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5146     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5147     if (!CopyToReg)
5148       continue;
5149 
5150     Chain = DAG.getCopyToReg(
5151       Chain, DL,
5152       CopyToReg->getOperand(1),
5153       SDValue(Result, i - 1),
5154       SDValue());
5155 
5156     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5157   }
5158 
5159   // Remove the old intrinsic from the chain
5160   DAG.ReplaceAllUsesOfValueWith(
5161     SDValue(Intr, Intr->getNumValues() - 1),
5162     Intr->getOperand(0));
5163 
5164   return Chain;
5165 }
5166 
5167 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5168                                           SelectionDAG &DAG) const {
5169   MVT VT = Op.getSimpleValueType();
5170   SDLoc DL(Op);
5171   // Checking the depth
5172   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5173     return DAG.getConstant(0, DL, VT);
5174 
5175   MachineFunction &MF = DAG.getMachineFunction();
5176   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5177   // Check for kernel and shader functions
5178   if (Info->isEntryFunction())
5179     return DAG.getConstant(0, DL, VT);
5180 
5181   MachineFrameInfo &MFI = MF.getFrameInfo();
5182   // There is a call to @llvm.returnaddress in this function
5183   MFI.setReturnAddressIsTaken(true);
5184 
5185   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5186   // Get the return address reg and mark it as an implicit live-in
5187   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5188 
5189   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5190 }
5191 
5192 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5193                                             SDValue Op,
5194                                             const SDLoc &DL,
5195                                             EVT VT) const {
5196   return Op.getValueType().bitsLE(VT) ?
5197       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5198     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5199                 DAG.getTargetConstant(0, DL, MVT::i32));
5200 }
5201 
5202 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5203   assert(Op.getValueType() == MVT::f16 &&
5204          "Do not know how to custom lower FP_ROUND for non-f16 type");
5205 
5206   SDValue Src = Op.getOperand(0);
5207   EVT SrcVT = Src.getValueType();
5208   if (SrcVT != MVT::f64)
5209     return Op;
5210 
5211   SDLoc DL(Op);
5212 
5213   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5214   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5215   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5216 }
5217 
5218 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5219                                                SelectionDAG &DAG) const {
5220   EVT VT = Op.getValueType();
5221   const MachineFunction &MF = DAG.getMachineFunction();
5222   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5223   bool IsIEEEMode = Info->getMode().IEEE;
5224 
5225   // FIXME: Assert during selection that this is only selected for
5226   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5227   // mode functions, but this happens to be OK since it's only done in cases
5228   // where there is known no sNaN.
5229   if (IsIEEEMode)
5230     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5231 
5232   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5233     return splitBinaryVectorOp(Op, DAG);
5234   return Op;
5235 }
5236 
5237 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5238   EVT VT = Op.getValueType();
5239   SDLoc SL(Op);
5240   SDValue LHS = Op.getOperand(0);
5241   SDValue RHS = Op.getOperand(1);
5242   bool isSigned = Op.getOpcode() == ISD::SMULO;
5243 
5244   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5245     const APInt &C = RHSC->getAPIntValue();
5246     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5247     if (C.isPowerOf2()) {
5248       // smulo(x, signed_min) is same as umulo(x, signed_min).
5249       bool UseArithShift = isSigned && !C.isMinSignedValue();
5250       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5251       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5252       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5253           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5254                       SL, VT, Result, ShiftAmt),
5255           LHS, ISD::SETNE);
5256       return DAG.getMergeValues({ Result, Overflow }, SL);
5257     }
5258   }
5259 
5260   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5261   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5262                             SL, VT, LHS, RHS);
5263 
5264   SDValue Sign = isSigned
5265     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5266                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5267     : DAG.getConstant(0, SL, VT);
5268   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5269 
5270   return DAG.getMergeValues({ Result, Overflow }, SL);
5271 }
5272 
5273 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5274   if (Op->isDivergent()) {
5275     // Select to V_MAD_[IU]64_[IU]32.
5276     return Op;
5277   }
5278   if (Subtarget->hasSMulHi()) {
5279     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5280     return SDValue();
5281   }
5282   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5283   // calculate the high part, so we might as well do the whole thing with
5284   // V_MAD_[IU]64_[IU]32.
5285   return Op;
5286 }
5287 
5288 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5289   if (!Subtarget->isTrapHandlerEnabled() ||
5290       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5291     return lowerTrapEndpgm(Op, DAG);
5292 
5293   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5294     switch (*HsaAbiVer) {
5295     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5296     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5297       return lowerTrapHsaQueuePtr(Op, DAG);
5298     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5299     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5300       return Subtarget->supportsGetDoorbellID() ?
5301           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5302     }
5303   }
5304 
5305   llvm_unreachable("Unknown trap handler");
5306 }
5307 
5308 SDValue SITargetLowering::lowerTrapEndpgm(
5309     SDValue Op, SelectionDAG &DAG) const {
5310   SDLoc SL(Op);
5311   SDValue Chain = Op.getOperand(0);
5312   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5313 }
5314 
5315 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5316     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5317   MachineFunction &MF = DAG.getMachineFunction();
5318   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5319   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5320   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5321   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5322                      MachineMemOperand::MODereferenceable |
5323                          MachineMemOperand::MOInvariant);
5324 }
5325 
5326 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5327     SDValue Op, SelectionDAG &DAG) const {
5328   SDLoc SL(Op);
5329   SDValue Chain = Op.getOperand(0);
5330 
5331   SDValue QueuePtr;
5332   // For code object version 5, QueuePtr is passed through implicit kernarg.
5333   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5334     QueuePtr =
5335         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5336   } else {
5337     MachineFunction &MF = DAG.getMachineFunction();
5338     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5339     Register UserSGPR = Info->getQueuePtrUserSGPR();
5340 
5341     if (UserSGPR == AMDGPU::NoRegister) {
5342       // We probably are in a function incorrectly marked with
5343       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5344       // trap, so just use a null pointer.
5345       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5346     } else {
5347       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5348                                       MVT::i64);
5349     }
5350   }
5351 
5352   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5353   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5354                                    QueuePtr, SDValue());
5355 
5356   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5357   SDValue Ops[] = {
5358     ToReg,
5359     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5360     SGPR01,
5361     ToReg.getValue(1)
5362   };
5363   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5364 }
5365 
5366 SDValue SITargetLowering::lowerTrapHsa(
5367     SDValue Op, SelectionDAG &DAG) const {
5368   SDLoc SL(Op);
5369   SDValue Chain = Op.getOperand(0);
5370 
5371   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5372   SDValue Ops[] = {
5373     Chain,
5374     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5375   };
5376   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5377 }
5378 
5379 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5380   SDLoc SL(Op);
5381   SDValue Chain = Op.getOperand(0);
5382   MachineFunction &MF = DAG.getMachineFunction();
5383 
5384   if (!Subtarget->isTrapHandlerEnabled() ||
5385       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5386     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5387                                      "debugtrap handler not supported",
5388                                      Op.getDebugLoc(),
5389                                      DS_Warning);
5390     LLVMContext &Ctx = MF.getFunction().getContext();
5391     Ctx.diagnose(NoTrap);
5392     return Chain;
5393   }
5394 
5395   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5396   SDValue Ops[] = {
5397     Chain,
5398     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5399   };
5400   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5401 }
5402 
5403 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5404                                              SelectionDAG &DAG) const {
5405   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5406   if (Subtarget->hasApertureRegs()) {
5407     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5408         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5409         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5410     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5411         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5412         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5413     unsigned Encoding =
5414         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5415         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5416         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5417 
5418     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5419     SDValue ApertureReg = SDValue(
5420         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5421     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5422     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5423   }
5424 
5425   // For code object version 5, private_base and shared_base are passed through
5426   // implicit kernargs.
5427   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5428     ImplicitParameter Param =
5429         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5430     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5431   }
5432 
5433   MachineFunction &MF = DAG.getMachineFunction();
5434   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5435   Register UserSGPR = Info->getQueuePtrUserSGPR();
5436   if (UserSGPR == AMDGPU::NoRegister) {
5437     // We probably are in a function incorrectly marked with
5438     // amdgpu-no-queue-ptr. This is undefined.
5439     return DAG.getUNDEF(MVT::i32);
5440   }
5441 
5442   SDValue QueuePtr = CreateLiveInRegister(
5443     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5444 
5445   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5446   // private_segment_aperture_base_hi.
5447   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5448 
5449   SDValue Ptr =
5450       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5451 
5452   // TODO: Use custom target PseudoSourceValue.
5453   // TODO: We should use the value from the IR intrinsic call, but it might not
5454   // be available and how do we get it?
5455   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5456   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5457                      commonAlignment(Align(64), StructOffset),
5458                      MachineMemOperand::MODereferenceable |
5459                          MachineMemOperand::MOInvariant);
5460 }
5461 
5462 /// Return true if the value is a known valid address, such that a null check is
5463 /// not necessary.
5464 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5465                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5466   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5467       isa<BasicBlockSDNode>(Val))
5468     return true;
5469 
5470   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5471     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5472 
5473   // TODO: Search through arithmetic, handle arguments and loads
5474   // marked nonnull.
5475   return false;
5476 }
5477 
5478 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5479                                              SelectionDAG &DAG) const {
5480   SDLoc SL(Op);
5481   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5482 
5483   SDValue Src = ASC->getOperand(0);
5484   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5485   unsigned SrcAS = ASC->getSrcAddressSpace();
5486 
5487   const AMDGPUTargetMachine &TM =
5488     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5489 
5490   // flat -> local/private
5491   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5492     unsigned DestAS = ASC->getDestAddressSpace();
5493 
5494     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5495         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5496       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5497 
5498       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5499         return Ptr;
5500 
5501       unsigned NullVal = TM.getNullPointerValue(DestAS);
5502       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5503       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5504 
5505       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5506                          SegmentNullPtr);
5507     }
5508   }
5509 
5510   // local/private -> flat
5511   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5512     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5513         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5514 
5515       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5516       SDValue CvtPtr =
5517           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5518       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5519 
5520       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5521         return CvtPtr;
5522 
5523       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5524       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5525 
5526       SDValue NonNull
5527         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5528 
5529       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5530                          FlatNullPtr);
5531     }
5532   }
5533 
5534   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5535       Op.getValueType() == MVT::i64) {
5536     const SIMachineFunctionInfo *Info =
5537         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5538     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5539     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5540     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5541   }
5542 
5543   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5544       Src.getValueType() == MVT::i64)
5545     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5546 
5547   // global <-> flat are no-ops and never emitted.
5548 
5549   const MachineFunction &MF = DAG.getMachineFunction();
5550   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5551     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5552   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5553 
5554   return DAG.getUNDEF(ASC->getValueType(0));
5555 }
5556 
5557 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5558 // the small vector and inserting them into the big vector. That is better than
5559 // the default expansion of doing it via a stack slot. Even though the use of
5560 // the stack slot would be optimized away afterwards, the stack slot itself
5561 // remains.
5562 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5563                                                 SelectionDAG &DAG) const {
5564   SDValue Vec = Op.getOperand(0);
5565   SDValue Ins = Op.getOperand(1);
5566   SDValue Idx = Op.getOperand(2);
5567   EVT VecVT = Vec.getValueType();
5568   EVT InsVT = Ins.getValueType();
5569   EVT EltVT = VecVT.getVectorElementType();
5570   unsigned InsNumElts = InsVT.getVectorNumElements();
5571   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5572   SDLoc SL(Op);
5573 
5574   for (unsigned I = 0; I != InsNumElts; ++I) {
5575     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5576                               DAG.getConstant(I, SL, MVT::i32));
5577     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5578                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5579   }
5580   return Vec;
5581 }
5582 
5583 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5584                                                  SelectionDAG &DAG) const {
5585   SDValue Vec = Op.getOperand(0);
5586   SDValue InsVal = Op.getOperand(1);
5587   SDValue Idx = Op.getOperand(2);
5588   EVT VecVT = Vec.getValueType();
5589   EVT EltVT = VecVT.getVectorElementType();
5590   unsigned VecSize = VecVT.getSizeInBits();
5591   unsigned EltSize = EltVT.getSizeInBits();
5592   SDLoc SL(Op);
5593 
5594   // Specially handle the case of v4i16 with static indexing.
5595   unsigned NumElts = VecVT.getVectorNumElements();
5596   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5597   if (NumElts == 4 && EltSize == 16 && KIdx) {
5598     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5599 
5600     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5601                                  DAG.getConstant(0, SL, MVT::i32));
5602     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5603                                  DAG.getConstant(1, SL, MVT::i32));
5604 
5605     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5606     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5607 
5608     unsigned Idx = KIdx->getZExtValue();
5609     bool InsertLo = Idx < 2;
5610     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5611       InsertLo ? LoVec : HiVec,
5612       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5613       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5614 
5615     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5616 
5617     SDValue Concat = InsertLo ?
5618       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5619       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5620 
5621     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5622   }
5623 
5624   // Static indexing does not lower to stack access, and hence there is no need
5625   // for special custom lowering to avoid stack access.
5626   if (isa<ConstantSDNode>(Idx))
5627     return SDValue();
5628 
5629   // Avoid stack access for dynamic indexing by custom lowering to
5630   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5631 
5632   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5633 
5634   MVT IntVT = MVT::getIntegerVT(VecSize);
5635 
5636   // Convert vector index to bit-index and get the required bit mask.
5637   assert(isPowerOf2_32(EltSize));
5638   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5639   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5640   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5641                             DAG.getConstant(0xffff, SL, IntVT),
5642                             ScaledIdx);
5643 
5644   // 1. Create a congruent vector with the target value in each element.
5645   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5646                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5647 
5648   // 2. Mask off all other indicies except the required index within (1).
5649   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5650 
5651   // 3. Mask off the required index within the target vector.
5652   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5653   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5654                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5655 
5656   // 4. Get (2) and (3) ORed into the target vector.
5657   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5658 
5659   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5660 }
5661 
5662 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5663                                                   SelectionDAG &DAG) const {
5664   SDLoc SL(Op);
5665 
5666   EVT ResultVT = Op.getValueType();
5667   SDValue Vec = Op.getOperand(0);
5668   SDValue Idx = Op.getOperand(1);
5669   EVT VecVT = Vec.getValueType();
5670   unsigned VecSize = VecVT.getSizeInBits();
5671   EVT EltVT = VecVT.getVectorElementType();
5672 
5673   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5674 
5675   // Make sure we do any optimizations that will make it easier to fold
5676   // source modifiers before obscuring it with bit operations.
5677 
5678   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5679   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5680     return Combined;
5681 
5682   if (VecSize == 128) {
5683     SDValue Lo, Hi;
5684     EVT LoVT, HiVT;
5685     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5686     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5687     Lo =
5688         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5689                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5690     Hi =
5691         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5692                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5693     EVT IdxVT = Idx.getValueType();
5694     unsigned NElem = VecVT.getVectorNumElements();
5695     assert(isPowerOf2_32(NElem));
5696     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5697     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5698     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5699     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5700   }
5701 
5702   assert(VecSize <= 64);
5703 
5704   MVT IntVT = MVT::getIntegerVT(VecSize);
5705 
5706   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5707   SDValue VecBC = peekThroughBitcasts(Vec);
5708   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5709     SDValue Src = VecBC.getOperand(0);
5710     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5711     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5712   }
5713 
5714   unsigned EltSize = EltVT.getSizeInBits();
5715   assert(isPowerOf2_32(EltSize));
5716 
5717   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5718 
5719   // Convert vector index to bit-index (* EltSize)
5720   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5721 
5722   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5723   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5724 
5725   if (ResultVT == MVT::f16) {
5726     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5727     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5728   }
5729 
5730   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5731 }
5732 
5733 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5734   assert(Elt % 2 == 0);
5735   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5736 }
5737 
5738 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5739                                               SelectionDAG &DAG) const {
5740   SDLoc SL(Op);
5741   EVT ResultVT = Op.getValueType();
5742   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5743 
5744   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5745   EVT EltVT = PackVT.getVectorElementType();
5746   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5747 
5748   // vector_shuffle <0,1,6,7> lhs, rhs
5749   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5750   //
5751   // vector_shuffle <6,7,2,3> lhs, rhs
5752   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5753   //
5754   // vector_shuffle <6,7,0,1> lhs, rhs
5755   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5756 
5757   // Avoid scalarizing when both halves are reading from consecutive elements.
5758   SmallVector<SDValue, 4> Pieces;
5759   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5760     if (elementPairIsContiguous(SVN->getMask(), I)) {
5761       const int Idx = SVN->getMaskElt(I);
5762       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5763       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5764       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5765                                     PackVT, SVN->getOperand(VecIdx),
5766                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5767       Pieces.push_back(SubVec);
5768     } else {
5769       const int Idx0 = SVN->getMaskElt(I);
5770       const int Idx1 = SVN->getMaskElt(I + 1);
5771       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5772       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5773       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5774       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5775 
5776       SDValue Vec0 = SVN->getOperand(VecIdx0);
5777       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5778                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5779 
5780       SDValue Vec1 = SVN->getOperand(VecIdx1);
5781       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5782                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5783       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5784     }
5785   }
5786 
5787   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5788 }
5789 
5790 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5791                                                 SelectionDAG &DAG) const {
5792   SDValue SVal = Op.getOperand(0);
5793   EVT ResultVT = Op.getValueType();
5794   EVT SValVT = SVal.getValueType();
5795   SDValue UndefVal = DAG.getUNDEF(SValVT);
5796   SDLoc SL(Op);
5797 
5798   SmallVector<SDValue, 8> VElts;
5799   VElts.push_back(SVal);
5800   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5801     VElts.push_back(UndefVal);
5802 
5803   return DAG.getBuildVector(ResultVT, SL, VElts);
5804 }
5805 
5806 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5807                                             SelectionDAG &DAG) const {
5808   SDLoc SL(Op);
5809   EVT VT = Op.getValueType();
5810 
5811   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5812       VT == MVT::v8i16 || VT == MVT::v8f16) {
5813     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5814                                   VT.getVectorNumElements() / 2);
5815     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5816 
5817     // Turn into pair of packed build_vectors.
5818     // TODO: Special case for constants that can be materialized with s_mov_b64.
5819     SmallVector<SDValue, 4> LoOps, HiOps;
5820     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5821       LoOps.push_back(Op.getOperand(I));
5822       HiOps.push_back(Op.getOperand(I + E));
5823     }
5824     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5825     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5826 
5827     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5828     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5829 
5830     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5831                                        { CastLo, CastHi });
5832     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5833   }
5834 
5835   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5836   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5837 
5838   SDValue Lo = Op.getOperand(0);
5839   SDValue Hi = Op.getOperand(1);
5840 
5841   // Avoid adding defined bits with the zero_extend.
5842   if (Hi.isUndef()) {
5843     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5844     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5845     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5846   }
5847 
5848   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5849   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5850 
5851   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5852                               DAG.getConstant(16, SL, MVT::i32));
5853   if (Lo.isUndef())
5854     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5855 
5856   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5857   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5858 
5859   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5860   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5861 }
5862 
5863 bool
5864 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5865   // We can fold offsets for anything that doesn't require a GOT relocation.
5866   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5867           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5868           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5869          !shouldEmitGOTReloc(GA->getGlobal());
5870 }
5871 
5872 static SDValue
5873 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5874                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5875                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5876   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5877   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5878   // lowered to the following code sequence:
5879   //
5880   // For constant address space:
5881   //   s_getpc_b64 s[0:1]
5882   //   s_add_u32 s0, s0, $symbol
5883   //   s_addc_u32 s1, s1, 0
5884   //
5885   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5886   //   a fixup or relocation is emitted to replace $symbol with a literal
5887   //   constant, which is a pc-relative offset from the encoding of the $symbol
5888   //   operand to the global variable.
5889   //
5890   // For global address space:
5891   //   s_getpc_b64 s[0:1]
5892   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5893   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5894   //
5895   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5896   //   fixups or relocations are emitted to replace $symbol@*@lo and
5897   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5898   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5899   //   operand to the global variable.
5900   //
5901   // What we want here is an offset from the value returned by s_getpc
5902   // (which is the address of the s_add_u32 instruction) to the global
5903   // variable, but since the encoding of $symbol starts 4 bytes after the start
5904   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5905   // small. This requires us to add 4 to the global variable offset in order to
5906   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5907   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5908   // instruction.
5909   SDValue PtrLo =
5910       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5911   SDValue PtrHi;
5912   if (GAFlags == SIInstrInfo::MO_NONE) {
5913     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5914   } else {
5915     PtrHi =
5916         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5917   }
5918   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5919 }
5920 
5921 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5922                                              SDValue Op,
5923                                              SelectionDAG &DAG) const {
5924   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5925   SDLoc DL(GSD);
5926   EVT PtrVT = Op.getValueType();
5927 
5928   const GlobalValue *GV = GSD->getGlobal();
5929   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5930        shouldUseLDSConstAddress(GV)) ||
5931       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5932       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5933     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5934         GV->hasExternalLinkage()) {
5935       Type *Ty = GV->getValueType();
5936       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5937       // zero-sized type in other languages to declare the dynamic shared
5938       // memory which size is not known at the compile time. They will be
5939       // allocated by the runtime and placed directly after the static
5940       // allocated ones. They all share the same offset.
5941       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5942         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5943         // Adjust alignment for that dynamic shared memory array.
5944         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5945         return SDValue(
5946             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5947       }
5948     }
5949     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5950   }
5951 
5952   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5953     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5954                                             SIInstrInfo::MO_ABS32_LO);
5955     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5956   }
5957 
5958   if (shouldEmitFixup(GV))
5959     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5960   else if (shouldEmitPCReloc(GV))
5961     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5962                                    SIInstrInfo::MO_REL32);
5963 
5964   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5965                                             SIInstrInfo::MO_GOTPCREL32);
5966 
5967   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5968   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5969   const DataLayout &DataLayout = DAG.getDataLayout();
5970   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5971   MachinePointerInfo PtrInfo
5972     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5973 
5974   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5975                      MachineMemOperand::MODereferenceable |
5976                          MachineMemOperand::MOInvariant);
5977 }
5978 
5979 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5980                                    const SDLoc &DL, SDValue V) const {
5981   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5982   // the destination register.
5983   //
5984   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5985   // so we will end up with redundant moves to m0.
5986   //
5987   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5988 
5989   // A Null SDValue creates a glue result.
5990   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5991                                   V, Chain);
5992   return SDValue(M0, 0);
5993 }
5994 
5995 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5996                                                  SDValue Op,
5997                                                  MVT VT,
5998                                                  unsigned Offset) const {
5999   SDLoc SL(Op);
6000   SDValue Param = lowerKernargMemParameter(
6001       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6002   // The local size values will have the hi 16-bits as zero.
6003   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6004                      DAG.getValueType(VT));
6005 }
6006 
6007 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6008                                         EVT VT) {
6009   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6010                                       "non-hsa intrinsic with hsa target",
6011                                       DL.getDebugLoc());
6012   DAG.getContext()->diagnose(BadIntrin);
6013   return DAG.getUNDEF(VT);
6014 }
6015 
6016 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6017                                          EVT VT) {
6018   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6019                                       "intrinsic not supported on subtarget",
6020                                       DL.getDebugLoc());
6021   DAG.getContext()->diagnose(BadIntrin);
6022   return DAG.getUNDEF(VT);
6023 }
6024 
6025 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6026                                     ArrayRef<SDValue> Elts) {
6027   assert(!Elts.empty());
6028   MVT Type;
6029   unsigned NumElts = Elts.size();
6030 
6031   if (NumElts <= 8) {
6032     Type = MVT::getVectorVT(MVT::f32, NumElts);
6033   } else {
6034     assert(Elts.size() <= 16);
6035     Type = MVT::v16f32;
6036     NumElts = 16;
6037   }
6038 
6039   SmallVector<SDValue, 16> VecElts(NumElts);
6040   for (unsigned i = 0; i < Elts.size(); ++i) {
6041     SDValue Elt = Elts[i];
6042     if (Elt.getValueType() != MVT::f32)
6043       Elt = DAG.getBitcast(MVT::f32, Elt);
6044     VecElts[i] = Elt;
6045   }
6046   for (unsigned i = Elts.size(); i < NumElts; ++i)
6047     VecElts[i] = DAG.getUNDEF(MVT::f32);
6048 
6049   if (NumElts == 1)
6050     return VecElts[0];
6051   return DAG.getBuildVector(Type, DL, VecElts);
6052 }
6053 
6054 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6055                               SDValue Src, int ExtraElts) {
6056   EVT SrcVT = Src.getValueType();
6057 
6058   SmallVector<SDValue, 8> Elts;
6059 
6060   if (SrcVT.isVector())
6061     DAG.ExtractVectorElements(Src, Elts);
6062   else
6063     Elts.push_back(Src);
6064 
6065   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6066   while (ExtraElts--)
6067     Elts.push_back(Undef);
6068 
6069   return DAG.getBuildVector(CastVT, DL, Elts);
6070 }
6071 
6072 // Re-construct the required return value for a image load intrinsic.
6073 // This is more complicated due to the optional use TexFailCtrl which means the required
6074 // return type is an aggregate
6075 static SDValue constructRetValue(SelectionDAG &DAG,
6076                                  MachineSDNode *Result,
6077                                  ArrayRef<EVT> ResultTypes,
6078                                  bool IsTexFail, bool Unpacked, bool IsD16,
6079                                  int DMaskPop, int NumVDataDwords,
6080                                  const SDLoc &DL) {
6081   // Determine the required return type. This is the same regardless of IsTexFail flag
6082   EVT ReqRetVT = ResultTypes[0];
6083   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6084   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6085     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6086 
6087   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6088     DMaskPop : (DMaskPop + 1) / 2;
6089 
6090   MVT DataDwordVT = NumDataDwords == 1 ?
6091     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6092 
6093   MVT MaskPopVT = MaskPopDwords == 1 ?
6094     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6095 
6096   SDValue Data(Result, 0);
6097   SDValue TexFail;
6098 
6099   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6100     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6101     if (MaskPopVT.isVector()) {
6102       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6103                          SDValue(Result, 0), ZeroIdx);
6104     } else {
6105       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6106                          SDValue(Result, 0), ZeroIdx);
6107     }
6108   }
6109 
6110   if (DataDwordVT.isVector())
6111     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6112                           NumDataDwords - MaskPopDwords);
6113 
6114   if (IsD16)
6115     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6116 
6117   EVT LegalReqRetVT = ReqRetVT;
6118   if (!ReqRetVT.isVector()) {
6119     if (!Data.getValueType().isInteger())
6120       Data = DAG.getNode(ISD::BITCAST, DL,
6121                          Data.getValueType().changeTypeToInteger(), Data);
6122     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6123   } else {
6124     // We need to widen the return vector to a legal type
6125     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6126         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6127       LegalReqRetVT =
6128           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6129                            ReqRetVT.getVectorNumElements() + 1);
6130     }
6131   }
6132   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6133 
6134   if (IsTexFail) {
6135     TexFail =
6136         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6137                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6138 
6139     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6140   }
6141 
6142   if (Result->getNumValues() == 1)
6143     return Data;
6144 
6145   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6146 }
6147 
6148 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6149                          SDValue *LWE, bool &IsTexFail) {
6150   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6151 
6152   uint64_t Value = TexFailCtrlConst->getZExtValue();
6153   if (Value) {
6154     IsTexFail = true;
6155   }
6156 
6157   SDLoc DL(TexFailCtrlConst);
6158   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6159   Value &= ~(uint64_t)0x1;
6160   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6161   Value &= ~(uint64_t)0x2;
6162 
6163   return Value == 0;
6164 }
6165 
6166 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6167                                       MVT PackVectorVT,
6168                                       SmallVectorImpl<SDValue> &PackedAddrs,
6169                                       unsigned DimIdx, unsigned EndIdx,
6170                                       unsigned NumGradients) {
6171   SDLoc DL(Op);
6172   for (unsigned I = DimIdx; I < EndIdx; I++) {
6173     SDValue Addr = Op.getOperand(I);
6174 
6175     // Gradients are packed with undef for each coordinate.
6176     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6177     // 1D: undef,dx/dh; undef,dx/dv
6178     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6179     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6180     if (((I + 1) >= EndIdx) ||
6181         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6182                                          I == DimIdx + NumGradients - 1))) {
6183       if (Addr.getValueType() != MVT::i16)
6184         Addr = DAG.getBitcast(MVT::i16, Addr);
6185       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6186     } else {
6187       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6188       I++;
6189     }
6190     Addr = DAG.getBitcast(MVT::f32, Addr);
6191     PackedAddrs.push_back(Addr);
6192   }
6193 }
6194 
6195 SDValue SITargetLowering::lowerImage(SDValue Op,
6196                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6197                                      SelectionDAG &DAG, bool WithChain) const {
6198   SDLoc DL(Op);
6199   MachineFunction &MF = DAG.getMachineFunction();
6200   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6201   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6202       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6203   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6204   unsigned IntrOpcode = Intr->BaseOpcode;
6205   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6206 
6207   SmallVector<EVT, 3> ResultTypes(Op->values());
6208   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6209   bool IsD16 = false;
6210   bool IsG16 = false;
6211   bool IsA16 = false;
6212   SDValue VData;
6213   int NumVDataDwords;
6214   bool AdjustRetType = false;
6215 
6216   // Offset of intrinsic arguments
6217   const unsigned ArgOffset = WithChain ? 2 : 1;
6218 
6219   unsigned DMask;
6220   unsigned DMaskLanes = 0;
6221 
6222   if (BaseOpcode->Atomic) {
6223     VData = Op.getOperand(2);
6224 
6225     bool Is64Bit = VData.getValueType() == MVT::i64;
6226     if (BaseOpcode->AtomicX2) {
6227       SDValue VData2 = Op.getOperand(3);
6228       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6229                                  {VData, VData2});
6230       if (Is64Bit)
6231         VData = DAG.getBitcast(MVT::v4i32, VData);
6232 
6233       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6234       DMask = Is64Bit ? 0xf : 0x3;
6235       NumVDataDwords = Is64Bit ? 4 : 2;
6236     } else {
6237       DMask = Is64Bit ? 0x3 : 0x1;
6238       NumVDataDwords = Is64Bit ? 2 : 1;
6239     }
6240   } else {
6241     auto *DMaskConst =
6242         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6243     DMask = DMaskConst->getZExtValue();
6244     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6245 
6246     if (BaseOpcode->Store) {
6247       VData = Op.getOperand(2);
6248 
6249       MVT StoreVT = VData.getSimpleValueType();
6250       if (StoreVT.getScalarType() == MVT::f16) {
6251         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6252           return Op; // D16 is unsupported for this instruction
6253 
6254         IsD16 = true;
6255         VData = handleD16VData(VData, DAG, true);
6256       }
6257 
6258       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6259     } else {
6260       // Work out the num dwords based on the dmask popcount and underlying type
6261       // and whether packing is supported.
6262       MVT LoadVT = ResultTypes[0].getSimpleVT();
6263       if (LoadVT.getScalarType() == MVT::f16) {
6264         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6265           return Op; // D16 is unsupported for this instruction
6266 
6267         IsD16 = true;
6268       }
6269 
6270       // Confirm that the return type is large enough for the dmask specified
6271       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6272           (!LoadVT.isVector() && DMaskLanes > 1))
6273           return Op;
6274 
6275       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6276       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6277       // instructions.
6278       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6279           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6280         NumVDataDwords = (DMaskLanes + 1) / 2;
6281       else
6282         NumVDataDwords = DMaskLanes;
6283 
6284       AdjustRetType = true;
6285     }
6286   }
6287 
6288   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6289   SmallVector<SDValue, 4> VAddrs;
6290 
6291   // Check for 16 bit addresses or derivatives and pack if true.
6292   MVT VAddrVT =
6293       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6294   MVT VAddrScalarVT = VAddrVT.getScalarType();
6295   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6296   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6297 
6298   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6299   VAddrScalarVT = VAddrVT.getScalarType();
6300   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6301   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6302 
6303   // Push back extra arguments.
6304   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6305     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6306       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6307       // Special handling of bias when A16 is on. Bias is of type half but
6308       // occupies full 32-bit.
6309       SDValue Bias = DAG.getBuildVector(
6310           MVT::v2f16, DL,
6311           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6312       VAddrs.push_back(Bias);
6313     } else {
6314       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6315              "Bias needs to be converted to 16 bit in A16 mode");
6316       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6317     }
6318   }
6319 
6320   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6321     // 16 bit gradients are supported, but are tied to the A16 control
6322     // so both gradients and addresses must be 16 bit
6323     LLVM_DEBUG(
6324         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6325                   "require 16 bit args for both gradients and addresses");
6326     return Op;
6327   }
6328 
6329   if (IsA16) {
6330     if (!ST->hasA16()) {
6331       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6332                            "support 16 bit addresses\n");
6333       return Op;
6334     }
6335   }
6336 
6337   // We've dealt with incorrect input so we know that if IsA16, IsG16
6338   // are set then we have to compress/pack operands (either address,
6339   // gradient or both)
6340   // In the case where a16 and gradients are tied (no G16 support) then we
6341   // have already verified that both IsA16 and IsG16 are true
6342   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6343     // Activate g16
6344     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6345         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6346     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6347   }
6348 
6349   // Add gradients (packed or unpacked)
6350   if (IsG16) {
6351     // Pack the gradients
6352     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6353     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6354                               ArgOffset + Intr->GradientStart,
6355                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6356   } else {
6357     for (unsigned I = ArgOffset + Intr->GradientStart;
6358          I < ArgOffset + Intr->CoordStart; I++)
6359       VAddrs.push_back(Op.getOperand(I));
6360   }
6361 
6362   // Add addresses (packed or unpacked)
6363   if (IsA16) {
6364     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6365                               ArgOffset + Intr->CoordStart, VAddrEnd,
6366                               0 /* No gradients */);
6367   } else {
6368     // Add uncompressed address
6369     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6370       VAddrs.push_back(Op.getOperand(I));
6371   }
6372 
6373   // If the register allocator cannot place the address registers contiguously
6374   // without introducing moves, then using the non-sequential address encoding
6375   // is always preferable, since it saves VALU instructions and is usually a
6376   // wash in terms of code size or even better.
6377   //
6378   // However, we currently have no way of hinting to the register allocator that
6379   // MIMG addresses should be placed contiguously when it is possible to do so,
6380   // so force non-NSA for the common 2-address case as a heuristic.
6381   //
6382   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6383   // allocation when possible.
6384   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6385                 VAddrs.size() >= 3 &&
6386                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6387   SDValue VAddr;
6388   if (!UseNSA)
6389     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6390 
6391   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6392   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6393   SDValue Unorm;
6394   if (!BaseOpcode->Sampler) {
6395     Unorm = True;
6396   } else {
6397     auto UnormConst =
6398         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6399 
6400     Unorm = UnormConst->getZExtValue() ? True : False;
6401   }
6402 
6403   SDValue TFE;
6404   SDValue LWE;
6405   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6406   bool IsTexFail = false;
6407   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6408     return Op;
6409 
6410   if (IsTexFail) {
6411     if (!DMaskLanes) {
6412       // Expecting to get an error flag since TFC is on - and dmask is 0
6413       // Force dmask to be at least 1 otherwise the instruction will fail
6414       DMask = 0x1;
6415       DMaskLanes = 1;
6416       NumVDataDwords = 1;
6417     }
6418     NumVDataDwords += 1;
6419     AdjustRetType = true;
6420   }
6421 
6422   // Has something earlier tagged that the return type needs adjusting
6423   // This happens if the instruction is a load or has set TexFailCtrl flags
6424   if (AdjustRetType) {
6425     // NumVDataDwords reflects the true number of dwords required in the return type
6426     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6427       // This is a no-op load. This can be eliminated
6428       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6429       if (isa<MemSDNode>(Op))
6430         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6431       return Undef;
6432     }
6433 
6434     EVT NewVT = NumVDataDwords > 1 ?
6435                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6436                 : MVT::i32;
6437 
6438     ResultTypes[0] = NewVT;
6439     if (ResultTypes.size() == 3) {
6440       // Original result was aggregate type used for TexFailCtrl results
6441       // The actual instruction returns as a vector type which has now been
6442       // created. Remove the aggregate result.
6443       ResultTypes.erase(&ResultTypes[1]);
6444     }
6445   }
6446 
6447   unsigned CPol = cast<ConstantSDNode>(
6448       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6449   if (BaseOpcode->Atomic)
6450     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6451   if (CPol & ~AMDGPU::CPol::ALL)
6452     return Op;
6453 
6454   SmallVector<SDValue, 26> Ops;
6455   if (BaseOpcode->Store || BaseOpcode->Atomic)
6456     Ops.push_back(VData); // vdata
6457   if (UseNSA)
6458     append_range(Ops, VAddrs);
6459   else
6460     Ops.push_back(VAddr);
6461   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6462   if (BaseOpcode->Sampler)
6463     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6464   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6465   if (IsGFX10Plus)
6466     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6467   Ops.push_back(Unorm);
6468   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6469   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6470                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6471   if (IsGFX10Plus)
6472     Ops.push_back(IsA16 ? True : False);
6473   if (!Subtarget->hasGFX90AInsts()) {
6474     Ops.push_back(TFE); //tfe
6475   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6476     report_fatal_error("TFE is not supported on this GPU");
6477   }
6478   Ops.push_back(LWE); // lwe
6479   if (!IsGFX10Plus)
6480     Ops.push_back(DimInfo->DA ? True : False);
6481   if (BaseOpcode->HasD16)
6482     Ops.push_back(IsD16 ? True : False);
6483   if (isa<MemSDNode>(Op))
6484     Ops.push_back(Op.getOperand(0)); // chain
6485 
6486   int NumVAddrDwords =
6487       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6488   int Opcode = -1;
6489 
6490   if (IsGFX10Plus) {
6491     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6492                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6493                                           : AMDGPU::MIMGEncGfx10Default,
6494                                    NumVDataDwords, NumVAddrDwords);
6495   } else {
6496     if (Subtarget->hasGFX90AInsts()) {
6497       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6498                                      NumVDataDwords, NumVAddrDwords);
6499       if (Opcode == -1)
6500         report_fatal_error(
6501             "requested image instruction is not supported on this GPU");
6502     }
6503     if (Opcode == -1 &&
6504         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6505       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6506                                      NumVDataDwords, NumVAddrDwords);
6507     if (Opcode == -1)
6508       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6509                                      NumVDataDwords, NumVAddrDwords);
6510   }
6511   assert(Opcode != -1);
6512 
6513   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6514   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6515     MachineMemOperand *MemRef = MemOp->getMemOperand();
6516     DAG.setNodeMemRefs(NewNode, {MemRef});
6517   }
6518 
6519   if (BaseOpcode->AtomicX2) {
6520     SmallVector<SDValue, 1> Elt;
6521     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6522     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6523   }
6524   if (BaseOpcode->Store)
6525     return SDValue(NewNode, 0);
6526   return constructRetValue(DAG, NewNode,
6527                            OrigResultTypes, IsTexFail,
6528                            Subtarget->hasUnpackedD16VMem(), IsD16,
6529                            DMaskLanes, NumVDataDwords, DL);
6530 }
6531 
6532 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6533                                        SDValue Offset, SDValue CachePolicy,
6534                                        SelectionDAG &DAG) const {
6535   MachineFunction &MF = DAG.getMachineFunction();
6536 
6537   const DataLayout &DataLayout = DAG.getDataLayout();
6538   Align Alignment =
6539       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6540 
6541   MachineMemOperand *MMO = MF.getMachineMemOperand(
6542       MachinePointerInfo(),
6543       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6544           MachineMemOperand::MOInvariant,
6545       VT.getStoreSize(), Alignment);
6546 
6547   if (!Offset->isDivergent()) {
6548     SDValue Ops[] = {
6549         Rsrc,
6550         Offset, // Offset
6551         CachePolicy
6552     };
6553 
6554     // Widen vec3 load to vec4.
6555     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6556       EVT WidenedVT =
6557           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6558       auto WidenedOp = DAG.getMemIntrinsicNode(
6559           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6560           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6561       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6562                                    DAG.getVectorIdxConstant(0, DL));
6563       return Subvector;
6564     }
6565 
6566     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6567                                    DAG.getVTList(VT), Ops, VT, MMO);
6568   }
6569 
6570   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6571   // assume that the buffer is unswizzled.
6572   SmallVector<SDValue, 4> Loads;
6573   unsigned NumLoads = 1;
6574   MVT LoadVT = VT.getSimpleVT();
6575   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6576   assert((LoadVT.getScalarType() == MVT::i32 ||
6577           LoadVT.getScalarType() == MVT::f32));
6578 
6579   if (NumElts == 8 || NumElts == 16) {
6580     NumLoads = NumElts / 4;
6581     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6582   }
6583 
6584   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6585   SDValue Ops[] = {
6586       DAG.getEntryNode(),                               // Chain
6587       Rsrc,                                             // rsrc
6588       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6589       {},                                               // voffset
6590       {},                                               // soffset
6591       {},                                               // offset
6592       CachePolicy,                                      // cachepolicy
6593       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6594   };
6595 
6596   // Use the alignment to ensure that the required offsets will fit into the
6597   // immediate offsets.
6598   setBufferOffsets(Offset, DAG, &Ops[3],
6599                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6600 
6601   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6602   for (unsigned i = 0; i < NumLoads; ++i) {
6603     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6604     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6605                                         LoadVT, MMO, DAG));
6606   }
6607 
6608   if (NumElts == 8 || NumElts == 16)
6609     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6610 
6611   return Loads[0];
6612 }
6613 
6614 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6615                                           unsigned Dim,
6616                                           const ArgDescriptor &Arg) const {
6617   SDLoc SL(Op);
6618   MachineFunction &MF = DAG.getMachineFunction();
6619   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6620   if (MaxID == 0)
6621     return DAG.getConstant(0, SL, MVT::i32);
6622 
6623   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6624                                SDLoc(DAG.getEntryNode()), Arg);
6625 
6626   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6627   // masking operations anyway.
6628   //
6629   // TODO: We could assert the top bit is 0 for the source copy.
6630   if (Arg.isMasked())
6631     return Val;
6632 
6633   // Preserve the known bits after expansion to a copy.
6634   EVT SmallVT =
6635       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6636   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6637                      DAG.getValueType(SmallVT));
6638 }
6639 
6640 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6641                                                   SelectionDAG &DAG) const {
6642   MachineFunction &MF = DAG.getMachineFunction();
6643   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6644 
6645   EVT VT = Op.getValueType();
6646   SDLoc DL(Op);
6647   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6648 
6649   // TODO: Should this propagate fast-math-flags?
6650 
6651   switch (IntrinsicID) {
6652   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6653     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6654       return emitNonHSAIntrinsicError(DAG, DL, VT);
6655     return getPreloadedValue(DAG, *MFI, VT,
6656                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6657   }
6658   case Intrinsic::amdgcn_dispatch_ptr:
6659   case Intrinsic::amdgcn_queue_ptr: {
6660     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6661       DiagnosticInfoUnsupported BadIntrin(
6662           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6663           DL.getDebugLoc());
6664       DAG.getContext()->diagnose(BadIntrin);
6665       return DAG.getUNDEF(VT);
6666     }
6667 
6668     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6669       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6670     return getPreloadedValue(DAG, *MFI, VT, RegID);
6671   }
6672   case Intrinsic::amdgcn_implicitarg_ptr: {
6673     if (MFI->isEntryFunction())
6674       return getImplicitArgPtr(DAG, DL);
6675     return getPreloadedValue(DAG, *MFI, VT,
6676                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6677   }
6678   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6679     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6680       // This only makes sense to call in a kernel, so just lower to null.
6681       return DAG.getConstant(0, DL, VT);
6682     }
6683 
6684     return getPreloadedValue(DAG, *MFI, VT,
6685                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6686   }
6687   case Intrinsic::amdgcn_dispatch_id: {
6688     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6689   }
6690   case Intrinsic::amdgcn_rcp:
6691     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6692   case Intrinsic::amdgcn_rsq:
6693     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6694   case Intrinsic::amdgcn_rsq_legacy:
6695     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6696       return emitRemovedIntrinsicError(DAG, DL, VT);
6697     return SDValue();
6698   case Intrinsic::amdgcn_rcp_legacy:
6699     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6700       return emitRemovedIntrinsicError(DAG, DL, VT);
6701     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6702   case Intrinsic::amdgcn_rsq_clamp: {
6703     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6704       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6705 
6706     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6707     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6708     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6709 
6710     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6711     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6712                               DAG.getConstantFP(Max, DL, VT));
6713     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6714                        DAG.getConstantFP(Min, DL, VT));
6715   }
6716   case Intrinsic::r600_read_ngroups_x:
6717     if (Subtarget->isAmdHsaOS())
6718       return emitNonHSAIntrinsicError(DAG, DL, VT);
6719 
6720     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6721                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6722                                     false);
6723   case Intrinsic::r600_read_ngroups_y:
6724     if (Subtarget->isAmdHsaOS())
6725       return emitNonHSAIntrinsicError(DAG, DL, VT);
6726 
6727     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6728                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6729                                     false);
6730   case Intrinsic::r600_read_ngroups_z:
6731     if (Subtarget->isAmdHsaOS())
6732       return emitNonHSAIntrinsicError(DAG, DL, VT);
6733 
6734     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6735                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6736                                     false);
6737   case Intrinsic::r600_read_global_size_x:
6738     if (Subtarget->isAmdHsaOS())
6739       return emitNonHSAIntrinsicError(DAG, DL, VT);
6740 
6741     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6742                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6743                                     Align(4), false);
6744   case Intrinsic::r600_read_global_size_y:
6745     if (Subtarget->isAmdHsaOS())
6746       return emitNonHSAIntrinsicError(DAG, DL, VT);
6747 
6748     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6749                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6750                                     Align(4), false);
6751   case Intrinsic::r600_read_global_size_z:
6752     if (Subtarget->isAmdHsaOS())
6753       return emitNonHSAIntrinsicError(DAG, DL, VT);
6754 
6755     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6756                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6757                                     Align(4), false);
6758   case Intrinsic::r600_read_local_size_x:
6759     if (Subtarget->isAmdHsaOS())
6760       return emitNonHSAIntrinsicError(DAG, DL, VT);
6761 
6762     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6763                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6764   case Intrinsic::r600_read_local_size_y:
6765     if (Subtarget->isAmdHsaOS())
6766       return emitNonHSAIntrinsicError(DAG, DL, VT);
6767 
6768     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6769                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6770   case Intrinsic::r600_read_local_size_z:
6771     if (Subtarget->isAmdHsaOS())
6772       return emitNonHSAIntrinsicError(DAG, DL, VT);
6773 
6774     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6775                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6776   case Intrinsic::amdgcn_workgroup_id_x:
6777     return getPreloadedValue(DAG, *MFI, VT,
6778                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6779   case Intrinsic::amdgcn_workgroup_id_y:
6780     return getPreloadedValue(DAG, *MFI, VT,
6781                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6782   case Intrinsic::amdgcn_workgroup_id_z:
6783     return getPreloadedValue(DAG, *MFI, VT,
6784                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6785   case Intrinsic::amdgcn_workitem_id_x:
6786     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6787   case Intrinsic::amdgcn_workitem_id_y:
6788     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6789   case Intrinsic::amdgcn_workitem_id_z:
6790     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6791   case Intrinsic::amdgcn_wavefrontsize:
6792     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6793                            SDLoc(Op), MVT::i32);
6794   case Intrinsic::amdgcn_s_buffer_load: {
6795     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6796     if (CPol & ~AMDGPU::CPol::ALL)
6797       return Op;
6798     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6799                         DAG);
6800   }
6801   case Intrinsic::amdgcn_fdiv_fast:
6802     return lowerFDIV_FAST(Op, DAG);
6803   case Intrinsic::amdgcn_sin:
6804     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6805 
6806   case Intrinsic::amdgcn_cos:
6807     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6808 
6809   case Intrinsic::amdgcn_mul_u24:
6810     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6811   case Intrinsic::amdgcn_mul_i24:
6812     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6813 
6814   case Intrinsic::amdgcn_log_clamp: {
6815     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6816       return SDValue();
6817 
6818     return emitRemovedIntrinsicError(DAG, DL, VT);
6819   }
6820   case Intrinsic::amdgcn_ldexp:
6821     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6822                        Op.getOperand(1), Op.getOperand(2));
6823 
6824   case Intrinsic::amdgcn_fract:
6825     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6826 
6827   case Intrinsic::amdgcn_class:
6828     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6829                        Op.getOperand(1), Op.getOperand(2));
6830   case Intrinsic::amdgcn_div_fmas:
6831     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6832                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6833                        Op.getOperand(4));
6834 
6835   case Intrinsic::amdgcn_div_fixup:
6836     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6837                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6838 
6839   case Intrinsic::amdgcn_div_scale: {
6840     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6841 
6842     // Translate to the operands expected by the machine instruction. The
6843     // first parameter must be the same as the first instruction.
6844     SDValue Numerator = Op.getOperand(1);
6845     SDValue Denominator = Op.getOperand(2);
6846 
6847     // Note this order is opposite of the machine instruction's operations,
6848     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6849     // intrinsic has the numerator as the first operand to match a normal
6850     // division operation.
6851 
6852     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6853 
6854     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6855                        Denominator, Numerator);
6856   }
6857   case Intrinsic::amdgcn_icmp: {
6858     // There is a Pat that handles this variant, so return it as-is.
6859     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6860         Op.getConstantOperandVal(2) == 0 &&
6861         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6862       return Op;
6863     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6864   }
6865   case Intrinsic::amdgcn_fcmp: {
6866     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6867   }
6868   case Intrinsic::amdgcn_ballot:
6869     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6870   case Intrinsic::amdgcn_fmed3:
6871     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6872                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6873   case Intrinsic::amdgcn_fdot2:
6874     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6875                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6876                        Op.getOperand(4));
6877   case Intrinsic::amdgcn_fmul_legacy:
6878     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6879                        Op.getOperand(1), Op.getOperand(2));
6880   case Intrinsic::amdgcn_sffbh:
6881     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6882   case Intrinsic::amdgcn_sbfe:
6883     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6884                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6885   case Intrinsic::amdgcn_ubfe:
6886     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6887                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6888   case Intrinsic::amdgcn_cvt_pkrtz:
6889   case Intrinsic::amdgcn_cvt_pknorm_i16:
6890   case Intrinsic::amdgcn_cvt_pknorm_u16:
6891   case Intrinsic::amdgcn_cvt_pk_i16:
6892   case Intrinsic::amdgcn_cvt_pk_u16: {
6893     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6894     EVT VT = Op.getValueType();
6895     unsigned Opcode;
6896 
6897     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6898       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6899     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6900       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6901     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6902       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6903     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6904       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6905     else
6906       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6907 
6908     if (isTypeLegal(VT))
6909       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6910 
6911     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6912                                Op.getOperand(1), Op.getOperand(2));
6913     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6914   }
6915   case Intrinsic::amdgcn_fmad_ftz:
6916     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6917                        Op.getOperand(2), Op.getOperand(3));
6918 
6919   case Intrinsic::amdgcn_if_break:
6920     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6921                                       Op->getOperand(1), Op->getOperand(2)), 0);
6922 
6923   case Intrinsic::amdgcn_groupstaticsize: {
6924     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6925     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6926       return Op;
6927 
6928     const Module *M = MF.getFunction().getParent();
6929     const GlobalValue *GV =
6930         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6931     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6932                                             SIInstrInfo::MO_ABS32_LO);
6933     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6934   }
6935   case Intrinsic::amdgcn_is_shared:
6936   case Intrinsic::amdgcn_is_private: {
6937     SDLoc SL(Op);
6938     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6939       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6940     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6941     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6942                                  Op.getOperand(1));
6943 
6944     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6945                                 DAG.getConstant(1, SL, MVT::i32));
6946     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6947   }
6948   case Intrinsic::amdgcn_perm:
6949     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6950                        Op.getOperand(2), Op.getOperand(3));
6951   case Intrinsic::amdgcn_reloc_constant: {
6952     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6953     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6954     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6955     auto RelocSymbol = cast<GlobalVariable>(
6956         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6957     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6958                                             SIInstrInfo::MO_ABS32_LO);
6959     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6960   }
6961   default:
6962     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6963             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6964       return lowerImage(Op, ImageDimIntr, DAG, false);
6965 
6966     return Op;
6967   }
6968 }
6969 
6970 /// Update \p MMO based on the offset inputs to an intrinsic.
6971 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6972                             SDValue SOffset, SDValue Offset,
6973                             SDValue VIndex = SDValue()) {
6974   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6975       !isa<ConstantSDNode>(Offset)) {
6976     // The combined offset is not known to be constant, so we cannot represent
6977     // it in the MMO. Give up.
6978     MMO->setValue((Value *)nullptr);
6979     return;
6980   }
6981 
6982   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6983                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6984     // The strided index component of the address is not known to be zero, so we
6985     // cannot represent it in the MMO. Give up.
6986     MMO->setValue((Value *)nullptr);
6987     return;
6988   }
6989 
6990   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6991                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6992                  cast<ConstantSDNode>(Offset)->getSExtValue());
6993 }
6994 
6995 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6996                                                      SelectionDAG &DAG,
6997                                                      unsigned NewOpcode) const {
6998   SDLoc DL(Op);
6999 
7000   SDValue VData = Op.getOperand(2);
7001   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7002   SDValue Ops[] = {
7003     Op.getOperand(0), // Chain
7004     VData,            // vdata
7005     Op.getOperand(3), // rsrc
7006     DAG.getConstant(0, DL, MVT::i32), // vindex
7007     Offsets.first,    // voffset
7008     Op.getOperand(5), // soffset
7009     Offsets.second,   // offset
7010     Op.getOperand(6), // cachepolicy
7011     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7012   };
7013 
7014   auto *M = cast<MemSDNode>(Op);
7015   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7016 
7017   EVT MemVT = VData.getValueType();
7018   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7019                                  M->getMemOperand());
7020 }
7021 
7022 // Return a value to use for the idxen operand by examining the vindex operand.
7023 static unsigned getIdxEn(SDValue VIndex) {
7024   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7025     // No need to set idxen if vindex is known to be zero.
7026     return VIndexC->getZExtValue() != 0;
7027   return 1;
7028 }
7029 
7030 SDValue
7031 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7032                                                 unsigned NewOpcode) const {
7033   SDLoc DL(Op);
7034 
7035   SDValue VData = Op.getOperand(2);
7036   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7037   SDValue Ops[] = {
7038     Op.getOperand(0), // Chain
7039     VData,            // vdata
7040     Op.getOperand(3), // rsrc
7041     Op.getOperand(4), // vindex
7042     Offsets.first,    // voffset
7043     Op.getOperand(6), // soffset
7044     Offsets.second,   // offset
7045     Op.getOperand(7), // cachepolicy
7046     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7047   };
7048 
7049   auto *M = cast<MemSDNode>(Op);
7050   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7051 
7052   EVT MemVT = VData.getValueType();
7053   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7054                                  M->getMemOperand());
7055 }
7056 
7057 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7058                                                  SelectionDAG &DAG) const {
7059   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7060   SDLoc DL(Op);
7061 
7062   switch (IntrID) {
7063   case Intrinsic::amdgcn_ds_ordered_add:
7064   case Intrinsic::amdgcn_ds_ordered_swap: {
7065     MemSDNode *M = cast<MemSDNode>(Op);
7066     SDValue Chain = M->getOperand(0);
7067     SDValue M0 = M->getOperand(2);
7068     SDValue Value = M->getOperand(3);
7069     unsigned IndexOperand = M->getConstantOperandVal(7);
7070     unsigned WaveRelease = M->getConstantOperandVal(8);
7071     unsigned WaveDone = M->getConstantOperandVal(9);
7072 
7073     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7074     IndexOperand &= ~0x3f;
7075     unsigned CountDw = 0;
7076 
7077     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7078       CountDw = (IndexOperand >> 24) & 0xf;
7079       IndexOperand &= ~(0xf << 24);
7080 
7081       if (CountDw < 1 || CountDw > 4) {
7082         report_fatal_error(
7083             "ds_ordered_count: dword count must be between 1 and 4");
7084       }
7085     }
7086 
7087     if (IndexOperand)
7088       report_fatal_error("ds_ordered_count: bad index operand");
7089 
7090     if (WaveDone && !WaveRelease)
7091       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7092 
7093     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7094     unsigned ShaderType =
7095         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7096     unsigned Offset0 = OrderedCountIndex << 2;
7097     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7098                        (Instruction << 4);
7099 
7100     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7101       Offset1 |= (CountDw - 1) << 6;
7102 
7103     unsigned Offset = Offset0 | (Offset1 << 8);
7104 
7105     SDValue Ops[] = {
7106       Chain,
7107       Value,
7108       DAG.getTargetConstant(Offset, DL, MVT::i16),
7109       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7110     };
7111     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7112                                    M->getVTList(), Ops, M->getMemoryVT(),
7113                                    M->getMemOperand());
7114   }
7115   case Intrinsic::amdgcn_ds_fadd: {
7116     MemSDNode *M = cast<MemSDNode>(Op);
7117     unsigned Opc;
7118     switch (IntrID) {
7119     case Intrinsic::amdgcn_ds_fadd:
7120       Opc = ISD::ATOMIC_LOAD_FADD;
7121       break;
7122     }
7123 
7124     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7125                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7126                          M->getMemOperand());
7127   }
7128   case Intrinsic::amdgcn_atomic_inc:
7129   case Intrinsic::amdgcn_atomic_dec:
7130   case Intrinsic::amdgcn_ds_fmin:
7131   case Intrinsic::amdgcn_ds_fmax: {
7132     MemSDNode *M = cast<MemSDNode>(Op);
7133     unsigned Opc;
7134     switch (IntrID) {
7135     case Intrinsic::amdgcn_atomic_inc:
7136       Opc = AMDGPUISD::ATOMIC_INC;
7137       break;
7138     case Intrinsic::amdgcn_atomic_dec:
7139       Opc = AMDGPUISD::ATOMIC_DEC;
7140       break;
7141     case Intrinsic::amdgcn_ds_fmin:
7142       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7143       break;
7144     case Intrinsic::amdgcn_ds_fmax:
7145       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7146       break;
7147     default:
7148       llvm_unreachable("Unknown intrinsic!");
7149     }
7150     SDValue Ops[] = {
7151       M->getOperand(0), // Chain
7152       M->getOperand(2), // Ptr
7153       M->getOperand(3)  // Value
7154     };
7155 
7156     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7157                                    M->getMemoryVT(), M->getMemOperand());
7158   }
7159   case Intrinsic::amdgcn_buffer_load:
7160   case Intrinsic::amdgcn_buffer_load_format: {
7161     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7162     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7163     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7164     SDValue Ops[] = {
7165       Op.getOperand(0), // Chain
7166       Op.getOperand(2), // rsrc
7167       Op.getOperand(3), // vindex
7168       SDValue(),        // voffset -- will be set by setBufferOffsets
7169       SDValue(),        // soffset -- will be set by setBufferOffsets
7170       SDValue(),        // offset -- will be set by setBufferOffsets
7171       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7172       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7173     };
7174     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7175 
7176     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7177         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7178 
7179     EVT VT = Op.getValueType();
7180     EVT IntVT = VT.changeTypeToInteger();
7181     auto *M = cast<MemSDNode>(Op);
7182     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7183     EVT LoadVT = Op.getValueType();
7184 
7185     if (LoadVT.getScalarType() == MVT::f16)
7186       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7187                                  M, DAG, Ops);
7188 
7189     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7190     if (LoadVT.getScalarType() == MVT::i8 ||
7191         LoadVT.getScalarType() == MVT::i16)
7192       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7193 
7194     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7195                                M->getMemOperand(), DAG);
7196   }
7197   case Intrinsic::amdgcn_raw_buffer_load:
7198   case Intrinsic::amdgcn_raw_buffer_load_format: {
7199     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7200 
7201     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7202     SDValue Ops[] = {
7203       Op.getOperand(0), // Chain
7204       Op.getOperand(2), // rsrc
7205       DAG.getConstant(0, DL, MVT::i32), // vindex
7206       Offsets.first,    // voffset
7207       Op.getOperand(4), // soffset
7208       Offsets.second,   // offset
7209       Op.getOperand(5), // cachepolicy, swizzled buffer
7210       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7211     };
7212 
7213     auto *M = cast<MemSDNode>(Op);
7214     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7215     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7216   }
7217   case Intrinsic::amdgcn_struct_buffer_load:
7218   case Intrinsic::amdgcn_struct_buffer_load_format: {
7219     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7220 
7221     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7222     SDValue Ops[] = {
7223       Op.getOperand(0), // Chain
7224       Op.getOperand(2), // rsrc
7225       Op.getOperand(3), // vindex
7226       Offsets.first,    // voffset
7227       Op.getOperand(5), // soffset
7228       Offsets.second,   // offset
7229       Op.getOperand(6), // cachepolicy, swizzled buffer
7230       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7231     };
7232 
7233     auto *M = cast<MemSDNode>(Op);
7234     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7235     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7236   }
7237   case Intrinsic::amdgcn_tbuffer_load: {
7238     MemSDNode *M = cast<MemSDNode>(Op);
7239     EVT LoadVT = Op.getValueType();
7240 
7241     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7242     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7243     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7244     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7245     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7246     SDValue Ops[] = {
7247       Op.getOperand(0),  // Chain
7248       Op.getOperand(2),  // rsrc
7249       Op.getOperand(3),  // vindex
7250       Op.getOperand(4),  // voffset
7251       Op.getOperand(5),  // soffset
7252       Op.getOperand(6),  // offset
7253       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7254       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7255       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7256     };
7257 
7258     if (LoadVT.getScalarType() == MVT::f16)
7259       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7260                                  M, DAG, Ops);
7261     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7262                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7263                                DAG);
7264   }
7265   case Intrinsic::amdgcn_raw_tbuffer_load: {
7266     MemSDNode *M = cast<MemSDNode>(Op);
7267     EVT LoadVT = Op.getValueType();
7268     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7269 
7270     SDValue Ops[] = {
7271       Op.getOperand(0),  // Chain
7272       Op.getOperand(2),  // rsrc
7273       DAG.getConstant(0, DL, MVT::i32), // vindex
7274       Offsets.first,     // voffset
7275       Op.getOperand(4),  // soffset
7276       Offsets.second,    // offset
7277       Op.getOperand(5),  // format
7278       Op.getOperand(6),  // cachepolicy, swizzled buffer
7279       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7280     };
7281 
7282     if (LoadVT.getScalarType() == MVT::f16)
7283       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7284                                  M, DAG, Ops);
7285     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7286                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7287                                DAG);
7288   }
7289   case Intrinsic::amdgcn_struct_tbuffer_load: {
7290     MemSDNode *M = cast<MemSDNode>(Op);
7291     EVT LoadVT = Op.getValueType();
7292     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7293 
7294     SDValue Ops[] = {
7295       Op.getOperand(0),  // Chain
7296       Op.getOperand(2),  // rsrc
7297       Op.getOperand(3),  // vindex
7298       Offsets.first,     // voffset
7299       Op.getOperand(5),  // soffset
7300       Offsets.second,    // offset
7301       Op.getOperand(6),  // format
7302       Op.getOperand(7),  // cachepolicy, swizzled buffer
7303       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7304     };
7305 
7306     if (LoadVT.getScalarType() == MVT::f16)
7307       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7308                                  M, DAG, Ops);
7309     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7310                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7311                                DAG);
7312   }
7313   case Intrinsic::amdgcn_buffer_atomic_swap:
7314   case Intrinsic::amdgcn_buffer_atomic_add:
7315   case Intrinsic::amdgcn_buffer_atomic_sub:
7316   case Intrinsic::amdgcn_buffer_atomic_csub:
7317   case Intrinsic::amdgcn_buffer_atomic_smin:
7318   case Intrinsic::amdgcn_buffer_atomic_umin:
7319   case Intrinsic::amdgcn_buffer_atomic_smax:
7320   case Intrinsic::amdgcn_buffer_atomic_umax:
7321   case Intrinsic::amdgcn_buffer_atomic_and:
7322   case Intrinsic::amdgcn_buffer_atomic_or:
7323   case Intrinsic::amdgcn_buffer_atomic_xor:
7324   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7325     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7326     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7327     SDValue Ops[] = {
7328       Op.getOperand(0), // Chain
7329       Op.getOperand(2), // vdata
7330       Op.getOperand(3), // rsrc
7331       Op.getOperand(4), // vindex
7332       SDValue(),        // voffset -- will be set by setBufferOffsets
7333       SDValue(),        // soffset -- will be set by setBufferOffsets
7334       SDValue(),        // offset -- will be set by setBufferOffsets
7335       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7336       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7337     };
7338     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7339 
7340     EVT VT = Op.getValueType();
7341 
7342     auto *M = cast<MemSDNode>(Op);
7343     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7344     unsigned Opcode = 0;
7345 
7346     switch (IntrID) {
7347     case Intrinsic::amdgcn_buffer_atomic_swap:
7348       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7349       break;
7350     case Intrinsic::amdgcn_buffer_atomic_add:
7351       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7352       break;
7353     case Intrinsic::amdgcn_buffer_atomic_sub:
7354       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7355       break;
7356     case Intrinsic::amdgcn_buffer_atomic_csub:
7357       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7358       break;
7359     case Intrinsic::amdgcn_buffer_atomic_smin:
7360       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7361       break;
7362     case Intrinsic::amdgcn_buffer_atomic_umin:
7363       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7364       break;
7365     case Intrinsic::amdgcn_buffer_atomic_smax:
7366       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7367       break;
7368     case Intrinsic::amdgcn_buffer_atomic_umax:
7369       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7370       break;
7371     case Intrinsic::amdgcn_buffer_atomic_and:
7372       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7373       break;
7374     case Intrinsic::amdgcn_buffer_atomic_or:
7375       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7376       break;
7377     case Intrinsic::amdgcn_buffer_atomic_xor:
7378       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7379       break;
7380     case Intrinsic::amdgcn_buffer_atomic_fadd:
7381       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7382         DiagnosticInfoUnsupported
7383           NoFpRet(DAG.getMachineFunction().getFunction(),
7384                   "return versions of fp atomics not supported",
7385                   DL.getDebugLoc(), DS_Error);
7386         DAG.getContext()->diagnose(NoFpRet);
7387         return SDValue();
7388       }
7389       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7390       break;
7391     default:
7392       llvm_unreachable("unhandled atomic opcode");
7393     }
7394 
7395     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7396                                    M->getMemOperand());
7397   }
7398   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7399     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7400   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7401     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7402   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7403     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7404   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7405     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7406   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7407     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7408   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7409     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7410   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7411     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7412   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7413     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7414   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7415     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7416   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7417     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7418   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7419     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7420   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7421     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7422   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7423     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7424   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7425     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7426   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7427     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7428   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7429     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7430   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7431     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7432   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7433     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7434   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7435     return lowerStructBufferAtomicIntrin(Op, DAG,
7436                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7437   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7438     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7439   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7440     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7441   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7442     return lowerStructBufferAtomicIntrin(Op, DAG,
7443                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7444   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7445     return lowerStructBufferAtomicIntrin(Op, DAG,
7446                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7447   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7448     return lowerStructBufferAtomicIntrin(Op, DAG,
7449                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7450   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7451     return lowerStructBufferAtomicIntrin(Op, DAG,
7452                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7453   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7454     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7455   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7456     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7457   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7458     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7459   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7460     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7461   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7462     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7463 
7464   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7465     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7466     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7467     SDValue Ops[] = {
7468       Op.getOperand(0), // Chain
7469       Op.getOperand(2), // src
7470       Op.getOperand(3), // cmp
7471       Op.getOperand(4), // rsrc
7472       Op.getOperand(5), // 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(6), DAG, &Ops[5]);
7480 
7481     EVT VT = Op.getValueType();
7482     auto *M = cast<MemSDNode>(Op);
7483     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7484 
7485     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7486                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7487   }
7488   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7489     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7490     SDValue Ops[] = {
7491       Op.getOperand(0), // Chain
7492       Op.getOperand(2), // src
7493       Op.getOperand(3), // cmp
7494       Op.getOperand(4), // rsrc
7495       DAG.getConstant(0, DL, MVT::i32), // vindex
7496       Offsets.first,    // voffset
7497       Op.getOperand(6), // soffset
7498       Offsets.second,   // offset
7499       Op.getOperand(7), // cachepolicy
7500       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7501     };
7502     EVT VT = Op.getValueType();
7503     auto *M = cast<MemSDNode>(Op);
7504     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7505 
7506     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7507                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7508   }
7509   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7510     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7511     SDValue Ops[] = {
7512       Op.getOperand(0), // Chain
7513       Op.getOperand(2), // src
7514       Op.getOperand(3), // cmp
7515       Op.getOperand(4), // rsrc
7516       Op.getOperand(5), // vindex
7517       Offsets.first,    // voffset
7518       Op.getOperand(7), // soffset
7519       Offsets.second,   // offset
7520       Op.getOperand(8), // cachepolicy
7521       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7522     };
7523     EVT VT = Op.getValueType();
7524     auto *M = cast<MemSDNode>(Op);
7525     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7526 
7527     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7528                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7529   }
7530   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7531     MemSDNode *M = cast<MemSDNode>(Op);
7532     SDValue NodePtr = M->getOperand(2);
7533     SDValue RayExtent = M->getOperand(3);
7534     SDValue RayOrigin = M->getOperand(4);
7535     SDValue RayDir = M->getOperand(5);
7536     SDValue RayInvDir = M->getOperand(6);
7537     SDValue TDescr = M->getOperand(7);
7538 
7539     assert(NodePtr.getValueType() == MVT::i32 ||
7540            NodePtr.getValueType() == MVT::i64);
7541     assert(RayDir.getValueType() == MVT::v3f16 ||
7542            RayDir.getValueType() == MVT::v3f32);
7543 
7544     if (!Subtarget->hasGFX10_AEncoding()) {
7545       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7546       return SDValue();
7547     }
7548 
7549     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7550     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7551     const unsigned NumVDataDwords = 4;
7552     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7553     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7554                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7555     const unsigned BaseOpcodes[2][2] = {
7556         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7557         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7558          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7559     int Opcode;
7560     if (UseNSA) {
7561       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7562                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7563                                      NumVAddrDwords);
7564     } else {
7565       Opcode = AMDGPU::getMIMGOpcode(
7566           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7567           PowerOf2Ceil(NumVAddrDwords));
7568     }
7569     assert(Opcode != -1);
7570 
7571     SmallVector<SDValue, 16> Ops;
7572 
7573     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7574       SmallVector<SDValue, 3> Lanes;
7575       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7576       if (Lanes[0].getValueSizeInBits() == 32) {
7577         for (unsigned I = 0; I < 3; ++I)
7578           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7579       } else {
7580         if (IsAligned) {
7581           Ops.push_back(
7582             DAG.getBitcast(MVT::i32,
7583                            DAG.getBuildVector(MVT::v2f16, DL,
7584                                               { Lanes[0], Lanes[1] })));
7585           Ops.push_back(Lanes[2]);
7586         } else {
7587           SDValue Elt0 = Ops.pop_back_val();
7588           Ops.push_back(
7589             DAG.getBitcast(MVT::i32,
7590                            DAG.getBuildVector(MVT::v2f16, DL,
7591                                               { Elt0, Lanes[0] })));
7592           Ops.push_back(
7593             DAG.getBitcast(MVT::i32,
7594                            DAG.getBuildVector(MVT::v2f16, DL,
7595                                               { Lanes[1], Lanes[2] })));
7596         }
7597       }
7598     };
7599 
7600     if (Is64)
7601       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7602     else
7603       Ops.push_back(NodePtr);
7604 
7605     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7606     packLanes(RayOrigin, true);
7607     packLanes(RayDir, true);
7608     packLanes(RayInvDir, false);
7609 
7610     if (!UseNSA) {
7611       // Build a single vector containing all the operands so far prepared.
7612       if (NumVAddrDwords > 8) {
7613         SDValue Undef = DAG.getUNDEF(MVT::i32);
7614         Ops.append(16 - Ops.size(), Undef);
7615       }
7616       assert(Ops.size() == 8 || Ops.size() == 16);
7617       SDValue MergedOps = DAG.getBuildVector(
7618           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7619       Ops.clear();
7620       Ops.push_back(MergedOps);
7621     }
7622 
7623     Ops.push_back(TDescr);
7624     if (IsA16)
7625       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7626     Ops.push_back(M->getChain());
7627 
7628     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7629     MachineMemOperand *MemRef = M->getMemOperand();
7630     DAG.setNodeMemRefs(NewNode, {MemRef});
7631     return SDValue(NewNode, 0);
7632   }
7633   case Intrinsic::amdgcn_global_atomic_fadd:
7634     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7635       DiagnosticInfoUnsupported
7636         NoFpRet(DAG.getMachineFunction().getFunction(),
7637                 "return versions of fp atomics not supported",
7638                 DL.getDebugLoc(), DS_Error);
7639       DAG.getContext()->diagnose(NoFpRet);
7640       return SDValue();
7641     }
7642     LLVM_FALLTHROUGH;
7643   case Intrinsic::amdgcn_global_atomic_fmin:
7644   case Intrinsic::amdgcn_global_atomic_fmax:
7645   case Intrinsic::amdgcn_flat_atomic_fadd:
7646   case Intrinsic::amdgcn_flat_atomic_fmin:
7647   case Intrinsic::amdgcn_flat_atomic_fmax: {
7648     MemSDNode *M = cast<MemSDNode>(Op);
7649     SDValue Ops[] = {
7650       M->getOperand(0), // Chain
7651       M->getOperand(2), // Ptr
7652       M->getOperand(3)  // Value
7653     };
7654     unsigned Opcode = 0;
7655     switch (IntrID) {
7656     case Intrinsic::amdgcn_global_atomic_fadd:
7657     case Intrinsic::amdgcn_flat_atomic_fadd: {
7658       EVT VT = Op.getOperand(3).getValueType();
7659       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7660                            DAG.getVTList(VT, MVT::Other), Ops,
7661                            M->getMemOperand());
7662     }
7663     case Intrinsic::amdgcn_global_atomic_fmin:
7664     case Intrinsic::amdgcn_flat_atomic_fmin: {
7665       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7666       break;
7667     }
7668     case Intrinsic::amdgcn_global_atomic_fmax:
7669     case Intrinsic::amdgcn_flat_atomic_fmax: {
7670       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7671       break;
7672     }
7673     default:
7674       llvm_unreachable("unhandled atomic opcode");
7675     }
7676     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7677                                    M->getVTList(), Ops, M->getMemoryVT(),
7678                                    M->getMemOperand());
7679   }
7680   default:
7681 
7682     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7683             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7684       return lowerImage(Op, ImageDimIntr, DAG, true);
7685 
7686     return SDValue();
7687   }
7688 }
7689 
7690 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7691 // dwordx4 if on SI.
7692 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7693                                               SDVTList VTList,
7694                                               ArrayRef<SDValue> Ops, EVT MemVT,
7695                                               MachineMemOperand *MMO,
7696                                               SelectionDAG &DAG) const {
7697   EVT VT = VTList.VTs[0];
7698   EVT WidenedVT = VT;
7699   EVT WidenedMemVT = MemVT;
7700   if (!Subtarget->hasDwordx3LoadStores() &&
7701       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7702     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7703                                  WidenedVT.getVectorElementType(), 4);
7704     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7705                                     WidenedMemVT.getVectorElementType(), 4);
7706     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7707   }
7708 
7709   assert(VTList.NumVTs == 2);
7710   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7711 
7712   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7713                                        WidenedMemVT, MMO);
7714   if (WidenedVT != VT) {
7715     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7716                                DAG.getVectorIdxConstant(0, DL));
7717     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7718   }
7719   return NewOp;
7720 }
7721 
7722 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7723                                          bool ImageStore) const {
7724   EVT StoreVT = VData.getValueType();
7725 
7726   // No change for f16 and legal vector D16 types.
7727   if (!StoreVT.isVector())
7728     return VData;
7729 
7730   SDLoc DL(VData);
7731   unsigned NumElements = StoreVT.getVectorNumElements();
7732 
7733   if (Subtarget->hasUnpackedD16VMem()) {
7734     // We need to unpack the packed data to store.
7735     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7736     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7737 
7738     EVT EquivStoreVT =
7739         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7740     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7741     return DAG.UnrollVectorOp(ZExt.getNode());
7742   }
7743 
7744   // The sq block of gfx8.1 does not estimate register use correctly for d16
7745   // image store instructions. The data operand is computed as if it were not a
7746   // d16 image instruction.
7747   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7748     // Bitcast to i16
7749     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7750     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7751 
7752     // Decompose into scalars
7753     SmallVector<SDValue, 4> Elts;
7754     DAG.ExtractVectorElements(IntVData, Elts);
7755 
7756     // Group pairs of i16 into v2i16 and bitcast to i32
7757     SmallVector<SDValue, 4> PackedElts;
7758     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7759       SDValue Pair =
7760           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7761       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7762       PackedElts.push_back(IntPair);
7763     }
7764     if ((NumElements % 2) == 1) {
7765       // Handle v3i16
7766       unsigned I = Elts.size() / 2;
7767       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7768                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7769       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7770       PackedElts.push_back(IntPair);
7771     }
7772 
7773     // Pad using UNDEF
7774     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7775 
7776     // Build final vector
7777     EVT VecVT =
7778         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7779     return DAG.getBuildVector(VecVT, DL, PackedElts);
7780   }
7781 
7782   if (NumElements == 3) {
7783     EVT IntStoreVT =
7784         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7785     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7786 
7787     EVT WidenedStoreVT = EVT::getVectorVT(
7788         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7789     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7790                                          WidenedStoreVT.getStoreSizeInBits());
7791     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7792     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7793   }
7794 
7795   assert(isTypeLegal(StoreVT));
7796   return VData;
7797 }
7798 
7799 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7800                                               SelectionDAG &DAG) const {
7801   SDLoc DL(Op);
7802   SDValue Chain = Op.getOperand(0);
7803   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7804   MachineFunction &MF = DAG.getMachineFunction();
7805 
7806   switch (IntrinsicID) {
7807   case Intrinsic::amdgcn_exp_compr: {
7808     SDValue Src0 = Op.getOperand(4);
7809     SDValue Src1 = Op.getOperand(5);
7810     // Hack around illegal type on SI by directly selecting it.
7811     if (isTypeLegal(Src0.getValueType()))
7812       return SDValue();
7813 
7814     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7815     SDValue Undef = DAG.getUNDEF(MVT::f32);
7816     const SDValue Ops[] = {
7817       Op.getOperand(2), // tgt
7818       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7819       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7820       Undef, // src2
7821       Undef, // src3
7822       Op.getOperand(7), // vm
7823       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7824       Op.getOperand(3), // en
7825       Op.getOperand(0) // Chain
7826     };
7827 
7828     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7829     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7830   }
7831   case Intrinsic::amdgcn_s_barrier: {
7832     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7833       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7834       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7835       if (WGSize <= ST.getWavefrontSize())
7836         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7837                                           Op.getOperand(0)), 0);
7838     }
7839     return SDValue();
7840   };
7841   case Intrinsic::amdgcn_tbuffer_store: {
7842     SDValue VData = Op.getOperand(2);
7843     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7844     if (IsD16)
7845       VData = handleD16VData(VData, DAG);
7846     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7847     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7848     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7849     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7850     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7851     SDValue Ops[] = {
7852       Chain,
7853       VData,             // vdata
7854       Op.getOperand(3),  // rsrc
7855       Op.getOperand(4),  // vindex
7856       Op.getOperand(5),  // voffset
7857       Op.getOperand(6),  // soffset
7858       Op.getOperand(7),  // offset
7859       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7860       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7861       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7862     };
7863     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7864                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7865     MemSDNode *M = cast<MemSDNode>(Op);
7866     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7867                                    M->getMemoryVT(), M->getMemOperand());
7868   }
7869 
7870   case Intrinsic::amdgcn_struct_tbuffer_store: {
7871     SDValue VData = Op.getOperand(2);
7872     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7873     if (IsD16)
7874       VData = handleD16VData(VData, DAG);
7875     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7876     SDValue Ops[] = {
7877       Chain,
7878       VData,             // vdata
7879       Op.getOperand(3),  // rsrc
7880       Op.getOperand(4),  // vindex
7881       Offsets.first,     // voffset
7882       Op.getOperand(6),  // soffset
7883       Offsets.second,    // offset
7884       Op.getOperand(7),  // format
7885       Op.getOperand(8),  // cachepolicy, swizzled buffer
7886       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7887     };
7888     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7889                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7890     MemSDNode *M = cast<MemSDNode>(Op);
7891     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7892                                    M->getMemoryVT(), M->getMemOperand());
7893   }
7894 
7895   case Intrinsic::amdgcn_raw_tbuffer_store: {
7896     SDValue VData = Op.getOperand(2);
7897     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7898     if (IsD16)
7899       VData = handleD16VData(VData, DAG);
7900     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7901     SDValue Ops[] = {
7902       Chain,
7903       VData,             // vdata
7904       Op.getOperand(3),  // rsrc
7905       DAG.getConstant(0, DL, MVT::i32), // vindex
7906       Offsets.first,     // voffset
7907       Op.getOperand(5),  // soffset
7908       Offsets.second,    // offset
7909       Op.getOperand(6),  // format
7910       Op.getOperand(7),  // cachepolicy, swizzled buffer
7911       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7912     };
7913     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7914                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7915     MemSDNode *M = cast<MemSDNode>(Op);
7916     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7917                                    M->getMemoryVT(), M->getMemOperand());
7918   }
7919 
7920   case Intrinsic::amdgcn_buffer_store:
7921   case Intrinsic::amdgcn_buffer_store_format: {
7922     SDValue VData = Op.getOperand(2);
7923     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7924     if (IsD16)
7925       VData = handleD16VData(VData, DAG);
7926     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7927     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7928     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7929     SDValue Ops[] = {
7930       Chain,
7931       VData,
7932       Op.getOperand(3), // rsrc
7933       Op.getOperand(4), // vindex
7934       SDValue(), // voffset -- will be set by setBufferOffsets
7935       SDValue(), // soffset -- will be set by setBufferOffsets
7936       SDValue(), // offset -- will be set by setBufferOffsets
7937       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7938       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7939     };
7940     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7941 
7942     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7943                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7944     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7945     MemSDNode *M = cast<MemSDNode>(Op);
7946     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7947 
7948     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7949     EVT VDataType = VData.getValueType().getScalarType();
7950     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7951       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7952 
7953     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7954                                    M->getMemoryVT(), M->getMemOperand());
7955   }
7956 
7957   case Intrinsic::amdgcn_raw_buffer_store:
7958   case Intrinsic::amdgcn_raw_buffer_store_format: {
7959     const bool IsFormat =
7960         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7961 
7962     SDValue VData = Op.getOperand(2);
7963     EVT VDataVT = VData.getValueType();
7964     EVT EltType = VDataVT.getScalarType();
7965     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7966     if (IsD16) {
7967       VData = handleD16VData(VData, DAG);
7968       VDataVT = VData.getValueType();
7969     }
7970 
7971     if (!isTypeLegal(VDataVT)) {
7972       VData =
7973           DAG.getNode(ISD::BITCAST, DL,
7974                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7975     }
7976 
7977     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7978     SDValue Ops[] = {
7979       Chain,
7980       VData,
7981       Op.getOperand(3), // rsrc
7982       DAG.getConstant(0, DL, MVT::i32), // vindex
7983       Offsets.first,    // voffset
7984       Op.getOperand(5), // soffset
7985       Offsets.second,   // offset
7986       Op.getOperand(6), // cachepolicy, swizzled buffer
7987       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7988     };
7989     unsigned Opc =
7990         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7991     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7992     MemSDNode *M = cast<MemSDNode>(Op);
7993     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7994 
7995     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7996     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7997       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7998 
7999     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8000                                    M->getMemoryVT(), M->getMemOperand());
8001   }
8002 
8003   case Intrinsic::amdgcn_struct_buffer_store:
8004   case Intrinsic::amdgcn_struct_buffer_store_format: {
8005     const bool IsFormat =
8006         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8007 
8008     SDValue VData = Op.getOperand(2);
8009     EVT VDataVT = VData.getValueType();
8010     EVT EltType = VDataVT.getScalarType();
8011     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8012 
8013     if (IsD16) {
8014       VData = handleD16VData(VData, DAG);
8015       VDataVT = VData.getValueType();
8016     }
8017 
8018     if (!isTypeLegal(VDataVT)) {
8019       VData =
8020           DAG.getNode(ISD::BITCAST, DL,
8021                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8022     }
8023 
8024     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8025     SDValue Ops[] = {
8026       Chain,
8027       VData,
8028       Op.getOperand(3), // rsrc
8029       Op.getOperand(4), // vindex
8030       Offsets.first,    // voffset
8031       Op.getOperand(6), // soffset
8032       Offsets.second,   // offset
8033       Op.getOperand(7), // cachepolicy, swizzled buffer
8034       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8035     };
8036     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8037                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8038     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8039     MemSDNode *M = cast<MemSDNode>(Op);
8040     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8041 
8042     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8043     EVT VDataType = VData.getValueType().getScalarType();
8044     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8045       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8046 
8047     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8048                                    M->getMemoryVT(), M->getMemOperand());
8049   }
8050   case Intrinsic::amdgcn_raw_buffer_load_lds:
8051   case Intrinsic::amdgcn_struct_buffer_load_lds: {
8052     unsigned Opc;
8053     bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8054     unsigned OpOffset = HasVIndex ? 1 : 0;
8055     SDValue VOffset = Op.getOperand(5 + OpOffset);
8056     auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8057     bool HasVOffset = !CVOffset || !CVOffset->isZero();
8058     unsigned Size = Op->getConstantOperandVal(4);
8059 
8060     switch (Size) {
8061     default:
8062       return SDValue();
8063     case 1:
8064       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8065                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8066                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8067                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8068       break;
8069     case 2:
8070       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8071                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8072                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8073                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8074       break;
8075     case 4:
8076       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8077                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8078                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8079                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8080       break;
8081     }
8082 
8083     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8084 
8085     SmallVector<SDValue, 8> Ops;
8086 
8087     if (HasVIndex && HasVOffset)
8088       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8089                                        { Op.getOperand(5), // VIndex
8090                                          VOffset }));
8091     else if (HasVIndex)
8092       Ops.push_back(Op.getOperand(5));
8093     else if (HasVOffset)
8094       Ops.push_back(VOffset);
8095 
8096     Ops.push_back(Op.getOperand(2));           // rsrc
8097     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8098     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8099     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8100     Ops.push_back(
8101       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8102     Ops.push_back(
8103       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
8104     Ops.push_back(M0Val.getValue(0)); // Chain
8105     Ops.push_back(M0Val.getValue(1)); // Glue
8106 
8107     auto *M = cast<MemSDNode>(Op);
8108     MachineMemOperand *LoadMMO = M->getMemOperand();
8109     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8110     LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8111     MachinePointerInfo StorePtrI = LoadPtrI;
8112     StorePtrI.V = nullptr;
8113     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8114 
8115     auto F = LoadMMO->getFlags() &
8116              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8117     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8118                                       Size, LoadMMO->getBaseAlign());
8119 
8120     MachineMemOperand *StoreMMO =
8121         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8122                                 sizeof(int32_t), LoadMMO->getBaseAlign());
8123 
8124     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8125     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8126 
8127     return SDValue(Load, 0);
8128   }
8129   case Intrinsic::amdgcn_global_load_lds: {
8130     unsigned Opc;
8131     unsigned Size = Op->getConstantOperandVal(4);
8132     switch (Size) {
8133     default:
8134       return SDValue();
8135     case 1:
8136       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8137       break;
8138     case 2:
8139       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8140       break;
8141     case 4:
8142       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8143       break;
8144     }
8145 
8146     auto *M = cast<MemSDNode>(Op);
8147     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8148 
8149     SmallVector<SDValue, 6> Ops;
8150 
8151     SDValue Addr = Op.getOperand(2); // Global ptr
8152     SDValue VOffset;
8153     // Try to split SAddr and VOffset. Global and LDS pointers share the same
8154     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8155     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8156       SDValue LHS = Addr.getOperand(0);
8157       SDValue RHS = Addr.getOperand(1);
8158 
8159       if (LHS->isDivergent())
8160         std::swap(LHS, RHS);
8161 
8162       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8163           RHS.getOperand(0).getValueType() == MVT::i32) {
8164         // add (i64 sgpr), (zero_extend (i32 vgpr))
8165         Addr = LHS;
8166         VOffset = RHS.getOperand(0);
8167       }
8168     }
8169 
8170     Ops.push_back(Addr);
8171     if (!Addr->isDivergent()) {
8172       Opc = AMDGPU::getGlobalSaddrOp(Opc);
8173       if (!VOffset)
8174         VOffset = SDValue(
8175             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8176                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8177       Ops.push_back(VOffset);
8178     }
8179 
8180     Ops.push_back(Op.getOperand(5));  // Offset
8181     Ops.push_back(Op.getOperand(6));  // CPol
8182     Ops.push_back(M0Val.getValue(0)); // Chain
8183     Ops.push_back(M0Val.getValue(1)); // Glue
8184 
8185     MachineMemOperand *LoadMMO = M->getMemOperand();
8186     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8187     LoadPtrI.Offset = Op->getConstantOperandVal(5);
8188     MachinePointerInfo StorePtrI = LoadPtrI;
8189     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8190     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8191     auto F = LoadMMO->getFlags() &
8192              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8193     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8194                                       Size, LoadMMO->getBaseAlign());
8195     MachineMemOperand *StoreMMO =
8196         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8197                                 sizeof(int32_t), Align(4));
8198 
8199     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8200     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8201 
8202     return SDValue(Load, 0);
8203   }
8204   case Intrinsic::amdgcn_end_cf:
8205     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8206                                       Op->getOperand(2), Chain), 0);
8207 
8208   default: {
8209     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8210             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8211       return lowerImage(Op, ImageDimIntr, DAG, true);
8212 
8213     return Op;
8214   }
8215   }
8216 }
8217 
8218 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8219 // offset (the offset that is included in bounds checking and swizzling, to be
8220 // split between the instruction's voffset and immoffset fields) and soffset
8221 // (the offset that is excluded from bounds checking and swizzling, to go in
8222 // the instruction's soffset field).  This function takes the first kind of
8223 // offset and figures out how to split it between voffset and immoffset.
8224 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8225     SDValue Offset, SelectionDAG &DAG) const {
8226   SDLoc DL(Offset);
8227   const unsigned MaxImm = 4095;
8228   SDValue N0 = Offset;
8229   ConstantSDNode *C1 = nullptr;
8230 
8231   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8232     N0 = SDValue();
8233   else if (DAG.isBaseWithConstantOffset(N0)) {
8234     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8235     N0 = N0.getOperand(0);
8236   }
8237 
8238   if (C1) {
8239     unsigned ImmOffset = C1->getZExtValue();
8240     // If the immediate value is too big for the immoffset field, put the value
8241     // and -4096 into the immoffset field so that the value that is copied/added
8242     // for the voffset field is a multiple of 4096, and it stands more chance
8243     // of being CSEd with the copy/add for another similar load/store.
8244     // However, do not do that rounding down to a multiple of 4096 if that is a
8245     // negative number, as it appears to be illegal to have a negative offset
8246     // in the vgpr, even if adding the immediate offset makes it positive.
8247     unsigned Overflow = ImmOffset & ~MaxImm;
8248     ImmOffset -= Overflow;
8249     if ((int32_t)Overflow < 0) {
8250       Overflow += ImmOffset;
8251       ImmOffset = 0;
8252     }
8253     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8254     if (Overflow) {
8255       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8256       if (!N0)
8257         N0 = OverflowVal;
8258       else {
8259         SDValue Ops[] = { N0, OverflowVal };
8260         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8261       }
8262     }
8263   }
8264   if (!N0)
8265     N0 = DAG.getConstant(0, DL, MVT::i32);
8266   if (!C1)
8267     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8268   return {N0, SDValue(C1, 0)};
8269 }
8270 
8271 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8272 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8273 // pointed to by Offsets.
8274 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8275                                         SelectionDAG &DAG, SDValue *Offsets,
8276                                         Align Alignment) const {
8277   SDLoc DL(CombinedOffset);
8278   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8279     uint32_t Imm = C->getZExtValue();
8280     uint32_t SOffset, ImmOffset;
8281     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8282                                  Alignment)) {
8283       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8284       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8285       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8286       return;
8287     }
8288   }
8289   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8290     SDValue N0 = CombinedOffset.getOperand(0);
8291     SDValue N1 = CombinedOffset.getOperand(1);
8292     uint32_t SOffset, ImmOffset;
8293     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8294     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8295                                                 Subtarget, Alignment)) {
8296       Offsets[0] = N0;
8297       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8298       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8299       return;
8300     }
8301   }
8302   Offsets[0] = CombinedOffset;
8303   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8304   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8305 }
8306 
8307 // Handle 8 bit and 16 bit buffer loads
8308 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8309                                                      EVT LoadVT, SDLoc DL,
8310                                                      ArrayRef<SDValue> Ops,
8311                                                      MemSDNode *M) const {
8312   EVT IntVT = LoadVT.changeTypeToInteger();
8313   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8314          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8315 
8316   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8317   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8318                                                Ops, IntVT,
8319                                                M->getMemOperand());
8320   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8321   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8322 
8323   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8324 }
8325 
8326 // Handle 8 bit and 16 bit buffer stores
8327 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8328                                                       EVT VDataType, SDLoc DL,
8329                                                       SDValue Ops[],
8330                                                       MemSDNode *M) const {
8331   if (VDataType == MVT::f16)
8332     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8333 
8334   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8335   Ops[1] = BufferStoreExt;
8336   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8337                                  AMDGPUISD::BUFFER_STORE_SHORT;
8338   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8339   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8340                                      M->getMemOperand());
8341 }
8342 
8343 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8344                                  ISD::LoadExtType ExtType, SDValue Op,
8345                                  const SDLoc &SL, EVT VT) {
8346   if (VT.bitsLT(Op.getValueType()))
8347     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8348 
8349   switch (ExtType) {
8350   case ISD::SEXTLOAD:
8351     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8352   case ISD::ZEXTLOAD:
8353     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8354   case ISD::EXTLOAD:
8355     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8356   case ISD::NON_EXTLOAD:
8357     return Op;
8358   }
8359 
8360   llvm_unreachable("invalid ext type");
8361 }
8362 
8363 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8364   SelectionDAG &DAG = DCI.DAG;
8365   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8366     return SDValue();
8367 
8368   // FIXME: Constant loads should all be marked invariant.
8369   unsigned AS = Ld->getAddressSpace();
8370   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8371       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8372       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8373     return SDValue();
8374 
8375   // Don't do this early, since it may interfere with adjacent load merging for
8376   // illegal types. We can avoid losing alignment information for exotic types
8377   // pre-legalize.
8378   EVT MemVT = Ld->getMemoryVT();
8379   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8380       MemVT.getSizeInBits() >= 32)
8381     return SDValue();
8382 
8383   SDLoc SL(Ld);
8384 
8385   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8386          "unexpected vector extload");
8387 
8388   // TODO: Drop only high part of range.
8389   SDValue Ptr = Ld->getBasePtr();
8390   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8391                                 MVT::i32, SL, Ld->getChain(), Ptr,
8392                                 Ld->getOffset(),
8393                                 Ld->getPointerInfo(), MVT::i32,
8394                                 Ld->getAlignment(),
8395                                 Ld->getMemOperand()->getFlags(),
8396                                 Ld->getAAInfo(),
8397                                 nullptr); // Drop ranges
8398 
8399   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8400   if (MemVT.isFloatingPoint()) {
8401     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8402            "unexpected fp extload");
8403     TruncVT = MemVT.changeTypeToInteger();
8404   }
8405 
8406   SDValue Cvt = NewLoad;
8407   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8408     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8409                       DAG.getValueType(TruncVT));
8410   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8411              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8412     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8413   } else {
8414     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8415   }
8416 
8417   EVT VT = Ld->getValueType(0);
8418   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8419 
8420   DCI.AddToWorklist(Cvt.getNode());
8421 
8422   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8423   // the appropriate extension from the 32-bit load.
8424   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8425   DCI.AddToWorklist(Cvt.getNode());
8426 
8427   // Handle conversion back to floating point if necessary.
8428   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8429 
8430   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8431 }
8432 
8433 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8434   SDLoc DL(Op);
8435   LoadSDNode *Load = cast<LoadSDNode>(Op);
8436   ISD::LoadExtType ExtType = Load->getExtensionType();
8437   EVT MemVT = Load->getMemoryVT();
8438 
8439   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8440     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8441       return SDValue();
8442 
8443     // FIXME: Copied from PPC
8444     // First, load into 32 bits, then truncate to 1 bit.
8445 
8446     SDValue Chain = Load->getChain();
8447     SDValue BasePtr = Load->getBasePtr();
8448     MachineMemOperand *MMO = Load->getMemOperand();
8449 
8450     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8451 
8452     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8453                                    BasePtr, RealMemVT, MMO);
8454 
8455     if (!MemVT.isVector()) {
8456       SDValue Ops[] = {
8457         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8458         NewLD.getValue(1)
8459       };
8460 
8461       return DAG.getMergeValues(Ops, DL);
8462     }
8463 
8464     SmallVector<SDValue, 3> Elts;
8465     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8466       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8467                                 DAG.getConstant(I, DL, MVT::i32));
8468 
8469       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8470     }
8471 
8472     SDValue Ops[] = {
8473       DAG.getBuildVector(MemVT, DL, Elts),
8474       NewLD.getValue(1)
8475     };
8476 
8477     return DAG.getMergeValues(Ops, DL);
8478   }
8479 
8480   if (!MemVT.isVector())
8481     return SDValue();
8482 
8483   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8484          "Custom lowering for non-i32 vectors hasn't been implemented.");
8485 
8486   unsigned Alignment = Load->getAlignment();
8487   unsigned AS = Load->getAddressSpace();
8488   if (Subtarget->hasLDSMisalignedBug() &&
8489       AS == AMDGPUAS::FLAT_ADDRESS &&
8490       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8491     return SplitVectorLoad(Op, DAG);
8492   }
8493 
8494   MachineFunction &MF = DAG.getMachineFunction();
8495   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8496   // If there is a possibility that flat instruction access scratch memory
8497   // then we need to use the same legalization rules we use for private.
8498   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8499       !Subtarget->hasMultiDwordFlatScratchAddressing())
8500     AS = MFI->hasFlatScratchInit() ?
8501          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8502 
8503   unsigned NumElements = MemVT.getVectorNumElements();
8504 
8505   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8506       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8507     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8508       if (MemVT.isPow2VectorType())
8509         return SDValue();
8510       return WidenOrSplitVectorLoad(Op, DAG);
8511     }
8512     // Non-uniform loads will be selected to MUBUF instructions, so they
8513     // have the same legalization requirements as global and private
8514     // loads.
8515     //
8516   }
8517 
8518   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8519       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8520       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8521     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8522         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8523         Alignment >= 4 && NumElements < 32) {
8524       if (MemVT.isPow2VectorType())
8525         return SDValue();
8526       return WidenOrSplitVectorLoad(Op, DAG);
8527     }
8528     // Non-uniform loads will be selected to MUBUF instructions, so they
8529     // have the same legalization requirements as global and private
8530     // loads.
8531     //
8532   }
8533   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8534       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8535       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8536       AS == AMDGPUAS::FLAT_ADDRESS) {
8537     if (NumElements > 4)
8538       return SplitVectorLoad(Op, DAG);
8539     // v3 loads not supported on SI.
8540     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8541       return WidenOrSplitVectorLoad(Op, DAG);
8542 
8543     // v3 and v4 loads are supported for private and global memory.
8544     return SDValue();
8545   }
8546   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8547     // Depending on the setting of the private_element_size field in the
8548     // resource descriptor, we can only make private accesses up to a certain
8549     // size.
8550     switch (Subtarget->getMaxPrivateElementSize()) {
8551     case 4: {
8552       SDValue Ops[2];
8553       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8554       return DAG.getMergeValues(Ops, DL);
8555     }
8556     case 8:
8557       if (NumElements > 2)
8558         return SplitVectorLoad(Op, DAG);
8559       return SDValue();
8560     case 16:
8561       // Same as global/flat
8562       if (NumElements > 4)
8563         return SplitVectorLoad(Op, DAG);
8564       // v3 loads not supported on SI.
8565       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8566         return WidenOrSplitVectorLoad(Op, DAG);
8567 
8568       return SDValue();
8569     default:
8570       llvm_unreachable("unsupported private_element_size");
8571     }
8572   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8573     bool Fast = false;
8574     auto Flags = Load->getMemOperand()->getFlags();
8575     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8576                                            Load->getAlign(), Flags, &Fast) &&
8577         Fast)
8578       return SDValue();
8579 
8580     if (MemVT.isVector())
8581       return SplitVectorLoad(Op, DAG);
8582   }
8583 
8584   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8585                                       MemVT, *Load->getMemOperand())) {
8586     SDValue Ops[2];
8587     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8588     return DAG.getMergeValues(Ops, DL);
8589   }
8590 
8591   return SDValue();
8592 }
8593 
8594 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8595   EVT VT = Op.getValueType();
8596   if (VT.getSizeInBits() == 128)
8597     return splitTernaryVectorOp(Op, DAG);
8598 
8599   assert(VT.getSizeInBits() == 64);
8600 
8601   SDLoc DL(Op);
8602   SDValue Cond = Op.getOperand(0);
8603 
8604   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8605   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8606 
8607   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8608   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8609 
8610   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8611   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8612 
8613   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8614 
8615   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8616   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8617 
8618   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8619 
8620   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8621   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8622 }
8623 
8624 // Catch division cases where we can use shortcuts with rcp and rsq
8625 // instructions.
8626 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8627                                               SelectionDAG &DAG) const {
8628   SDLoc SL(Op);
8629   SDValue LHS = Op.getOperand(0);
8630   SDValue RHS = Op.getOperand(1);
8631   EVT VT = Op.getValueType();
8632   const SDNodeFlags Flags = Op->getFlags();
8633 
8634   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8635 
8636   // Without !fpmath accuracy information, we can't do more because we don't
8637   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8638   if (!AllowInaccurateRcp)
8639     return SDValue();
8640 
8641   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8642     if (CLHS->isExactlyValue(1.0)) {
8643       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8644       // the CI documentation has a worst case error of 1 ulp.
8645       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8646       // use it as long as we aren't trying to use denormals.
8647       //
8648       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8649 
8650       // 1.0 / sqrt(x) -> rsq(x)
8651 
8652       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8653       // error seems really high at 2^29 ULP.
8654       if (RHS.getOpcode() == ISD::FSQRT)
8655         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8656 
8657       // 1.0 / x -> rcp(x)
8658       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8659     }
8660 
8661     // Same as for 1.0, but expand the sign out of the constant.
8662     if (CLHS->isExactlyValue(-1.0)) {
8663       // -1.0 / x -> rcp (fneg x)
8664       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8665       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8666     }
8667   }
8668 
8669   // Turn into multiply by the reciprocal.
8670   // x / y -> x * (1.0 / y)
8671   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8672   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8673 }
8674 
8675 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8676                                                 SelectionDAG &DAG) const {
8677   SDLoc SL(Op);
8678   SDValue X = Op.getOperand(0);
8679   SDValue Y = Op.getOperand(1);
8680   EVT VT = Op.getValueType();
8681   const SDNodeFlags Flags = Op->getFlags();
8682 
8683   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8684                             DAG.getTarget().Options.UnsafeFPMath;
8685   if (!AllowInaccurateDiv)
8686     return SDValue();
8687 
8688   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8689   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8690 
8691   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8692   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8693 
8694   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8695   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8696   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8697   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8698   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8699   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8700 }
8701 
8702 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8703                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8704                           SDNodeFlags Flags) {
8705   if (GlueChain->getNumValues() <= 1) {
8706     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8707   }
8708 
8709   assert(GlueChain->getNumValues() == 3);
8710 
8711   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8712   switch (Opcode) {
8713   default: llvm_unreachable("no chain equivalent for opcode");
8714   case ISD::FMUL:
8715     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8716     break;
8717   }
8718 
8719   return DAG.getNode(Opcode, SL, VTList,
8720                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8721                      Flags);
8722 }
8723 
8724 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8725                            EVT VT, SDValue A, SDValue B, SDValue C,
8726                            SDValue GlueChain, SDNodeFlags Flags) {
8727   if (GlueChain->getNumValues() <= 1) {
8728     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8729   }
8730 
8731   assert(GlueChain->getNumValues() == 3);
8732 
8733   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8734   switch (Opcode) {
8735   default: llvm_unreachable("no chain equivalent for opcode");
8736   case ISD::FMA:
8737     Opcode = AMDGPUISD::FMA_W_CHAIN;
8738     break;
8739   }
8740 
8741   return DAG.getNode(Opcode, SL, VTList,
8742                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8743                      Flags);
8744 }
8745 
8746 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8747   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8748     return FastLowered;
8749 
8750   SDLoc SL(Op);
8751   SDValue Src0 = Op.getOperand(0);
8752   SDValue Src1 = Op.getOperand(1);
8753 
8754   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8755   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8756 
8757   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8758   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8759 
8760   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8761   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8762 
8763   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8764 }
8765 
8766 // Faster 2.5 ULP division that does not support denormals.
8767 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8768   SDLoc SL(Op);
8769   SDValue LHS = Op.getOperand(1);
8770   SDValue RHS = Op.getOperand(2);
8771 
8772   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8773 
8774   const APFloat K0Val(BitsToFloat(0x6f800000));
8775   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8776 
8777   const APFloat K1Val(BitsToFloat(0x2f800000));
8778   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8779 
8780   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8781 
8782   EVT SetCCVT =
8783     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8784 
8785   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8786 
8787   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8788 
8789   // TODO: Should this propagate fast-math-flags?
8790   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8791 
8792   // rcp does not support denormals.
8793   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8794 
8795   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8796 
8797   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8798 }
8799 
8800 // Returns immediate value for setting the F32 denorm mode when using the
8801 // S_DENORM_MODE instruction.
8802 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8803                                     const SDLoc &SL, const GCNSubtarget *ST) {
8804   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8805   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8806                                 ? FP_DENORM_FLUSH_NONE
8807                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8808 
8809   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8810   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8811 }
8812 
8813 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8814   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8815     return FastLowered;
8816 
8817   // The selection matcher assumes anything with a chain selecting to a
8818   // mayRaiseFPException machine instruction. Since we're introducing a chain
8819   // here, we need to explicitly report nofpexcept for the regular fdiv
8820   // lowering.
8821   SDNodeFlags Flags = Op->getFlags();
8822   Flags.setNoFPExcept(true);
8823 
8824   SDLoc SL(Op);
8825   SDValue LHS = Op.getOperand(0);
8826   SDValue RHS = Op.getOperand(1);
8827 
8828   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8829 
8830   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8831 
8832   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8833                                           {RHS, RHS, LHS}, Flags);
8834   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8835                                         {LHS, RHS, LHS}, Flags);
8836 
8837   // Denominator is scaled to not be denormal, so using rcp is ok.
8838   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8839                                   DenominatorScaled, Flags);
8840   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8841                                      DenominatorScaled, Flags);
8842 
8843   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8844                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8845                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8846   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8847 
8848   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8849 
8850   if (!HasFP32Denormals) {
8851     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8852     // lowering. The chain dependence is insufficient, and we need glue. We do
8853     // not need the glue variants in a strictfp function.
8854 
8855     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8856 
8857     SDNode *EnableDenorm;
8858     if (Subtarget->hasDenormModeInst()) {
8859       const SDValue EnableDenormValue =
8860           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8861 
8862       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8863                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8864     } else {
8865       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8866                                                         SL, MVT::i32);
8867       EnableDenorm =
8868           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8869                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8870     }
8871 
8872     SDValue Ops[3] = {
8873       NegDivScale0,
8874       SDValue(EnableDenorm, 0),
8875       SDValue(EnableDenorm, 1)
8876     };
8877 
8878     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8879   }
8880 
8881   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8882                              ApproxRcp, One, NegDivScale0, Flags);
8883 
8884   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8885                              ApproxRcp, Fma0, Flags);
8886 
8887   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8888                            Fma1, Fma1, Flags);
8889 
8890   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8891                              NumeratorScaled, Mul, Flags);
8892 
8893   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8894                              Fma2, Fma1, Mul, Fma2, Flags);
8895 
8896   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8897                              NumeratorScaled, Fma3, Flags);
8898 
8899   if (!HasFP32Denormals) {
8900     SDNode *DisableDenorm;
8901     if (Subtarget->hasDenormModeInst()) {
8902       const SDValue DisableDenormValue =
8903           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8904 
8905       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8906                                   Fma4.getValue(1), DisableDenormValue,
8907                                   Fma4.getValue(2)).getNode();
8908     } else {
8909       const SDValue DisableDenormValue =
8910           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8911 
8912       DisableDenorm = DAG.getMachineNode(
8913           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8914           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8915     }
8916 
8917     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8918                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8919     DAG.setRoot(OutputChain);
8920   }
8921 
8922   SDValue Scale = NumeratorScaled.getValue(1);
8923   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8924                              {Fma4, Fma1, Fma3, Scale}, Flags);
8925 
8926   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8927 }
8928 
8929 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8930   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8931     return FastLowered;
8932 
8933   SDLoc SL(Op);
8934   SDValue X = Op.getOperand(0);
8935   SDValue Y = Op.getOperand(1);
8936 
8937   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8938 
8939   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8940 
8941   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8942 
8943   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8944 
8945   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8946 
8947   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8948 
8949   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8950 
8951   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8952 
8953   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8954 
8955   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8956   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8957 
8958   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8959                              NegDivScale0, Mul, DivScale1);
8960 
8961   SDValue Scale;
8962 
8963   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8964     // Workaround a hardware bug on SI where the condition output from div_scale
8965     // is not usable.
8966 
8967     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8968 
8969     // Figure out if the scale to use for div_fmas.
8970     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8971     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8972     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8973     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8974 
8975     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8976     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8977 
8978     SDValue Scale0Hi
8979       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8980     SDValue Scale1Hi
8981       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8982 
8983     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8984     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8985     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8986   } else {
8987     Scale = DivScale1.getValue(1);
8988   }
8989 
8990   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8991                              Fma4, Fma3, Mul, Scale);
8992 
8993   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8994 }
8995 
8996 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8997   EVT VT = Op.getValueType();
8998 
8999   if (VT == MVT::f32)
9000     return LowerFDIV32(Op, DAG);
9001 
9002   if (VT == MVT::f64)
9003     return LowerFDIV64(Op, DAG);
9004 
9005   if (VT == MVT::f16)
9006     return LowerFDIV16(Op, DAG);
9007 
9008   llvm_unreachable("Unexpected type for fdiv");
9009 }
9010 
9011 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9012   SDLoc DL(Op);
9013   StoreSDNode *Store = cast<StoreSDNode>(Op);
9014   EVT VT = Store->getMemoryVT();
9015 
9016   if (VT == MVT::i1) {
9017     return DAG.getTruncStore(Store->getChain(), DL,
9018        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9019        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9020   }
9021 
9022   assert(VT.isVector() &&
9023          Store->getValue().getValueType().getScalarType() == MVT::i32);
9024 
9025   unsigned AS = Store->getAddressSpace();
9026   if (Subtarget->hasLDSMisalignedBug() &&
9027       AS == AMDGPUAS::FLAT_ADDRESS &&
9028       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9029     return SplitVectorStore(Op, DAG);
9030   }
9031 
9032   MachineFunction &MF = DAG.getMachineFunction();
9033   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9034   // If there is a possibility that flat instruction access scratch memory
9035   // then we need to use the same legalization rules we use for private.
9036   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9037       !Subtarget->hasMultiDwordFlatScratchAddressing())
9038     AS = MFI->hasFlatScratchInit() ?
9039          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9040 
9041   unsigned NumElements = VT.getVectorNumElements();
9042   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9043       AS == AMDGPUAS::FLAT_ADDRESS) {
9044     if (NumElements > 4)
9045       return SplitVectorStore(Op, DAG);
9046     // v3 stores not supported on SI.
9047     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9048       return SplitVectorStore(Op, DAG);
9049 
9050     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9051                                         VT, *Store->getMemOperand()))
9052       return expandUnalignedStore(Store, DAG);
9053 
9054     return SDValue();
9055   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9056     switch (Subtarget->getMaxPrivateElementSize()) {
9057     case 4:
9058       return scalarizeVectorStore(Store, DAG);
9059     case 8:
9060       if (NumElements > 2)
9061         return SplitVectorStore(Op, DAG);
9062       return SDValue();
9063     case 16:
9064       if (NumElements > 4 ||
9065           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9066         return SplitVectorStore(Op, DAG);
9067       return SDValue();
9068     default:
9069       llvm_unreachable("unsupported private_element_size");
9070     }
9071   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9072     bool Fast = false;
9073     auto Flags = Store->getMemOperand()->getFlags();
9074     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9075                                            Store->getAlign(), Flags, &Fast) &&
9076         Fast)
9077       return SDValue();
9078 
9079     if (VT.isVector())
9080       return SplitVectorStore(Op, DAG);
9081 
9082     return expandUnalignedStore(Store, DAG);
9083   }
9084 
9085   // Probably an invalid store. If so we'll end up emitting a selection error.
9086   return SDValue();
9087 }
9088 
9089 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9090   SDLoc DL(Op);
9091   EVT VT = Op.getValueType();
9092   SDValue Arg = Op.getOperand(0);
9093   SDValue TrigVal;
9094 
9095   // Propagate fast-math flags so that the multiply we introduce can be folded
9096   // if Arg is already the result of a multiply by constant.
9097   auto Flags = Op->getFlags();
9098 
9099   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9100 
9101   if (Subtarget->hasTrigReducedRange()) {
9102     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9103     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9104   } else {
9105     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9106   }
9107 
9108   switch (Op.getOpcode()) {
9109   case ISD::FCOS:
9110     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9111   case ISD::FSIN:
9112     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9113   default:
9114     llvm_unreachable("Wrong trig opcode");
9115   }
9116 }
9117 
9118 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9119   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9120   assert(AtomicNode->isCompareAndSwap());
9121   unsigned AS = AtomicNode->getAddressSpace();
9122 
9123   // No custom lowering required for local address space
9124   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9125     return Op;
9126 
9127   // Non-local address space requires custom lowering for atomic compare
9128   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9129   SDLoc DL(Op);
9130   SDValue ChainIn = Op.getOperand(0);
9131   SDValue Addr = Op.getOperand(1);
9132   SDValue Old = Op.getOperand(2);
9133   SDValue New = Op.getOperand(3);
9134   EVT VT = Op.getValueType();
9135   MVT SimpleVT = VT.getSimpleVT();
9136   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9137 
9138   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9139   SDValue Ops[] = { ChainIn, Addr, NewOld };
9140 
9141   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9142                                  Ops, VT, AtomicNode->getMemOperand());
9143 }
9144 
9145 //===----------------------------------------------------------------------===//
9146 // Custom DAG optimizations
9147 //===----------------------------------------------------------------------===//
9148 
9149 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9150                                                      DAGCombinerInfo &DCI) const {
9151   EVT VT = N->getValueType(0);
9152   EVT ScalarVT = VT.getScalarType();
9153   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9154     return SDValue();
9155 
9156   SelectionDAG &DAG = DCI.DAG;
9157   SDLoc DL(N);
9158 
9159   SDValue Src = N->getOperand(0);
9160   EVT SrcVT = Src.getValueType();
9161 
9162   // TODO: We could try to match extracting the higher bytes, which would be
9163   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9164   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9165   // about in practice.
9166   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9167     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9168       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9169       DCI.AddToWorklist(Cvt.getNode());
9170 
9171       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9172       if (ScalarVT != MVT::f32) {
9173         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9174                           DAG.getTargetConstant(0, DL, MVT::i32));
9175       }
9176       return Cvt;
9177     }
9178   }
9179 
9180   return SDValue();
9181 }
9182 
9183 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9184 
9185 // This is a variant of
9186 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9187 //
9188 // The normal DAG combiner will do this, but only if the add has one use since
9189 // that would increase the number of instructions.
9190 //
9191 // This prevents us from seeing a constant offset that can be folded into a
9192 // memory instruction's addressing mode. If we know the resulting add offset of
9193 // a pointer can be folded into an addressing offset, we can replace the pointer
9194 // operand with the add of new constant offset. This eliminates one of the uses,
9195 // and may allow the remaining use to also be simplified.
9196 //
9197 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9198                                                unsigned AddrSpace,
9199                                                EVT MemVT,
9200                                                DAGCombinerInfo &DCI) const {
9201   SDValue N0 = N->getOperand(0);
9202   SDValue N1 = N->getOperand(1);
9203 
9204   // We only do this to handle cases where it's profitable when there are
9205   // multiple uses of the add, so defer to the standard combine.
9206   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9207       N0->hasOneUse())
9208     return SDValue();
9209 
9210   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9211   if (!CN1)
9212     return SDValue();
9213 
9214   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9215   if (!CAdd)
9216     return SDValue();
9217 
9218   // If the resulting offset is too large, we can't fold it into the addressing
9219   // mode offset.
9220   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9221   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9222 
9223   AddrMode AM;
9224   AM.HasBaseReg = true;
9225   AM.BaseOffs = Offset.getSExtValue();
9226   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9227     return SDValue();
9228 
9229   SelectionDAG &DAG = DCI.DAG;
9230   SDLoc SL(N);
9231   EVT VT = N->getValueType(0);
9232 
9233   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9234   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9235 
9236   SDNodeFlags Flags;
9237   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9238                           (N0.getOpcode() == ISD::OR ||
9239                            N0->getFlags().hasNoUnsignedWrap()));
9240 
9241   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9242 }
9243 
9244 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9245 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9246 /// specific intrinsic, but they all place the pointer operand first.
9247 static unsigned getBasePtrIndex(const MemSDNode *N) {
9248   switch (N->getOpcode()) {
9249   case ISD::STORE:
9250   case ISD::INTRINSIC_W_CHAIN:
9251   case ISD::INTRINSIC_VOID:
9252     return 2;
9253   default:
9254     return 1;
9255   }
9256 }
9257 
9258 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9259                                                   DAGCombinerInfo &DCI) const {
9260   SelectionDAG &DAG = DCI.DAG;
9261   SDLoc SL(N);
9262 
9263   unsigned PtrIdx = getBasePtrIndex(N);
9264   SDValue Ptr = N->getOperand(PtrIdx);
9265 
9266   // TODO: We could also do this for multiplies.
9267   if (Ptr.getOpcode() == ISD::SHL) {
9268     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9269                                           N->getMemoryVT(), DCI);
9270     if (NewPtr) {
9271       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9272 
9273       NewOps[PtrIdx] = NewPtr;
9274       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9275     }
9276   }
9277 
9278   return SDValue();
9279 }
9280 
9281 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9282   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9283          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9284          (Opc == ISD::XOR && Val == 0);
9285 }
9286 
9287 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9288 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9289 // integer combine opportunities since most 64-bit operations are decomposed
9290 // this way.  TODO: We won't want this for SALU especially if it is an inline
9291 // immediate.
9292 SDValue SITargetLowering::splitBinaryBitConstantOp(
9293   DAGCombinerInfo &DCI,
9294   const SDLoc &SL,
9295   unsigned Opc, SDValue LHS,
9296   const ConstantSDNode *CRHS) const {
9297   uint64_t Val = CRHS->getZExtValue();
9298   uint32_t ValLo = Lo_32(Val);
9299   uint32_t ValHi = Hi_32(Val);
9300   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9301 
9302     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9303          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9304         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9305     // If we need to materialize a 64-bit immediate, it will be split up later
9306     // anyway. Avoid creating the harder to understand 64-bit immediate
9307     // materialization.
9308     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9309   }
9310 
9311   return SDValue();
9312 }
9313 
9314 // Returns true if argument is a boolean value which is not serialized into
9315 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9316 static bool isBoolSGPR(SDValue V) {
9317   if (V.getValueType() != MVT::i1)
9318     return false;
9319   switch (V.getOpcode()) {
9320   default:
9321     break;
9322   case ISD::SETCC:
9323   case AMDGPUISD::FP_CLASS:
9324     return true;
9325   case ISD::AND:
9326   case ISD::OR:
9327   case ISD::XOR:
9328     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9329   }
9330   return false;
9331 }
9332 
9333 // If a constant has all zeroes or all ones within each byte return it.
9334 // Otherwise return 0.
9335 static uint32_t getConstantPermuteMask(uint32_t C) {
9336   // 0xff for any zero byte in the mask
9337   uint32_t ZeroByteMask = 0;
9338   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9339   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9340   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9341   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9342   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9343   if ((NonZeroByteMask & C) != NonZeroByteMask)
9344     return 0; // Partial bytes selected.
9345   return C;
9346 }
9347 
9348 // Check if a node selects whole bytes from its operand 0 starting at a byte
9349 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9350 // or -1 if not succeeded.
9351 // Note byte select encoding:
9352 // value 0-3 selects corresponding source byte;
9353 // value 0xc selects zero;
9354 // value 0xff selects 0xff.
9355 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9356   assert(V.getValueSizeInBits() == 32);
9357 
9358   if (V.getNumOperands() != 2)
9359     return ~0;
9360 
9361   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9362   if (!N1)
9363     return ~0;
9364 
9365   uint32_t C = N1->getZExtValue();
9366 
9367   switch (V.getOpcode()) {
9368   default:
9369     break;
9370   case ISD::AND:
9371     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9372       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9373     }
9374     break;
9375 
9376   case ISD::OR:
9377     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9378       return (0x03020100 & ~ConstMask) | ConstMask;
9379     }
9380     break;
9381 
9382   case ISD::SHL:
9383     if (C % 8)
9384       return ~0;
9385 
9386     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9387 
9388   case ISD::SRL:
9389     if (C % 8)
9390       return ~0;
9391 
9392     return uint32_t(0x0c0c0c0c03020100ull >> C);
9393   }
9394 
9395   return ~0;
9396 }
9397 
9398 SDValue SITargetLowering::performAndCombine(SDNode *N,
9399                                             DAGCombinerInfo &DCI) const {
9400   if (DCI.isBeforeLegalize())
9401     return SDValue();
9402 
9403   SelectionDAG &DAG = DCI.DAG;
9404   EVT VT = N->getValueType(0);
9405   SDValue LHS = N->getOperand(0);
9406   SDValue RHS = N->getOperand(1);
9407 
9408 
9409   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9410   if (VT == MVT::i64 && CRHS) {
9411     if (SDValue Split
9412         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9413       return Split;
9414   }
9415 
9416   if (CRHS && VT == MVT::i32) {
9417     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9418     // nb = number of trailing zeroes in mask
9419     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9420     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9421     uint64_t Mask = CRHS->getZExtValue();
9422     unsigned Bits = countPopulation(Mask);
9423     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9424         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9425       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9426         unsigned Shift = CShift->getZExtValue();
9427         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9428         unsigned Offset = NB + Shift;
9429         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9430           SDLoc SL(N);
9431           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9432                                     LHS->getOperand(0),
9433                                     DAG.getConstant(Offset, SL, MVT::i32),
9434                                     DAG.getConstant(Bits, SL, MVT::i32));
9435           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9436           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9437                                     DAG.getValueType(NarrowVT));
9438           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9439                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9440           return Shl;
9441         }
9442       }
9443     }
9444 
9445     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9446     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9447         isa<ConstantSDNode>(LHS.getOperand(2))) {
9448       uint32_t Sel = getConstantPermuteMask(Mask);
9449       if (!Sel)
9450         return SDValue();
9451 
9452       // Select 0xc for all zero bytes
9453       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9454       SDLoc DL(N);
9455       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9456                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9457     }
9458   }
9459 
9460   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9461   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9462   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9463     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9464     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9465 
9466     SDValue X = LHS.getOperand(0);
9467     SDValue Y = RHS.getOperand(0);
9468     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9469       return SDValue();
9470 
9471     if (LCC == ISD::SETO) {
9472       if (X != LHS.getOperand(1))
9473         return SDValue();
9474 
9475       if (RCC == ISD::SETUNE) {
9476         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9477         if (!C1 || !C1->isInfinity() || C1->isNegative())
9478           return SDValue();
9479 
9480         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9481                               SIInstrFlags::N_SUBNORMAL |
9482                               SIInstrFlags::N_ZERO |
9483                               SIInstrFlags::P_ZERO |
9484                               SIInstrFlags::P_SUBNORMAL |
9485                               SIInstrFlags::P_NORMAL;
9486 
9487         static_assert(((~(SIInstrFlags::S_NAN |
9488                           SIInstrFlags::Q_NAN |
9489                           SIInstrFlags::N_INFINITY |
9490                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9491                       "mask not equal");
9492 
9493         SDLoc DL(N);
9494         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9495                            X, DAG.getConstant(Mask, DL, MVT::i32));
9496       }
9497     }
9498   }
9499 
9500   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9501     std::swap(LHS, RHS);
9502 
9503   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9504       RHS.hasOneUse()) {
9505     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9506     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9507     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9508     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9509     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9510         (RHS.getOperand(0) == LHS.getOperand(0) &&
9511          LHS.getOperand(0) == LHS.getOperand(1))) {
9512       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9513       unsigned NewMask = LCC == ISD::SETO ?
9514         Mask->getZExtValue() & ~OrdMask :
9515         Mask->getZExtValue() & OrdMask;
9516 
9517       SDLoc DL(N);
9518       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9519                          DAG.getConstant(NewMask, DL, MVT::i32));
9520     }
9521   }
9522 
9523   if (VT == MVT::i32 &&
9524       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9525     // and x, (sext cc from i1) => select cc, x, 0
9526     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9527       std::swap(LHS, RHS);
9528     if (isBoolSGPR(RHS.getOperand(0)))
9529       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9530                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9531   }
9532 
9533   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9534   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9535   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9536       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9537     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9538     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9539     if (LHSMask != ~0u && RHSMask != ~0u) {
9540       // Canonicalize the expression in an attempt to have fewer unique masks
9541       // and therefore fewer registers used to hold the masks.
9542       if (LHSMask > RHSMask) {
9543         std::swap(LHSMask, RHSMask);
9544         std::swap(LHS, RHS);
9545       }
9546 
9547       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9548       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9549       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9550       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9551 
9552       // Check of we need to combine values from two sources within a byte.
9553       if (!(LHSUsedLanes & RHSUsedLanes) &&
9554           // If we select high and lower word keep it for SDWA.
9555           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9556           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9557         // Each byte in each mask is either selector mask 0-3, or has higher
9558         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9559         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9560         // mask which is not 0xff wins. By anding both masks we have a correct
9561         // result except that 0x0c shall be corrected to give 0x0c only.
9562         uint32_t Mask = LHSMask & RHSMask;
9563         for (unsigned I = 0; I < 32; I += 8) {
9564           uint32_t ByteSel = 0xff << I;
9565           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9566             Mask &= (0x0c << I) & 0xffffffff;
9567         }
9568 
9569         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9570         // or 0x0c.
9571         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9572         SDLoc DL(N);
9573 
9574         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9575                            LHS.getOperand(0), RHS.getOperand(0),
9576                            DAG.getConstant(Sel, DL, MVT::i32));
9577       }
9578     }
9579   }
9580 
9581   return SDValue();
9582 }
9583 
9584 SDValue SITargetLowering::performOrCombine(SDNode *N,
9585                                            DAGCombinerInfo &DCI) const {
9586   SelectionDAG &DAG = DCI.DAG;
9587   SDValue LHS = N->getOperand(0);
9588   SDValue RHS = N->getOperand(1);
9589 
9590   EVT VT = N->getValueType(0);
9591   if (VT == MVT::i1) {
9592     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9593     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9594         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9595       SDValue Src = LHS.getOperand(0);
9596       if (Src != RHS.getOperand(0))
9597         return SDValue();
9598 
9599       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9600       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9601       if (!CLHS || !CRHS)
9602         return SDValue();
9603 
9604       // Only 10 bits are used.
9605       static const uint32_t MaxMask = 0x3ff;
9606 
9607       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9608       SDLoc DL(N);
9609       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9610                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9611     }
9612 
9613     return SDValue();
9614   }
9615 
9616   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9617   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9618       LHS.getOpcode() == AMDGPUISD::PERM &&
9619       isa<ConstantSDNode>(LHS.getOperand(2))) {
9620     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9621     if (!Sel)
9622       return SDValue();
9623 
9624     Sel |= LHS.getConstantOperandVal(2);
9625     SDLoc DL(N);
9626     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9627                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9628   }
9629 
9630   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9631   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9632   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9633       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9634     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9635     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9636     if (LHSMask != ~0u && RHSMask != ~0u) {
9637       // Canonicalize the expression in an attempt to have fewer unique masks
9638       // and therefore fewer registers used to hold the masks.
9639       if (LHSMask > RHSMask) {
9640         std::swap(LHSMask, RHSMask);
9641         std::swap(LHS, RHS);
9642       }
9643 
9644       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9645       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9646       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9647       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9648 
9649       // Check of we need to combine values from two sources within a byte.
9650       if (!(LHSUsedLanes & RHSUsedLanes) &&
9651           // If we select high and lower word keep it for SDWA.
9652           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9653           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9654         // Kill zero bytes selected by other mask. Zero value is 0xc.
9655         LHSMask &= ~RHSUsedLanes;
9656         RHSMask &= ~LHSUsedLanes;
9657         // Add 4 to each active LHS lane
9658         LHSMask |= LHSUsedLanes & 0x04040404;
9659         // Combine masks
9660         uint32_t Sel = LHSMask | RHSMask;
9661         SDLoc DL(N);
9662 
9663         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9664                            LHS.getOperand(0), RHS.getOperand(0),
9665                            DAG.getConstant(Sel, DL, MVT::i32));
9666       }
9667     }
9668   }
9669 
9670   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9671     return SDValue();
9672 
9673   // TODO: This could be a generic combine with a predicate for extracting the
9674   // high half of an integer being free.
9675 
9676   // (or i64:x, (zero_extend i32:y)) ->
9677   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9678   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9679       RHS.getOpcode() != ISD::ZERO_EXTEND)
9680     std::swap(LHS, RHS);
9681 
9682   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9683     SDValue ExtSrc = RHS.getOperand(0);
9684     EVT SrcVT = ExtSrc.getValueType();
9685     if (SrcVT == MVT::i32) {
9686       SDLoc SL(N);
9687       SDValue LowLHS, HiBits;
9688       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9689       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9690 
9691       DCI.AddToWorklist(LowOr.getNode());
9692       DCI.AddToWorklist(HiBits.getNode());
9693 
9694       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9695                                 LowOr, HiBits);
9696       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9697     }
9698   }
9699 
9700   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9701   if (CRHS) {
9702     if (SDValue Split
9703           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9704                                      N->getOperand(0), CRHS))
9705       return Split;
9706   }
9707 
9708   return SDValue();
9709 }
9710 
9711 SDValue SITargetLowering::performXorCombine(SDNode *N,
9712                                             DAGCombinerInfo &DCI) const {
9713   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9714     return RV;
9715 
9716   EVT VT = N->getValueType(0);
9717   if (VT != MVT::i64)
9718     return SDValue();
9719 
9720   SDValue LHS = N->getOperand(0);
9721   SDValue RHS = N->getOperand(1);
9722 
9723   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9724   if (CRHS) {
9725     if (SDValue Split
9726           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9727       return Split;
9728   }
9729 
9730   return SDValue();
9731 }
9732 
9733 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9734                                                    DAGCombinerInfo &DCI) const {
9735   if (!Subtarget->has16BitInsts() ||
9736       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9737     return SDValue();
9738 
9739   EVT VT = N->getValueType(0);
9740   if (VT != MVT::i32)
9741     return SDValue();
9742 
9743   SDValue Src = N->getOperand(0);
9744   if (Src.getValueType() != MVT::i16)
9745     return SDValue();
9746 
9747   return SDValue();
9748 }
9749 
9750 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9751                                                         DAGCombinerInfo &DCI)
9752                                                         const {
9753   SDValue Src = N->getOperand(0);
9754   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9755 
9756   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9757       VTSign->getVT() == MVT::i8) ||
9758       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9759       VTSign->getVT() == MVT::i16)) &&
9760       Src.hasOneUse()) {
9761     auto *M = cast<MemSDNode>(Src);
9762     SDValue Ops[] = {
9763       Src.getOperand(0), // Chain
9764       Src.getOperand(1), // rsrc
9765       Src.getOperand(2), // vindex
9766       Src.getOperand(3), // voffset
9767       Src.getOperand(4), // soffset
9768       Src.getOperand(5), // offset
9769       Src.getOperand(6),
9770       Src.getOperand(7)
9771     };
9772     // replace with BUFFER_LOAD_BYTE/SHORT
9773     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9774                                          Src.getOperand(0).getValueType());
9775     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9776                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9777     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9778                                                           ResList,
9779                                                           Ops, M->getMemoryVT(),
9780                                                           M->getMemOperand());
9781     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9782                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9783   }
9784   return SDValue();
9785 }
9786 
9787 SDValue SITargetLowering::performClassCombine(SDNode *N,
9788                                               DAGCombinerInfo &DCI) const {
9789   SelectionDAG &DAG = DCI.DAG;
9790   SDValue Mask = N->getOperand(1);
9791 
9792   // fp_class x, 0 -> false
9793   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9794     if (CMask->isZero())
9795       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9796   }
9797 
9798   if (N->getOperand(0).isUndef())
9799     return DAG.getUNDEF(MVT::i1);
9800 
9801   return SDValue();
9802 }
9803 
9804 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9805                                             DAGCombinerInfo &DCI) const {
9806   EVT VT = N->getValueType(0);
9807   SDValue N0 = N->getOperand(0);
9808 
9809   if (N0.isUndef())
9810     return N0;
9811 
9812   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9813                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9814     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9815                            N->getFlags());
9816   }
9817 
9818   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9819     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9820                            N0.getOperand(0), N->getFlags());
9821   }
9822 
9823   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9824 }
9825 
9826 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9827                                        unsigned MaxDepth) const {
9828   unsigned Opcode = Op.getOpcode();
9829   if (Opcode == ISD::FCANONICALIZE)
9830     return true;
9831 
9832   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9833     auto F = CFP->getValueAPF();
9834     if (F.isNaN() && F.isSignaling())
9835       return false;
9836     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9837   }
9838 
9839   // If source is a result of another standard FP operation it is already in
9840   // canonical form.
9841   if (MaxDepth == 0)
9842     return false;
9843 
9844   switch (Opcode) {
9845   // These will flush denorms if required.
9846   case ISD::FADD:
9847   case ISD::FSUB:
9848   case ISD::FMUL:
9849   case ISD::FCEIL:
9850   case ISD::FFLOOR:
9851   case ISD::FMA:
9852   case ISD::FMAD:
9853   case ISD::FSQRT:
9854   case ISD::FDIV:
9855   case ISD::FREM:
9856   case ISD::FP_ROUND:
9857   case ISD::FP_EXTEND:
9858   case AMDGPUISD::FMUL_LEGACY:
9859   case AMDGPUISD::FMAD_FTZ:
9860   case AMDGPUISD::RCP:
9861   case AMDGPUISD::RSQ:
9862   case AMDGPUISD::RSQ_CLAMP:
9863   case AMDGPUISD::RCP_LEGACY:
9864   case AMDGPUISD::RCP_IFLAG:
9865   case AMDGPUISD::DIV_SCALE:
9866   case AMDGPUISD::DIV_FMAS:
9867   case AMDGPUISD::DIV_FIXUP:
9868   case AMDGPUISD::FRACT:
9869   case AMDGPUISD::LDEXP:
9870   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9871   case AMDGPUISD::CVT_F32_UBYTE0:
9872   case AMDGPUISD::CVT_F32_UBYTE1:
9873   case AMDGPUISD::CVT_F32_UBYTE2:
9874   case AMDGPUISD::CVT_F32_UBYTE3:
9875     return true;
9876 
9877   // It can/will be lowered or combined as a bit operation.
9878   // Need to check their input recursively to handle.
9879   case ISD::FNEG:
9880   case ISD::FABS:
9881   case ISD::FCOPYSIGN:
9882     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9883 
9884   case ISD::FSIN:
9885   case ISD::FCOS:
9886   case ISD::FSINCOS:
9887     return Op.getValueType().getScalarType() != MVT::f16;
9888 
9889   case ISD::FMINNUM:
9890   case ISD::FMAXNUM:
9891   case ISD::FMINNUM_IEEE:
9892   case ISD::FMAXNUM_IEEE:
9893   case AMDGPUISD::CLAMP:
9894   case AMDGPUISD::FMED3:
9895   case AMDGPUISD::FMAX3:
9896   case AMDGPUISD::FMIN3: {
9897     // FIXME: Shouldn't treat the generic operations different based these.
9898     // However, we aren't really required to flush the result from
9899     // minnum/maxnum..
9900 
9901     // snans will be quieted, so we only need to worry about denormals.
9902     if (Subtarget->supportsMinMaxDenormModes() ||
9903         denormalsEnabledForType(DAG, Op.getValueType()))
9904       return true;
9905 
9906     // Flushing may be required.
9907     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9908     // targets need to check their input recursively.
9909 
9910     // FIXME: Does this apply with clamp? It's implemented with max.
9911     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9912       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9913         return false;
9914     }
9915 
9916     return true;
9917   }
9918   case ISD::SELECT: {
9919     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9920            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9921   }
9922   case ISD::BUILD_VECTOR: {
9923     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9924       SDValue SrcOp = Op.getOperand(i);
9925       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9926         return false;
9927     }
9928 
9929     return true;
9930   }
9931   case ISD::EXTRACT_VECTOR_ELT:
9932   case ISD::EXTRACT_SUBVECTOR: {
9933     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9934   }
9935   case ISD::INSERT_VECTOR_ELT: {
9936     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9937            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9938   }
9939   case ISD::UNDEF:
9940     // Could be anything.
9941     return false;
9942 
9943   case ISD::BITCAST:
9944     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9945   case ISD::TRUNCATE: {
9946     // Hack round the mess we make when legalizing extract_vector_elt
9947     if (Op.getValueType() == MVT::i16) {
9948       SDValue TruncSrc = Op.getOperand(0);
9949       if (TruncSrc.getValueType() == MVT::i32 &&
9950           TruncSrc.getOpcode() == ISD::BITCAST &&
9951           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9952         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9953       }
9954     }
9955     return false;
9956   }
9957   case ISD::INTRINSIC_WO_CHAIN: {
9958     unsigned IntrinsicID
9959       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9960     // TODO: Handle more intrinsics
9961     switch (IntrinsicID) {
9962     case Intrinsic::amdgcn_cvt_pkrtz:
9963     case Intrinsic::amdgcn_cubeid:
9964     case Intrinsic::amdgcn_frexp_mant:
9965     case Intrinsic::amdgcn_fdot2:
9966     case Intrinsic::amdgcn_rcp:
9967     case Intrinsic::amdgcn_rsq:
9968     case Intrinsic::amdgcn_rsq_clamp:
9969     case Intrinsic::amdgcn_rcp_legacy:
9970     case Intrinsic::amdgcn_rsq_legacy:
9971     case Intrinsic::amdgcn_trig_preop:
9972       return true;
9973     default:
9974       break;
9975     }
9976 
9977     LLVM_FALLTHROUGH;
9978   }
9979   default:
9980     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9981            DAG.isKnownNeverSNaN(Op);
9982   }
9983 
9984   llvm_unreachable("invalid operation");
9985 }
9986 
9987 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9988                                        unsigned MaxDepth) const {
9989   MachineRegisterInfo &MRI = MF.getRegInfo();
9990   MachineInstr *MI = MRI.getVRegDef(Reg);
9991   unsigned Opcode = MI->getOpcode();
9992 
9993   if (Opcode == AMDGPU::G_FCANONICALIZE)
9994     return true;
9995 
9996   Optional<FPValueAndVReg> FCR;
9997   // Constant splat (can be padded with undef) or scalar constant.
9998   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9999     if (FCR->Value.isSignaling())
10000       return false;
10001     return !FCR->Value.isDenormal() ||
10002            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10003   }
10004 
10005   if (MaxDepth == 0)
10006     return false;
10007 
10008   switch (Opcode) {
10009   case AMDGPU::G_FMINNUM_IEEE:
10010   case AMDGPU::G_FMAXNUM_IEEE: {
10011     if (Subtarget->supportsMinMaxDenormModes() ||
10012         denormalsEnabledForType(MRI.getType(Reg), MF))
10013       return true;
10014     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10015       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10016         return false;
10017     return true;
10018   }
10019   default:
10020     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10021            isKnownNeverSNaN(Reg, MRI);
10022   }
10023 
10024   llvm_unreachable("invalid operation");
10025 }
10026 
10027 // Constant fold canonicalize.
10028 SDValue SITargetLowering::getCanonicalConstantFP(
10029   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10030   // Flush denormals to 0 if not enabled.
10031   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10032     return DAG.getConstantFP(0.0, SL, VT);
10033 
10034   if (C.isNaN()) {
10035     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10036     if (C.isSignaling()) {
10037       // Quiet a signaling NaN.
10038       // FIXME: Is this supposed to preserve payload bits?
10039       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10040     }
10041 
10042     // Make sure it is the canonical NaN bitpattern.
10043     //
10044     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10045     // immediate?
10046     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10047       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10048   }
10049 
10050   // Already canonical.
10051   return DAG.getConstantFP(C, SL, VT);
10052 }
10053 
10054 static bool vectorEltWillFoldAway(SDValue Op) {
10055   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10056 }
10057 
10058 SDValue SITargetLowering::performFCanonicalizeCombine(
10059   SDNode *N,
10060   DAGCombinerInfo &DCI) const {
10061   SelectionDAG &DAG = DCI.DAG;
10062   SDValue N0 = N->getOperand(0);
10063   EVT VT = N->getValueType(0);
10064 
10065   // fcanonicalize undef -> qnan
10066   if (N0.isUndef()) {
10067     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10068     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10069   }
10070 
10071   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10072     EVT VT = N->getValueType(0);
10073     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10074   }
10075 
10076   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10077   //                                                   (fcanonicalize k)
10078   //
10079   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10080 
10081   // TODO: This could be better with wider vectors that will be split to v2f16,
10082   // and to consider uses since there aren't that many packed operations.
10083   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10084       isTypeLegal(MVT::v2f16)) {
10085     SDLoc SL(N);
10086     SDValue NewElts[2];
10087     SDValue Lo = N0.getOperand(0);
10088     SDValue Hi = N0.getOperand(1);
10089     EVT EltVT = Lo.getValueType();
10090 
10091     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10092       for (unsigned I = 0; I != 2; ++I) {
10093         SDValue Op = N0.getOperand(I);
10094         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10095           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10096                                               CFP->getValueAPF());
10097         } else if (Op.isUndef()) {
10098           // Handled below based on what the other operand is.
10099           NewElts[I] = Op;
10100         } else {
10101           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10102         }
10103       }
10104 
10105       // If one half is undef, and one is constant, prefer a splat vector rather
10106       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10107       // cheaper to use and may be free with a packed operation.
10108       if (NewElts[0].isUndef()) {
10109         if (isa<ConstantFPSDNode>(NewElts[1]))
10110           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10111             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10112       }
10113 
10114       if (NewElts[1].isUndef()) {
10115         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10116           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10117       }
10118 
10119       return DAG.getBuildVector(VT, SL, NewElts);
10120     }
10121   }
10122 
10123   unsigned SrcOpc = N0.getOpcode();
10124 
10125   // If it's free to do so, push canonicalizes further up the source, which may
10126   // find a canonical source.
10127   //
10128   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10129   // sNaNs.
10130   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10131     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10132     if (CRHS && N0.hasOneUse()) {
10133       SDLoc SL(N);
10134       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10135                                    N0.getOperand(0));
10136       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10137       DCI.AddToWorklist(Canon0.getNode());
10138 
10139       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10140     }
10141   }
10142 
10143   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10144 }
10145 
10146 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10147   switch (Opc) {
10148   case ISD::FMAXNUM:
10149   case ISD::FMAXNUM_IEEE:
10150     return AMDGPUISD::FMAX3;
10151   case ISD::SMAX:
10152     return AMDGPUISD::SMAX3;
10153   case ISD::UMAX:
10154     return AMDGPUISD::UMAX3;
10155   case ISD::FMINNUM:
10156   case ISD::FMINNUM_IEEE:
10157     return AMDGPUISD::FMIN3;
10158   case ISD::SMIN:
10159     return AMDGPUISD::SMIN3;
10160   case ISD::UMIN:
10161     return AMDGPUISD::UMIN3;
10162   default:
10163     llvm_unreachable("Not a min/max opcode");
10164   }
10165 }
10166 
10167 SDValue SITargetLowering::performIntMed3ImmCombine(
10168   SelectionDAG &DAG, const SDLoc &SL,
10169   SDValue Op0, SDValue Op1, bool Signed) const {
10170   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10171   if (!K1)
10172     return SDValue();
10173 
10174   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10175   if (!K0)
10176     return SDValue();
10177 
10178   if (Signed) {
10179     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10180       return SDValue();
10181   } else {
10182     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10183       return SDValue();
10184   }
10185 
10186   EVT VT = K0->getValueType(0);
10187   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10188   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10189     return DAG.getNode(Med3Opc, SL, VT,
10190                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10191   }
10192 
10193   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10194   if (VT == MVT::i16) {
10195     MVT NVT = MVT::i32;
10196     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10197 
10198     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10199     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10200     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10201 
10202     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10203     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10204   }
10205 
10206   return SDValue();
10207 }
10208 
10209 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10210   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10211     return C;
10212 
10213   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10214     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10215       return C;
10216   }
10217 
10218   return nullptr;
10219 }
10220 
10221 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10222                                                   const SDLoc &SL,
10223                                                   SDValue Op0,
10224                                                   SDValue Op1) const {
10225   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10226   if (!K1)
10227     return SDValue();
10228 
10229   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10230   if (!K0)
10231     return SDValue();
10232 
10233   // Ordered >= (although NaN inputs should have folded away by now).
10234   if (K0->getValueAPF() > K1->getValueAPF())
10235     return SDValue();
10236 
10237   const MachineFunction &MF = DAG.getMachineFunction();
10238   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10239 
10240   // TODO: Check IEEE bit enabled?
10241   EVT VT = Op0.getValueType();
10242   if (Info->getMode().DX10Clamp) {
10243     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10244     // hardware fmed3 behavior converting to a min.
10245     // FIXME: Should this be allowing -0.0?
10246     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10247       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10248   }
10249 
10250   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10251   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10252     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10253     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10254     // then give the other result, which is different from med3 with a NaN
10255     // input.
10256     SDValue Var = Op0.getOperand(0);
10257     if (!DAG.isKnownNeverSNaN(Var))
10258       return SDValue();
10259 
10260     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10261 
10262     if ((!K0->hasOneUse() ||
10263          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10264         (!K1->hasOneUse() ||
10265          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10266       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10267                          Var, SDValue(K0, 0), SDValue(K1, 0));
10268     }
10269   }
10270 
10271   return SDValue();
10272 }
10273 
10274 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10275                                                DAGCombinerInfo &DCI) const {
10276   SelectionDAG &DAG = DCI.DAG;
10277 
10278   EVT VT = N->getValueType(0);
10279   unsigned Opc = N->getOpcode();
10280   SDValue Op0 = N->getOperand(0);
10281   SDValue Op1 = N->getOperand(1);
10282 
10283   // Only do this if the inner op has one use since this will just increases
10284   // register pressure for no benefit.
10285 
10286   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10287       !VT.isVector() &&
10288       (VT == MVT::i32 || VT == MVT::f32 ||
10289        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10290     // max(max(a, b), c) -> max3(a, b, c)
10291     // min(min(a, b), c) -> min3(a, b, c)
10292     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10293       SDLoc DL(N);
10294       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10295                          DL,
10296                          N->getValueType(0),
10297                          Op0.getOperand(0),
10298                          Op0.getOperand(1),
10299                          Op1);
10300     }
10301 
10302     // Try commuted.
10303     // max(a, max(b, c)) -> max3(a, b, c)
10304     // min(a, min(b, c)) -> min3(a, b, c)
10305     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10306       SDLoc DL(N);
10307       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10308                          DL,
10309                          N->getValueType(0),
10310                          Op0,
10311                          Op1.getOperand(0),
10312                          Op1.getOperand(1));
10313     }
10314   }
10315 
10316   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10317   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10318     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10319       return Med3;
10320   }
10321 
10322   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10323     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10324       return Med3;
10325   }
10326 
10327   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10328   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10329        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10330        (Opc == AMDGPUISD::FMIN_LEGACY &&
10331         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10332       (VT == MVT::f32 || VT == MVT::f64 ||
10333        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10334        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10335       Op0.hasOneUse()) {
10336     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10337       return Res;
10338   }
10339 
10340   return SDValue();
10341 }
10342 
10343 static bool isClampZeroToOne(SDValue A, SDValue B) {
10344   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10345     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10346       // FIXME: Should this be allowing -0.0?
10347       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10348              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10349     }
10350   }
10351 
10352   return false;
10353 }
10354 
10355 // FIXME: Should only worry about snans for version with chain.
10356 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10357                                               DAGCombinerInfo &DCI) const {
10358   EVT VT = N->getValueType(0);
10359   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10360   // NaNs. With a NaN input, the order of the operands may change the result.
10361 
10362   SelectionDAG &DAG = DCI.DAG;
10363   SDLoc SL(N);
10364 
10365   SDValue Src0 = N->getOperand(0);
10366   SDValue Src1 = N->getOperand(1);
10367   SDValue Src2 = N->getOperand(2);
10368 
10369   if (isClampZeroToOne(Src0, Src1)) {
10370     // const_a, const_b, x -> clamp is safe in all cases including signaling
10371     // nans.
10372     // FIXME: Should this be allowing -0.0?
10373     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10374   }
10375 
10376   const MachineFunction &MF = DAG.getMachineFunction();
10377   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10378 
10379   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10380   // handling no dx10-clamp?
10381   if (Info->getMode().DX10Clamp) {
10382     // If NaNs is clamped to 0, we are free to reorder the inputs.
10383 
10384     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10385       std::swap(Src0, Src1);
10386 
10387     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10388       std::swap(Src1, Src2);
10389 
10390     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10391       std::swap(Src0, Src1);
10392 
10393     if (isClampZeroToOne(Src1, Src2))
10394       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10395   }
10396 
10397   return SDValue();
10398 }
10399 
10400 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10401                                                  DAGCombinerInfo &DCI) const {
10402   SDValue Src0 = N->getOperand(0);
10403   SDValue Src1 = N->getOperand(1);
10404   if (Src0.isUndef() && Src1.isUndef())
10405     return DCI.DAG.getUNDEF(N->getValueType(0));
10406   return SDValue();
10407 }
10408 
10409 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10410 // expanded into a set of cmp/select instructions.
10411 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10412                                                 unsigned NumElem,
10413                                                 bool IsDivergentIdx,
10414                                                 const GCNSubtarget *Subtarget) {
10415   if (UseDivergentRegisterIndexing)
10416     return false;
10417 
10418   unsigned VecSize = EltSize * NumElem;
10419 
10420   // Sub-dword vectors of size 2 dword or less have better implementation.
10421   if (VecSize <= 64 && EltSize < 32)
10422     return false;
10423 
10424   // Always expand the rest of sub-dword instructions, otherwise it will be
10425   // lowered via memory.
10426   if (EltSize < 32)
10427     return true;
10428 
10429   // Always do this if var-idx is divergent, otherwise it will become a loop.
10430   if (IsDivergentIdx)
10431     return true;
10432 
10433   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10434   unsigned NumInsts = NumElem /* Number of compares */ +
10435                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10436 
10437   // On some architectures (GFX9) movrel is not available and it's better
10438   // to expand.
10439   if (!Subtarget->hasMovrel())
10440     return NumInsts <= 16;
10441 
10442   // If movrel is available, use it instead of expanding for vector of 8
10443   // elements.
10444   return NumInsts <= 15;
10445 }
10446 
10447 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
10448   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10449   if (isa<ConstantSDNode>(Idx))
10450     return false;
10451 
10452   SDValue Vec = N->getOperand(0);
10453   EVT VecVT = Vec.getValueType();
10454   EVT EltVT = VecVT.getVectorElementType();
10455   unsigned EltSize = EltVT.getSizeInBits();
10456   unsigned NumElem = VecVT.getVectorNumElements();
10457 
10458   return SITargetLowering::shouldExpandVectorDynExt(
10459       EltSize, NumElem, Idx->isDivergent(), getSubtarget());
10460 }
10461 
10462 SDValue SITargetLowering::performExtractVectorEltCombine(
10463   SDNode *N, DAGCombinerInfo &DCI) const {
10464   SDValue Vec = N->getOperand(0);
10465   SelectionDAG &DAG = DCI.DAG;
10466 
10467   EVT VecVT = Vec.getValueType();
10468   EVT EltVT = VecVT.getVectorElementType();
10469 
10470   if ((Vec.getOpcode() == ISD::FNEG ||
10471        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10472     SDLoc SL(N);
10473     EVT EltVT = N->getValueType(0);
10474     SDValue Idx = N->getOperand(1);
10475     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10476                               Vec.getOperand(0), Idx);
10477     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10478   }
10479 
10480   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10481   //    =>
10482   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10483   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10484   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10485   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10486     SDLoc SL(N);
10487     EVT EltVT = N->getValueType(0);
10488     SDValue Idx = N->getOperand(1);
10489     unsigned Opc = Vec.getOpcode();
10490 
10491     switch(Opc) {
10492     default:
10493       break;
10494       // TODO: Support other binary operations.
10495     case ISD::FADD:
10496     case ISD::FSUB:
10497     case ISD::FMUL:
10498     case ISD::ADD:
10499     case ISD::UMIN:
10500     case ISD::UMAX:
10501     case ISD::SMIN:
10502     case ISD::SMAX:
10503     case ISD::FMAXNUM:
10504     case ISD::FMINNUM:
10505     case ISD::FMAXNUM_IEEE:
10506     case ISD::FMINNUM_IEEE: {
10507       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10508                                  Vec.getOperand(0), Idx);
10509       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10510                                  Vec.getOperand(1), Idx);
10511 
10512       DCI.AddToWorklist(Elt0.getNode());
10513       DCI.AddToWorklist(Elt1.getNode());
10514       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10515     }
10516     }
10517   }
10518 
10519   unsigned VecSize = VecVT.getSizeInBits();
10520   unsigned EltSize = EltVT.getSizeInBits();
10521 
10522   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10523   if (shouldExpandVectorDynExt(N)) {
10524     SDLoc SL(N);
10525     SDValue Idx = N->getOperand(1);
10526     SDValue V;
10527     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10528       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10529       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10530       if (I == 0)
10531         V = Elt;
10532       else
10533         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10534     }
10535     return V;
10536   }
10537 
10538   if (!DCI.isBeforeLegalize())
10539     return SDValue();
10540 
10541   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10542   // elements. This exposes more load reduction opportunities by replacing
10543   // multiple small extract_vector_elements with a single 32-bit extract.
10544   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10545   if (isa<MemSDNode>(Vec) &&
10546       EltSize <= 16 &&
10547       EltVT.isByteSized() &&
10548       VecSize > 32 &&
10549       VecSize % 32 == 0 &&
10550       Idx) {
10551     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10552 
10553     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10554     unsigned EltIdx = BitIndex / 32;
10555     unsigned LeftoverBitIdx = BitIndex % 32;
10556     SDLoc SL(N);
10557 
10558     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10559     DCI.AddToWorklist(Cast.getNode());
10560 
10561     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10562                               DAG.getConstant(EltIdx, SL, MVT::i32));
10563     DCI.AddToWorklist(Elt.getNode());
10564     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10565                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10566     DCI.AddToWorklist(Srl.getNode());
10567 
10568     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10569     DCI.AddToWorklist(Trunc.getNode());
10570     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10571   }
10572 
10573   return SDValue();
10574 }
10575 
10576 SDValue
10577 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10578                                                 DAGCombinerInfo &DCI) const {
10579   SDValue Vec = N->getOperand(0);
10580   SDValue Idx = N->getOperand(2);
10581   EVT VecVT = Vec.getValueType();
10582   EVT EltVT = VecVT.getVectorElementType();
10583 
10584   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10585   // => BUILD_VECTOR n x select (e, const-idx)
10586   if (!shouldExpandVectorDynExt(N))
10587     return SDValue();
10588 
10589   SelectionDAG &DAG = DCI.DAG;
10590   SDLoc SL(N);
10591   SDValue Ins = N->getOperand(1);
10592   EVT IdxVT = Idx.getValueType();
10593 
10594   SmallVector<SDValue, 16> Ops;
10595   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10596     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10597     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10598     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10599     Ops.push_back(V);
10600   }
10601 
10602   return DAG.getBuildVector(VecVT, SL, Ops);
10603 }
10604 
10605 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10606                                           const SDNode *N0,
10607                                           const SDNode *N1) const {
10608   EVT VT = N0->getValueType(0);
10609 
10610   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10611   // support denormals ever.
10612   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10613        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10614         getSubtarget()->hasMadF16())) &&
10615        isOperationLegal(ISD::FMAD, VT))
10616     return ISD::FMAD;
10617 
10618   const TargetOptions &Options = DAG.getTarget().Options;
10619   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10620        (N0->getFlags().hasAllowContract() &&
10621         N1->getFlags().hasAllowContract())) &&
10622       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10623     return ISD::FMA;
10624   }
10625 
10626   return 0;
10627 }
10628 
10629 // For a reassociatable opcode perform:
10630 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10631 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10632                                                SelectionDAG &DAG) const {
10633   EVT VT = N->getValueType(0);
10634   if (VT != MVT::i32 && VT != MVT::i64)
10635     return SDValue();
10636 
10637   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10638     return SDValue();
10639 
10640   unsigned Opc = N->getOpcode();
10641   SDValue Op0 = N->getOperand(0);
10642   SDValue Op1 = N->getOperand(1);
10643 
10644   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10645     return SDValue();
10646 
10647   if (Op0->isDivergent())
10648     std::swap(Op0, Op1);
10649 
10650   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10651     return SDValue();
10652 
10653   SDValue Op2 = Op1.getOperand(1);
10654   Op1 = Op1.getOperand(0);
10655   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10656     return SDValue();
10657 
10658   if (Op1->isDivergent())
10659     std::swap(Op1, Op2);
10660 
10661   SDLoc SL(N);
10662   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10663   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10664 }
10665 
10666 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10667                            EVT VT,
10668                            SDValue N0, SDValue N1, SDValue N2,
10669                            bool Signed) {
10670   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10671   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10672   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10673   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10674 }
10675 
10676 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
10677 // multiplies, if any.
10678 //
10679 // Full 64-bit multiplies that feed into an addition are lowered here instead
10680 // of using the generic expansion. The generic expansion ends up with
10681 // a tree of ADD nodes that prevents us from using the "add" part of the
10682 // MAD instruction. The expansion produced here results in a chain of ADDs
10683 // instead of a tree.
10684 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10685                                             DAGCombinerInfo &DCI) const {
10686   assert(N->getOpcode() == ISD::ADD);
10687 
10688   SelectionDAG &DAG = DCI.DAG;
10689   EVT VT = N->getValueType(0);
10690   SDLoc SL(N);
10691   SDValue LHS = N->getOperand(0);
10692   SDValue RHS = N->getOperand(1);
10693 
10694   if (VT.isVector())
10695     return SDValue();
10696 
10697   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
10698   // result in scalar registers for uniform values.
10699   if (!N->isDivergent() && Subtarget->hasSMulHi())
10700     return SDValue();
10701 
10702   unsigned NumBits = VT.getScalarSizeInBits();
10703   if (NumBits <= 32 || NumBits > 64)
10704     return SDValue();
10705 
10706   if (LHS.getOpcode() != ISD::MUL) {
10707     assert(RHS.getOpcode() == ISD::MUL);
10708     std::swap(LHS, RHS);
10709   }
10710 
10711   // Avoid the fold if it would unduly increase the number of multiplies due to
10712   // multiple uses, except on hardware with full-rate multiply-add (which is
10713   // part of full-rate 64-bit ops).
10714   if (!Subtarget->hasFullRate64Ops()) {
10715     unsigned NumUsers = 0;
10716     for (SDNode *Use : LHS->uses()) {
10717       // There is a use that does not feed into addition, so the multiply can't
10718       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
10719       if (Use->getOpcode() != ISD::ADD)
10720         return SDValue();
10721 
10722       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
10723       // MUL + 3xADD + 3xADDC over 3xMAD.
10724       ++NumUsers;
10725       if (NumUsers >= 3)
10726         return SDValue();
10727     }
10728   }
10729 
10730   SDValue MulLHS = LHS.getOperand(0);
10731   SDValue MulRHS = LHS.getOperand(1);
10732   SDValue AddRHS = RHS;
10733 
10734   // Always check whether operands are small unsigned values, since that
10735   // knowledge is useful in more cases. Check for small signed values only if
10736   // doing so can unlock a shorter code sequence.
10737   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
10738   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
10739 
10740   bool MulSignedLo = false;
10741   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
10742     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
10743                   numBitsSigned(MulRHS, DAG) <= 32;
10744   }
10745 
10746   // The operands and final result all have the same number of bits. If
10747   // operands need to be extended, they can be extended with garbage. The
10748   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
10749   // truncated away in the end.
10750   if (VT != MVT::i64) {
10751     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
10752     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
10753     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
10754   }
10755 
10756   // The basic code generated is conceptually straightforward. Pseudo code:
10757   //
10758   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
10759   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
10760   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
10761   //
10762   // The second and third lines are optional, depending on whether the factors
10763   // are {sign,zero}-extended or not.
10764   //
10765   // The actual DAG is noisier than the pseudo code, but only due to
10766   // instructions that disassemble values into low and high parts, and
10767   // assemble the final result.
10768   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
10769   SDValue One = DAG.getConstant(1, SL, MVT::i32);
10770 
10771   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
10772   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
10773   SDValue Accum =
10774       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
10775 
10776   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
10777     auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero);
10778     auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One);
10779 
10780     if (!MulLHSUnsigned32) {
10781       auto MulLHSHi =
10782           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
10783       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
10784       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10785     }
10786 
10787     if (!MulRHSUnsigned32) {
10788       auto MulRHSHi =
10789           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
10790       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
10791       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10792     }
10793 
10794     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
10795     Accum = DAG.getBitcast(MVT::i64, Accum);
10796   }
10797 
10798   if (VT != MVT::i64)
10799     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
10800   return Accum;
10801 }
10802 
10803 SDValue SITargetLowering::performAddCombine(SDNode *N,
10804                                             DAGCombinerInfo &DCI) const {
10805   SelectionDAG &DAG = DCI.DAG;
10806   EVT VT = N->getValueType(0);
10807   SDLoc SL(N);
10808   SDValue LHS = N->getOperand(0);
10809   SDValue RHS = N->getOperand(1);
10810 
10811   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10812     if (Subtarget->hasMad64_32()) {
10813       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10814         return Folded;
10815     }
10816 
10817     return SDValue();
10818   }
10819 
10820   if (SDValue V = reassociateScalarOps(N, DAG)) {
10821     return V;
10822   }
10823 
10824   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10825     return SDValue();
10826 
10827   // add x, zext (setcc) => addcarry x, 0, setcc
10828   // add x, sext (setcc) => subcarry x, 0, setcc
10829   unsigned Opc = LHS.getOpcode();
10830   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10831       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10832     std::swap(RHS, LHS);
10833 
10834   Opc = RHS.getOpcode();
10835   switch (Opc) {
10836   default: break;
10837   case ISD::ZERO_EXTEND:
10838   case ISD::SIGN_EXTEND:
10839   case ISD::ANY_EXTEND: {
10840     auto Cond = RHS.getOperand(0);
10841     // If this won't be a real VOPC output, we would still need to insert an
10842     // extra instruction anyway.
10843     if (!isBoolSGPR(Cond))
10844       break;
10845     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10846     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10847     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10848     return DAG.getNode(Opc, SL, VTList, Args);
10849   }
10850   case ISD::ADDCARRY: {
10851     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10852     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10853     if (!C || C->getZExtValue() != 0) break;
10854     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10855     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10856   }
10857   }
10858   return SDValue();
10859 }
10860 
10861 SDValue SITargetLowering::performSubCombine(SDNode *N,
10862                                             DAGCombinerInfo &DCI) const {
10863   SelectionDAG &DAG = DCI.DAG;
10864   EVT VT = N->getValueType(0);
10865 
10866   if (VT != MVT::i32)
10867     return SDValue();
10868 
10869   SDLoc SL(N);
10870   SDValue LHS = N->getOperand(0);
10871   SDValue RHS = N->getOperand(1);
10872 
10873   // sub x, zext (setcc) => subcarry x, 0, setcc
10874   // sub x, sext (setcc) => addcarry x, 0, setcc
10875   unsigned Opc = RHS.getOpcode();
10876   switch (Opc) {
10877   default: break;
10878   case ISD::ZERO_EXTEND:
10879   case ISD::SIGN_EXTEND:
10880   case ISD::ANY_EXTEND: {
10881     auto Cond = RHS.getOperand(0);
10882     // If this won't be a real VOPC output, we would still need to insert an
10883     // extra instruction anyway.
10884     if (!isBoolSGPR(Cond))
10885       break;
10886     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10887     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10888     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10889     return DAG.getNode(Opc, SL, VTList, Args);
10890   }
10891   }
10892 
10893   if (LHS.getOpcode() == ISD::SUBCARRY) {
10894     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10895     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10896     if (!C || !C->isZero())
10897       return SDValue();
10898     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10899     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10900   }
10901   return SDValue();
10902 }
10903 
10904 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10905   DAGCombinerInfo &DCI) const {
10906 
10907   if (N->getValueType(0) != MVT::i32)
10908     return SDValue();
10909 
10910   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10911   if (!C || C->getZExtValue() != 0)
10912     return SDValue();
10913 
10914   SelectionDAG &DAG = DCI.DAG;
10915   SDValue LHS = N->getOperand(0);
10916 
10917   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10918   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10919   unsigned LHSOpc = LHS.getOpcode();
10920   unsigned Opc = N->getOpcode();
10921   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10922       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10923     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10924     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10925   }
10926   return SDValue();
10927 }
10928 
10929 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10930                                              DAGCombinerInfo &DCI) const {
10931   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10932     return SDValue();
10933 
10934   SelectionDAG &DAG = DCI.DAG;
10935   EVT VT = N->getValueType(0);
10936 
10937   SDLoc SL(N);
10938   SDValue LHS = N->getOperand(0);
10939   SDValue RHS = N->getOperand(1);
10940 
10941   // These should really be instruction patterns, but writing patterns with
10942   // source modifiers is a pain.
10943 
10944   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10945   if (LHS.getOpcode() == ISD::FADD) {
10946     SDValue A = LHS.getOperand(0);
10947     if (A == LHS.getOperand(1)) {
10948       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10949       if (FusedOp != 0) {
10950         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10951         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10952       }
10953     }
10954   }
10955 
10956   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10957   if (RHS.getOpcode() == ISD::FADD) {
10958     SDValue A = RHS.getOperand(0);
10959     if (A == RHS.getOperand(1)) {
10960       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10961       if (FusedOp != 0) {
10962         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10963         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10964       }
10965     }
10966   }
10967 
10968   return SDValue();
10969 }
10970 
10971 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10972                                              DAGCombinerInfo &DCI) const {
10973   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10974     return SDValue();
10975 
10976   SelectionDAG &DAG = DCI.DAG;
10977   SDLoc SL(N);
10978   EVT VT = N->getValueType(0);
10979   assert(!VT.isVector());
10980 
10981   // Try to get the fneg to fold into the source modifier. This undoes generic
10982   // DAG combines and folds them into the mad.
10983   //
10984   // Only do this if we are not trying to support denormals. v_mad_f32 does
10985   // not support denormals ever.
10986   SDValue LHS = N->getOperand(0);
10987   SDValue RHS = N->getOperand(1);
10988   if (LHS.getOpcode() == ISD::FADD) {
10989     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10990     SDValue A = LHS.getOperand(0);
10991     if (A == LHS.getOperand(1)) {
10992       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10993       if (FusedOp != 0){
10994         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10995         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10996 
10997         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10998       }
10999     }
11000   }
11001 
11002   if (RHS.getOpcode() == ISD::FADD) {
11003     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11004 
11005     SDValue A = RHS.getOperand(0);
11006     if (A == RHS.getOperand(1)) {
11007       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11008       if (FusedOp != 0){
11009         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11010         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11011       }
11012     }
11013   }
11014 
11015   return SDValue();
11016 }
11017 
11018 SDValue SITargetLowering::performFMACombine(SDNode *N,
11019                                             DAGCombinerInfo &DCI) const {
11020   SelectionDAG &DAG = DCI.DAG;
11021   EVT VT = N->getValueType(0);
11022   SDLoc SL(N);
11023 
11024   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11025     return SDValue();
11026 
11027   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11028   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11029   SDValue Op1 = N->getOperand(0);
11030   SDValue Op2 = N->getOperand(1);
11031   SDValue FMA = N->getOperand(2);
11032 
11033   if (FMA.getOpcode() != ISD::FMA ||
11034       Op1.getOpcode() != ISD::FP_EXTEND ||
11035       Op2.getOpcode() != ISD::FP_EXTEND)
11036     return SDValue();
11037 
11038   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11039   // regardless of the denorm mode setting. Therefore,
11040   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11041   const TargetOptions &Options = DAG.getTarget().Options;
11042   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11043       (N->getFlags().hasAllowContract() &&
11044        FMA->getFlags().hasAllowContract())) {
11045     Op1 = Op1.getOperand(0);
11046     Op2 = Op2.getOperand(0);
11047     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11048         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11049       return SDValue();
11050 
11051     SDValue Vec1 = Op1.getOperand(0);
11052     SDValue Idx1 = Op1.getOperand(1);
11053     SDValue Vec2 = Op2.getOperand(0);
11054 
11055     SDValue FMAOp1 = FMA.getOperand(0);
11056     SDValue FMAOp2 = FMA.getOperand(1);
11057     SDValue FMAAcc = FMA.getOperand(2);
11058 
11059     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11060         FMAOp2.getOpcode() != ISD::FP_EXTEND)
11061       return SDValue();
11062 
11063     FMAOp1 = FMAOp1.getOperand(0);
11064     FMAOp2 = FMAOp2.getOperand(0);
11065     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11066         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11067       return SDValue();
11068 
11069     SDValue Vec3 = FMAOp1.getOperand(0);
11070     SDValue Vec4 = FMAOp2.getOperand(0);
11071     SDValue Idx2 = FMAOp1.getOperand(1);
11072 
11073     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11074         // Idx1 and Idx2 cannot be the same.
11075         Idx1 == Idx2)
11076       return SDValue();
11077 
11078     if (Vec1 == Vec2 || Vec3 == Vec4)
11079       return SDValue();
11080 
11081     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11082       return SDValue();
11083 
11084     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11085         (Vec1 == Vec4 && Vec2 == Vec3)) {
11086       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11087                          DAG.getTargetConstant(0, SL, MVT::i1));
11088     }
11089   }
11090   return SDValue();
11091 }
11092 
11093 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11094                                               DAGCombinerInfo &DCI) const {
11095   SelectionDAG &DAG = DCI.DAG;
11096   SDLoc SL(N);
11097 
11098   SDValue LHS = N->getOperand(0);
11099   SDValue RHS = N->getOperand(1);
11100   EVT VT = LHS.getValueType();
11101   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11102 
11103   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11104   if (!CRHS) {
11105     CRHS = dyn_cast<ConstantSDNode>(LHS);
11106     if (CRHS) {
11107       std::swap(LHS, RHS);
11108       CC = getSetCCSwappedOperands(CC);
11109     }
11110   }
11111 
11112   if (CRHS) {
11113     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11114         isBoolSGPR(LHS.getOperand(0))) {
11115       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11116       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11117       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11118       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11119       if ((CRHS->isAllOnes() &&
11120            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11121           (CRHS->isZero() &&
11122            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11123         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11124                            DAG.getConstant(-1, SL, MVT::i1));
11125       if ((CRHS->isAllOnes() &&
11126            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11127           (CRHS->isZero() &&
11128            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11129         return LHS.getOperand(0);
11130     }
11131 
11132     const APInt &CRHSVal = CRHS->getAPIntValue();
11133     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11134         LHS.getOpcode() == ISD::SELECT &&
11135         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11136         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11137         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11138         isBoolSGPR(LHS.getOperand(0))) {
11139       // Given CT != FT:
11140       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11141       // setcc (select cc, CT, CF), CF, ne => cc
11142       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11143       // setcc (select cc, CT, CF), CT, eq => cc
11144       const APInt &CT = LHS.getConstantOperandAPInt(1);
11145       const APInt &CF = LHS.getConstantOperandAPInt(2);
11146 
11147       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11148           (CT == CRHSVal && CC == ISD::SETNE))
11149         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11150                            DAG.getConstant(-1, SL, MVT::i1));
11151       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11152           (CT == CRHSVal && CC == ISD::SETEQ))
11153         return LHS.getOperand(0);
11154     }
11155   }
11156 
11157   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11158                                            VT != MVT::f16))
11159     return SDValue();
11160 
11161   // Match isinf/isfinite pattern
11162   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11163   // (fcmp one (fabs x), inf) -> (fp_class x,
11164   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11165   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11166     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11167     if (!CRHS)
11168       return SDValue();
11169 
11170     const APFloat &APF = CRHS->getValueAPF();
11171     if (APF.isInfinity() && !APF.isNegative()) {
11172       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11173                                  SIInstrFlags::N_INFINITY;
11174       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11175                                     SIInstrFlags::P_ZERO |
11176                                     SIInstrFlags::N_NORMAL |
11177                                     SIInstrFlags::P_NORMAL |
11178                                     SIInstrFlags::N_SUBNORMAL |
11179                                     SIInstrFlags::P_SUBNORMAL;
11180       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11181       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11182                          DAG.getConstant(Mask, SL, MVT::i32));
11183     }
11184   }
11185 
11186   return SDValue();
11187 }
11188 
11189 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11190                                                      DAGCombinerInfo &DCI) const {
11191   SelectionDAG &DAG = DCI.DAG;
11192   SDLoc SL(N);
11193   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11194 
11195   SDValue Src = N->getOperand(0);
11196   SDValue Shift = N->getOperand(0);
11197 
11198   // TODO: Extend type shouldn't matter (assuming legal types).
11199   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11200     Shift = Shift.getOperand(0);
11201 
11202   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11203     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11204     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11205     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11206     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11207     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11208     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11209       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11210                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11211 
11212       unsigned ShiftOffset = 8 * Offset;
11213       if (Shift.getOpcode() == ISD::SHL)
11214         ShiftOffset -= C->getZExtValue();
11215       else
11216         ShiftOffset += C->getZExtValue();
11217 
11218       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11219         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11220                            MVT::f32, Shifted);
11221       }
11222     }
11223   }
11224 
11225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11226   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11227   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11228     // We simplified Src. If this node is not dead, visit it again so it is
11229     // folded properly.
11230     if (N->getOpcode() != ISD::DELETED_NODE)
11231       DCI.AddToWorklist(N);
11232     return SDValue(N, 0);
11233   }
11234 
11235   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11236   if (SDValue DemandedSrc =
11237           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11238     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11239 
11240   return SDValue();
11241 }
11242 
11243 SDValue SITargetLowering::performClampCombine(SDNode *N,
11244                                               DAGCombinerInfo &DCI) const {
11245   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11246   if (!CSrc)
11247     return SDValue();
11248 
11249   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11250   const APFloat &F = CSrc->getValueAPF();
11251   APFloat Zero = APFloat::getZero(F.getSemantics());
11252   if (F < Zero ||
11253       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11254     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11255   }
11256 
11257   APFloat One(F.getSemantics(), "1.0");
11258   if (F > One)
11259     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11260 
11261   return SDValue(CSrc, 0);
11262 }
11263 
11264 
11265 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11266                                             DAGCombinerInfo &DCI) const {
11267   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11268     return SDValue();
11269   switch (N->getOpcode()) {
11270   case ISD::ADD:
11271     return performAddCombine(N, DCI);
11272   case ISD::SUB:
11273     return performSubCombine(N, DCI);
11274   case ISD::ADDCARRY:
11275   case ISD::SUBCARRY:
11276     return performAddCarrySubCarryCombine(N, DCI);
11277   case ISD::FADD:
11278     return performFAddCombine(N, DCI);
11279   case ISD::FSUB:
11280     return performFSubCombine(N, DCI);
11281   case ISD::SETCC:
11282     return performSetCCCombine(N, DCI);
11283   case ISD::FMAXNUM:
11284   case ISD::FMINNUM:
11285   case ISD::FMAXNUM_IEEE:
11286   case ISD::FMINNUM_IEEE:
11287   case ISD::SMAX:
11288   case ISD::SMIN:
11289   case ISD::UMAX:
11290   case ISD::UMIN:
11291   case AMDGPUISD::FMIN_LEGACY:
11292   case AMDGPUISD::FMAX_LEGACY:
11293     return performMinMaxCombine(N, DCI);
11294   case ISD::FMA:
11295     return performFMACombine(N, DCI);
11296   case ISD::AND:
11297     return performAndCombine(N, DCI);
11298   case ISD::OR:
11299     return performOrCombine(N, DCI);
11300   case ISD::XOR:
11301     return performXorCombine(N, DCI);
11302   case ISD::ZERO_EXTEND:
11303     return performZeroExtendCombine(N, DCI);
11304   case ISD::SIGN_EXTEND_INREG:
11305     return performSignExtendInRegCombine(N , DCI);
11306   case AMDGPUISD::FP_CLASS:
11307     return performClassCombine(N, DCI);
11308   case ISD::FCANONICALIZE:
11309     return performFCanonicalizeCombine(N, DCI);
11310   case AMDGPUISD::RCP:
11311     return performRcpCombine(N, DCI);
11312   case AMDGPUISD::FRACT:
11313   case AMDGPUISD::RSQ:
11314   case AMDGPUISD::RCP_LEGACY:
11315   case AMDGPUISD::RCP_IFLAG:
11316   case AMDGPUISD::RSQ_CLAMP:
11317   case AMDGPUISD::LDEXP: {
11318     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11319     SDValue Src = N->getOperand(0);
11320     if (Src.isUndef())
11321       return Src;
11322     break;
11323   }
11324   case ISD::SINT_TO_FP:
11325   case ISD::UINT_TO_FP:
11326     return performUCharToFloatCombine(N, DCI);
11327   case AMDGPUISD::CVT_F32_UBYTE0:
11328   case AMDGPUISD::CVT_F32_UBYTE1:
11329   case AMDGPUISD::CVT_F32_UBYTE2:
11330   case AMDGPUISD::CVT_F32_UBYTE3:
11331     return performCvtF32UByteNCombine(N, DCI);
11332   case AMDGPUISD::FMED3:
11333     return performFMed3Combine(N, DCI);
11334   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11335     return performCvtPkRTZCombine(N, DCI);
11336   case AMDGPUISD::CLAMP:
11337     return performClampCombine(N, DCI);
11338   case ISD::SCALAR_TO_VECTOR: {
11339     SelectionDAG &DAG = DCI.DAG;
11340     EVT VT = N->getValueType(0);
11341 
11342     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11343     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11344       SDLoc SL(N);
11345       SDValue Src = N->getOperand(0);
11346       EVT EltVT = Src.getValueType();
11347       if (EltVT == MVT::f16)
11348         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11349 
11350       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11351       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11352     }
11353 
11354     break;
11355   }
11356   case ISD::EXTRACT_VECTOR_ELT:
11357     return performExtractVectorEltCombine(N, DCI);
11358   case ISD::INSERT_VECTOR_ELT:
11359     return performInsertVectorEltCombine(N, DCI);
11360   case ISD::LOAD: {
11361     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11362       return Widended;
11363     LLVM_FALLTHROUGH;
11364   }
11365   default: {
11366     if (!DCI.isBeforeLegalize()) {
11367       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11368         return performMemSDNodeCombine(MemNode, DCI);
11369     }
11370 
11371     break;
11372   }
11373   }
11374 
11375   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11376 }
11377 
11378 /// Helper function for adjustWritemask
11379 static unsigned SubIdx2Lane(unsigned Idx) {
11380   switch (Idx) {
11381   default: return ~0u;
11382   case AMDGPU::sub0: return 0;
11383   case AMDGPU::sub1: return 1;
11384   case AMDGPU::sub2: return 2;
11385   case AMDGPU::sub3: return 3;
11386   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11387   }
11388 }
11389 
11390 /// Adjust the writemask of MIMG instructions
11391 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11392                                           SelectionDAG &DAG) const {
11393   unsigned Opcode = Node->getMachineOpcode();
11394 
11395   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11396   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11397   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11398     return Node; // not implemented for D16
11399 
11400   SDNode *Users[5] = { nullptr };
11401   unsigned Lane = 0;
11402   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11403   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11404   unsigned NewDmask = 0;
11405   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11406   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11407   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11408                   Node->getConstantOperandVal(LWEIdx))
11409                      ? true
11410                      : false;
11411   unsigned TFCLane = 0;
11412   bool HasChain = Node->getNumValues() > 1;
11413 
11414   if (OldDmask == 0) {
11415     // These are folded out, but on the chance it happens don't assert.
11416     return Node;
11417   }
11418 
11419   unsigned OldBitsSet = countPopulation(OldDmask);
11420   // Work out which is the TFE/LWE lane if that is enabled.
11421   if (UsesTFC) {
11422     TFCLane = OldBitsSet;
11423   }
11424 
11425   // Try to figure out the used register components
11426   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11427        I != E; ++I) {
11428 
11429     // Don't look at users of the chain.
11430     if (I.getUse().getResNo() != 0)
11431       continue;
11432 
11433     // Abort if we can't understand the usage
11434     if (!I->isMachineOpcode() ||
11435         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11436       return Node;
11437 
11438     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11439     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11440     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11441     // set, etc.
11442     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11443     if (Lane == ~0u)
11444       return Node;
11445 
11446     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11447     if (UsesTFC && Lane == TFCLane) {
11448       Users[Lane] = *I;
11449     } else {
11450       // Set which texture component corresponds to the lane.
11451       unsigned Comp;
11452       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11453         Comp = countTrailingZeros(Dmask);
11454         Dmask &= ~(1 << Comp);
11455       }
11456 
11457       // Abort if we have more than one user per component.
11458       if (Users[Lane])
11459         return Node;
11460 
11461       Users[Lane] = *I;
11462       NewDmask |= 1 << Comp;
11463     }
11464   }
11465 
11466   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11467   bool NoChannels = !NewDmask;
11468   if (NoChannels) {
11469     if (!UsesTFC) {
11470       // No uses of the result and not using TFC. Then do nothing.
11471       return Node;
11472     }
11473     // If the original dmask has one channel - then nothing to do
11474     if (OldBitsSet == 1)
11475       return Node;
11476     // Use an arbitrary dmask - required for the instruction to work
11477     NewDmask = 1;
11478   }
11479   // Abort if there's no change
11480   if (NewDmask == OldDmask)
11481     return Node;
11482 
11483   unsigned BitsSet = countPopulation(NewDmask);
11484 
11485   // Check for TFE or LWE - increase the number of channels by one to account
11486   // for the extra return value
11487   // This will need adjustment for D16 if this is also included in
11488   // adjustWriteMask (this function) but at present D16 are excluded.
11489   unsigned NewChannels = BitsSet + UsesTFC;
11490 
11491   int NewOpcode =
11492       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11493   assert(NewOpcode != -1 &&
11494          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11495          "failed to find equivalent MIMG op");
11496 
11497   // Adjust the writemask in the node
11498   SmallVector<SDValue, 12> Ops;
11499   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11500   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11501   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11502 
11503   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11504 
11505   MVT ResultVT = NewChannels == 1 ?
11506     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11507                            NewChannels == 5 ? 8 : NewChannels);
11508   SDVTList NewVTList = HasChain ?
11509     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11510 
11511 
11512   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11513                                               NewVTList, Ops);
11514 
11515   if (HasChain) {
11516     // Update chain.
11517     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11518     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11519   }
11520 
11521   if (NewChannels == 1) {
11522     assert(Node->hasNUsesOfValue(1, 0));
11523     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11524                                       SDLoc(Node), Users[Lane]->getValueType(0),
11525                                       SDValue(NewNode, 0));
11526     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11527     return nullptr;
11528   }
11529 
11530   // Update the users of the node with the new indices
11531   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11532     SDNode *User = Users[i];
11533     if (!User) {
11534       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11535       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11536       if (i || !NoChannels)
11537         continue;
11538     } else {
11539       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11540       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11541     }
11542 
11543     switch (Idx) {
11544     default: break;
11545     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11546     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11547     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11548     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11549     }
11550   }
11551 
11552   DAG.RemoveDeadNode(Node);
11553   return nullptr;
11554 }
11555 
11556 static bool isFrameIndexOp(SDValue Op) {
11557   if (Op.getOpcode() == ISD::AssertZext)
11558     Op = Op.getOperand(0);
11559 
11560   return isa<FrameIndexSDNode>(Op);
11561 }
11562 
11563 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11564 /// with frame index operands.
11565 /// LLVM assumes that inputs are to these instructions are registers.
11566 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11567                                                         SelectionDAG &DAG) const {
11568   if (Node->getOpcode() == ISD::CopyToReg) {
11569     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11570     SDValue SrcVal = Node->getOperand(2);
11571 
11572     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11573     // to try understanding copies to physical registers.
11574     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11575       SDLoc SL(Node);
11576       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11577       SDValue VReg = DAG.getRegister(
11578         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11579 
11580       SDNode *Glued = Node->getGluedNode();
11581       SDValue ToVReg
11582         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11583                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11584       SDValue ToResultReg
11585         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11586                            VReg, ToVReg.getValue(1));
11587       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11588       DAG.RemoveDeadNode(Node);
11589       return ToResultReg.getNode();
11590     }
11591   }
11592 
11593   SmallVector<SDValue, 8> Ops;
11594   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11595     if (!isFrameIndexOp(Node->getOperand(i))) {
11596       Ops.push_back(Node->getOperand(i));
11597       continue;
11598     }
11599 
11600     SDLoc DL(Node);
11601     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11602                                      Node->getOperand(i).getValueType(),
11603                                      Node->getOperand(i)), 0));
11604   }
11605 
11606   return DAG.UpdateNodeOperands(Node, Ops);
11607 }
11608 
11609 /// Fold the instructions after selecting them.
11610 /// Returns null if users were already updated.
11611 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11612                                           SelectionDAG &DAG) const {
11613   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11614   unsigned Opcode = Node->getMachineOpcode();
11615 
11616   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11617       !TII->isGather4(Opcode) &&
11618       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11619     return adjustWritemask(Node, DAG);
11620   }
11621 
11622   if (Opcode == AMDGPU::INSERT_SUBREG ||
11623       Opcode == AMDGPU::REG_SEQUENCE) {
11624     legalizeTargetIndependentNode(Node, DAG);
11625     return Node;
11626   }
11627 
11628   switch (Opcode) {
11629   case AMDGPU::V_DIV_SCALE_F32_e64:
11630   case AMDGPU::V_DIV_SCALE_F64_e64: {
11631     // Satisfy the operand register constraint when one of the inputs is
11632     // undefined. Ordinarily each undef value will have its own implicit_def of
11633     // a vreg, so force these to use a single register.
11634     SDValue Src0 = Node->getOperand(1);
11635     SDValue Src1 = Node->getOperand(3);
11636     SDValue Src2 = Node->getOperand(5);
11637 
11638     if ((Src0.isMachineOpcode() &&
11639          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11640         (Src0 == Src1 || Src0 == Src2))
11641       break;
11642 
11643     MVT VT = Src0.getValueType().getSimpleVT();
11644     const TargetRegisterClass *RC =
11645         getRegClassFor(VT, Src0.getNode()->isDivergent());
11646 
11647     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11648     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11649 
11650     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11651                                       UndefReg, Src0, SDValue());
11652 
11653     // src0 must be the same register as src1 or src2, even if the value is
11654     // undefined, so make sure we don't violate this constraint.
11655     if (Src0.isMachineOpcode() &&
11656         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11657       if (Src1.isMachineOpcode() &&
11658           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11659         Src0 = Src1;
11660       else if (Src2.isMachineOpcode() &&
11661                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11662         Src0 = Src2;
11663       else {
11664         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11665         Src0 = UndefReg;
11666         Src1 = UndefReg;
11667       }
11668     } else
11669       break;
11670 
11671     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11672     Ops[1] = Src0;
11673     Ops[3] = Src1;
11674     Ops[5] = Src2;
11675     Ops.push_back(ImpDef.getValue(1));
11676     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11677   }
11678   default:
11679     break;
11680   }
11681 
11682   return Node;
11683 }
11684 
11685 // Any MIMG instructions that use tfe or lwe require an initialization of the
11686 // result register that will be written in the case of a memory access failure.
11687 // The required code is also added to tie this init code to the result of the
11688 // img instruction.
11689 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11690   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11691   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11692   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11693   MachineBasicBlock &MBB = *MI.getParent();
11694 
11695   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11696   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11697   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11698 
11699   if (!TFE && !LWE) // intersect_ray
11700     return;
11701 
11702   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11703   unsigned LWEVal = LWE->getImm();
11704   unsigned D16Val = D16 ? D16->getImm() : 0;
11705 
11706   if (!TFEVal && !LWEVal)
11707     return;
11708 
11709   // At least one of TFE or LWE are non-zero
11710   // We have to insert a suitable initialization of the result value and
11711   // tie this to the dest of the image instruction.
11712 
11713   const DebugLoc &DL = MI.getDebugLoc();
11714 
11715   int DstIdx =
11716       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11717 
11718   // Calculate which dword we have to initialize to 0.
11719   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11720 
11721   // check that dmask operand is found.
11722   assert(MO_Dmask && "Expected dmask operand in instruction");
11723 
11724   unsigned dmask = MO_Dmask->getImm();
11725   // Determine the number of active lanes taking into account the
11726   // Gather4 special case
11727   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11728 
11729   bool Packed = !Subtarget->hasUnpackedD16VMem();
11730 
11731   unsigned InitIdx =
11732       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11733 
11734   // Abandon attempt if the dst size isn't large enough
11735   // - this is in fact an error but this is picked up elsewhere and
11736   // reported correctly.
11737   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11738   if (DstSize < InitIdx)
11739     return;
11740 
11741   // Create a register for the initialization value.
11742   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11743   unsigned NewDst = 0; // Final initialized value will be in here
11744 
11745   // If PRTStrictNull feature is enabled (the default) then initialize
11746   // all the result registers to 0, otherwise just the error indication
11747   // register (VGPRn+1)
11748   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11749   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11750 
11751   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11752   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11753     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11754     // Initialize dword
11755     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11756     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11757       .addImm(0);
11758     // Insert into the super-reg
11759     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11760       .addReg(PrevDst)
11761       .addReg(SubReg)
11762       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11763 
11764     PrevDst = NewDst;
11765   }
11766 
11767   // Add as an implicit operand
11768   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11769 
11770   // Tie the just added implicit operand to the dst
11771   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11772 }
11773 
11774 /// Assign the register class depending on the number of
11775 /// bits set in the writemask
11776 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11777                                                      SDNode *Node) const {
11778   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11779 
11780   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11781 
11782   if (TII->isVOP3(MI.getOpcode())) {
11783     // Make sure constant bus requirements are respected.
11784     TII->legalizeOperandsVOP3(MRI, MI);
11785 
11786     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11787     // This saves a chain-copy of registers and better balance register
11788     // use between vgpr and agpr as agpr tuples tend to be big.
11789     if (MI.getDesc().OpInfo) {
11790       unsigned Opc = MI.getOpcode();
11791       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11792       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11793                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11794         if (I == -1)
11795           break;
11796         MachineOperand &Op = MI.getOperand(I);
11797         if (!Op.isReg() || !Op.getReg().isVirtual())
11798           continue;
11799         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11800         if (!TRI->hasAGPRs(RC))
11801           continue;
11802         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11803         if (!Src || !Src->isCopy() ||
11804             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11805           continue;
11806         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11807         // All uses of agpr64 and agpr32 can also accept vgpr except for
11808         // v_accvgpr_read, but we do not produce agpr reads during selection,
11809         // so no use checks are needed.
11810         MRI.setRegClass(Op.getReg(), NewRC);
11811       }
11812 
11813       // Resolve the rest of AV operands to AGPRs.
11814       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11815         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11816           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11817           if (TRI->isVectorSuperClass(RC)) {
11818             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11819             MRI.setRegClass(Src2->getReg(), NewRC);
11820             if (Src2->isTied())
11821               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11822           }
11823         }
11824       }
11825     }
11826 
11827     return;
11828   }
11829 
11830   if (TII->isMIMG(MI)) {
11831     if (!MI.mayStore())
11832       AddIMGInit(MI);
11833     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
11834   }
11835 }
11836 
11837 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11838                               uint64_t Val) {
11839   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11840   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11841 }
11842 
11843 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11844                                                 const SDLoc &DL,
11845                                                 SDValue Ptr) const {
11846   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11847 
11848   // Build the half of the subregister with the constants before building the
11849   // full 128-bit register. If we are building multiple resource descriptors,
11850   // this will allow CSEing of the 2-component register.
11851   const SDValue Ops0[] = {
11852     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11853     buildSMovImm32(DAG, DL, 0),
11854     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11855     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11856     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11857   };
11858 
11859   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11860                                                 MVT::v2i32, Ops0), 0);
11861 
11862   // Combine the constants and the pointer.
11863   const SDValue Ops1[] = {
11864     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11865     Ptr,
11866     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11867     SubRegHi,
11868     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11869   };
11870 
11871   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11872 }
11873 
11874 /// Return a resource descriptor with the 'Add TID' bit enabled
11875 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11876 ///        of the resource descriptor) to create an offset, which is added to
11877 ///        the resource pointer.
11878 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11879                                            SDValue Ptr, uint32_t RsrcDword1,
11880                                            uint64_t RsrcDword2And3) const {
11881   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11882   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11883   if (RsrcDword1) {
11884     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11885                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11886                     0);
11887   }
11888 
11889   SDValue DataLo = buildSMovImm32(DAG, DL,
11890                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11891   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11892 
11893   const SDValue Ops[] = {
11894     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11895     PtrLo,
11896     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11897     PtrHi,
11898     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11899     DataLo,
11900     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11901     DataHi,
11902     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11903   };
11904 
11905   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11906 }
11907 
11908 //===----------------------------------------------------------------------===//
11909 //                         SI Inline Assembly Support
11910 //===----------------------------------------------------------------------===//
11911 
11912 std::pair<unsigned, const TargetRegisterClass *>
11913 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11914                                                StringRef Constraint,
11915                                                MVT VT) const {
11916   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11917 
11918   const TargetRegisterClass *RC = nullptr;
11919   if (Constraint.size() == 1) {
11920     const unsigned BitWidth = VT.getSizeInBits();
11921     switch (Constraint[0]) {
11922     default:
11923       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11924     case 's':
11925     case 'r':
11926       switch (BitWidth) {
11927       case 16:
11928         RC = &AMDGPU::SReg_32RegClass;
11929         break;
11930       case 64:
11931         RC = &AMDGPU::SGPR_64RegClass;
11932         break;
11933       default:
11934         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11935         if (!RC)
11936           return std::make_pair(0U, nullptr);
11937         break;
11938       }
11939       break;
11940     case 'v':
11941       switch (BitWidth) {
11942       case 16:
11943         RC = &AMDGPU::VGPR_32RegClass;
11944         break;
11945       default:
11946         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11947         if (!RC)
11948           return std::make_pair(0U, nullptr);
11949         break;
11950       }
11951       break;
11952     case 'a':
11953       if (!Subtarget->hasMAIInsts())
11954         break;
11955       switch (BitWidth) {
11956       case 16:
11957         RC = &AMDGPU::AGPR_32RegClass;
11958         break;
11959       default:
11960         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11961         if (!RC)
11962           return std::make_pair(0U, nullptr);
11963         break;
11964       }
11965       break;
11966     }
11967     // We actually support i128, i16 and f16 as inline parameters
11968     // even if they are not reported as legal
11969     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11970                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11971       return std::make_pair(0U, RC);
11972   }
11973 
11974   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11975     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11976     if (RegName.consume_front("v")) {
11977       RC = &AMDGPU::VGPR_32RegClass;
11978     } else if (RegName.consume_front("s")) {
11979       RC = &AMDGPU::SGPR_32RegClass;
11980     } else if (RegName.consume_front("a")) {
11981       RC = &AMDGPU::AGPR_32RegClass;
11982     }
11983 
11984     if (RC) {
11985       uint32_t Idx;
11986       if (RegName.consume_front("[")) {
11987         uint32_t End;
11988         bool Failed = RegName.consumeInteger(10, Idx);
11989         Failed |= !RegName.consume_front(":");
11990         Failed |= RegName.consumeInteger(10, End);
11991         Failed |= !RegName.consume_back("]");
11992         if (!Failed) {
11993           uint32_t Width = (End - Idx + 1) * 32;
11994           MCRegister Reg = RC->getRegister(Idx);
11995           if (SIRegisterInfo::isVGPRClass(RC))
11996             RC = TRI->getVGPRClassForBitWidth(Width);
11997           else if (SIRegisterInfo::isSGPRClass(RC))
11998             RC = TRI->getSGPRClassForBitWidth(Width);
11999           else if (SIRegisterInfo::isAGPRClass(RC))
12000             RC = TRI->getAGPRClassForBitWidth(Width);
12001           if (RC) {
12002             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12003             return std::make_pair(Reg, RC);
12004           }
12005         }
12006       } else {
12007         bool Failed = RegName.getAsInteger(10, Idx);
12008         if (!Failed && Idx < RC->getNumRegs())
12009           return std::make_pair(RC->getRegister(Idx), RC);
12010       }
12011     }
12012   }
12013 
12014   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12015   if (Ret.first)
12016     Ret.second = TRI->getPhysRegClass(Ret.first);
12017 
12018   return Ret;
12019 }
12020 
12021 static bool isImmConstraint(StringRef Constraint) {
12022   if (Constraint.size() == 1) {
12023     switch (Constraint[0]) {
12024     default: break;
12025     case 'I':
12026     case 'J':
12027     case 'A':
12028     case 'B':
12029     case 'C':
12030       return true;
12031     }
12032   } else if (Constraint == "DA" ||
12033              Constraint == "DB") {
12034     return true;
12035   }
12036   return false;
12037 }
12038 
12039 SITargetLowering::ConstraintType
12040 SITargetLowering::getConstraintType(StringRef Constraint) const {
12041   if (Constraint.size() == 1) {
12042     switch (Constraint[0]) {
12043     default: break;
12044     case 's':
12045     case 'v':
12046     case 'a':
12047       return C_RegisterClass;
12048     }
12049   }
12050   if (isImmConstraint(Constraint)) {
12051     return C_Other;
12052   }
12053   return TargetLowering::getConstraintType(Constraint);
12054 }
12055 
12056 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12057   if (!AMDGPU::isInlinableIntLiteral(Val)) {
12058     Val = Val & maskTrailingOnes<uint64_t>(Size);
12059   }
12060   return Val;
12061 }
12062 
12063 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12064                                                     std::string &Constraint,
12065                                                     std::vector<SDValue> &Ops,
12066                                                     SelectionDAG &DAG) const {
12067   if (isImmConstraint(Constraint)) {
12068     uint64_t Val;
12069     if (getAsmOperandConstVal(Op, Val) &&
12070         checkAsmConstraintVal(Op, Constraint, Val)) {
12071       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12072       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12073     }
12074   } else {
12075     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12076   }
12077 }
12078 
12079 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12080   unsigned Size = Op.getScalarValueSizeInBits();
12081   if (Size > 64)
12082     return false;
12083 
12084   if (Size == 16 && !Subtarget->has16BitInsts())
12085     return false;
12086 
12087   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12088     Val = C->getSExtValue();
12089     return true;
12090   }
12091   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12092     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12093     return true;
12094   }
12095   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12096     if (Size != 16 || Op.getNumOperands() != 2)
12097       return false;
12098     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12099       return false;
12100     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12101       Val = C->getSExtValue();
12102       return true;
12103     }
12104     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12105       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12106       return true;
12107     }
12108   }
12109 
12110   return false;
12111 }
12112 
12113 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12114                                              const std::string &Constraint,
12115                                              uint64_t Val) const {
12116   if (Constraint.size() == 1) {
12117     switch (Constraint[0]) {
12118     case 'I':
12119       return AMDGPU::isInlinableIntLiteral(Val);
12120     case 'J':
12121       return isInt<16>(Val);
12122     case 'A':
12123       return checkAsmConstraintValA(Op, Val);
12124     case 'B':
12125       return isInt<32>(Val);
12126     case 'C':
12127       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12128              AMDGPU::isInlinableIntLiteral(Val);
12129     default:
12130       break;
12131     }
12132   } else if (Constraint.size() == 2) {
12133     if (Constraint == "DA") {
12134       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12135       int64_t LoBits = static_cast<int32_t>(Val);
12136       return checkAsmConstraintValA(Op, HiBits, 32) &&
12137              checkAsmConstraintValA(Op, LoBits, 32);
12138     }
12139     if (Constraint == "DB") {
12140       return true;
12141     }
12142   }
12143   llvm_unreachable("Invalid asm constraint");
12144 }
12145 
12146 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12147                                               uint64_t Val,
12148                                               unsigned MaxSize) const {
12149   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12150   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12151   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12152       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12153       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12154     return true;
12155   }
12156   return false;
12157 }
12158 
12159 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12160   switch (UnalignedClassID) {
12161   case AMDGPU::VReg_64RegClassID:
12162     return AMDGPU::VReg_64_Align2RegClassID;
12163   case AMDGPU::VReg_96RegClassID:
12164     return AMDGPU::VReg_96_Align2RegClassID;
12165   case AMDGPU::VReg_128RegClassID:
12166     return AMDGPU::VReg_128_Align2RegClassID;
12167   case AMDGPU::VReg_160RegClassID:
12168     return AMDGPU::VReg_160_Align2RegClassID;
12169   case AMDGPU::VReg_192RegClassID:
12170     return AMDGPU::VReg_192_Align2RegClassID;
12171   case AMDGPU::VReg_224RegClassID:
12172     return AMDGPU::VReg_224_Align2RegClassID;
12173   case AMDGPU::VReg_256RegClassID:
12174     return AMDGPU::VReg_256_Align2RegClassID;
12175   case AMDGPU::VReg_512RegClassID:
12176     return AMDGPU::VReg_512_Align2RegClassID;
12177   case AMDGPU::VReg_1024RegClassID:
12178     return AMDGPU::VReg_1024_Align2RegClassID;
12179   case AMDGPU::AReg_64RegClassID:
12180     return AMDGPU::AReg_64_Align2RegClassID;
12181   case AMDGPU::AReg_96RegClassID:
12182     return AMDGPU::AReg_96_Align2RegClassID;
12183   case AMDGPU::AReg_128RegClassID:
12184     return AMDGPU::AReg_128_Align2RegClassID;
12185   case AMDGPU::AReg_160RegClassID:
12186     return AMDGPU::AReg_160_Align2RegClassID;
12187   case AMDGPU::AReg_192RegClassID:
12188     return AMDGPU::AReg_192_Align2RegClassID;
12189   case AMDGPU::AReg_256RegClassID:
12190     return AMDGPU::AReg_256_Align2RegClassID;
12191   case AMDGPU::AReg_512RegClassID:
12192     return AMDGPU::AReg_512_Align2RegClassID;
12193   case AMDGPU::AReg_1024RegClassID:
12194     return AMDGPU::AReg_1024_Align2RegClassID;
12195   default:
12196     return -1;
12197   }
12198 }
12199 
12200 // Figure out which registers should be reserved for stack access. Only after
12201 // the function is legalized do we know all of the non-spill stack objects or if
12202 // calls are present.
12203 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12204   MachineRegisterInfo &MRI = MF.getRegInfo();
12205   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12206   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12207   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12208   const SIInstrInfo *TII = ST.getInstrInfo();
12209 
12210   if (Info->isEntryFunction()) {
12211     // Callable functions have fixed registers used for stack access.
12212     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12213   }
12214 
12215   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12216                              Info->getStackPtrOffsetReg()));
12217   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12218     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12219 
12220   // We need to worry about replacing the default register with itself in case
12221   // of MIR testcases missing the MFI.
12222   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12223     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12224 
12225   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12226     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12227 
12228   Info->limitOccupancy(MF);
12229 
12230   if (ST.isWave32() && !MF.empty()) {
12231     for (auto &MBB : MF) {
12232       for (auto &MI : MBB) {
12233         TII->fixImplicitOperands(MI);
12234       }
12235     }
12236   }
12237 
12238   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12239   // classes if required. Ideally the register class constraints would differ
12240   // per-subtarget, but there's no easy way to achieve that right now. This is
12241   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12242   // from using them as the register class for legal types.
12243   if (ST.needsAlignedVGPRs()) {
12244     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12245       const Register Reg = Register::index2VirtReg(I);
12246       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12247       if (!RC)
12248         continue;
12249       int NewClassID = getAlignedAGPRClassID(RC->getID());
12250       if (NewClassID != -1)
12251         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12252     }
12253   }
12254 
12255   TargetLoweringBase::finalizeLowering(MF);
12256 }
12257 
12258 void SITargetLowering::computeKnownBitsForFrameIndex(
12259   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12260   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12261 
12262   // Set the high bits to zero based on the maximum allowed scratch size per
12263   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12264   // calculation won't overflow, so assume the sign bit is never set.
12265   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12266 }
12267 
12268 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12269                                    KnownBits &Known, unsigned Dim) {
12270   unsigned MaxValue =
12271       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12272   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12273 }
12274 
12275 void SITargetLowering::computeKnownBitsForTargetInstr(
12276     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12277     const MachineRegisterInfo &MRI, unsigned Depth) const {
12278   const MachineInstr *MI = MRI.getVRegDef(R);
12279   switch (MI->getOpcode()) {
12280   case AMDGPU::G_INTRINSIC: {
12281     switch (MI->getIntrinsicID()) {
12282     case Intrinsic::amdgcn_workitem_id_x:
12283       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12284       break;
12285     case Intrinsic::amdgcn_workitem_id_y:
12286       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12287       break;
12288     case Intrinsic::amdgcn_workitem_id_z:
12289       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12290       break;
12291     case Intrinsic::amdgcn_mbcnt_lo:
12292     case Intrinsic::amdgcn_mbcnt_hi: {
12293       // These return at most the wavefront size - 1.
12294       unsigned Size = MRI.getType(R).getSizeInBits();
12295       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12296       break;
12297     }
12298     case Intrinsic::amdgcn_groupstaticsize: {
12299       // We can report everything over the maximum size as 0. We can't report
12300       // based on the actual size because we don't know if it's accurate or not
12301       // at any given point.
12302       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12303       break;
12304     }
12305     }
12306     break;
12307   }
12308   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12309     Known.Zero.setHighBits(24);
12310     break;
12311   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12312     Known.Zero.setHighBits(16);
12313     break;
12314   }
12315 }
12316 
12317 Align SITargetLowering::computeKnownAlignForTargetInstr(
12318   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12319   unsigned Depth) const {
12320   const MachineInstr *MI = MRI.getVRegDef(R);
12321   switch (MI->getOpcode()) {
12322   case AMDGPU::G_INTRINSIC:
12323   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12324     // FIXME: Can this move to generic code? What about the case where the call
12325     // site specifies a lower alignment?
12326     Intrinsic::ID IID = MI->getIntrinsicID();
12327     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12328     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12329     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12330       return *RetAlign;
12331     return Align(1);
12332   }
12333   default:
12334     return Align(1);
12335   }
12336 }
12337 
12338 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12339   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12340   const Align CacheLineAlign = Align(64);
12341 
12342   // Pre-GFX10 target did not benefit from loop alignment
12343   if (!ML || DisableLoopAlignment ||
12344       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12345       getSubtarget()->hasInstFwdPrefetchBug())
12346     return PrefAlign;
12347 
12348   // On GFX10 I$ is 4 x 64 bytes cache lines.
12349   // By default prefetcher keeps one cache line behind and reads two ahead.
12350   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12351   // behind and one ahead.
12352   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12353   // If loop fits 64 bytes it always spans no more than two cache lines and
12354   // does not need an alignment.
12355   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12356   // Else if loop is less or equal 192 bytes we need two lines behind.
12357 
12358   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12359   const MachineBasicBlock *Header = ML->getHeader();
12360   if (Header->getAlignment() != PrefAlign)
12361     return Header->getAlignment(); // Already processed.
12362 
12363   unsigned LoopSize = 0;
12364   for (const MachineBasicBlock *MBB : ML->blocks()) {
12365     // If inner loop block is aligned assume in average half of the alignment
12366     // size to be added as nops.
12367     if (MBB != Header)
12368       LoopSize += MBB->getAlignment().value() / 2;
12369 
12370     for (const MachineInstr &MI : *MBB) {
12371       LoopSize += TII->getInstSizeInBytes(MI);
12372       if (LoopSize > 192)
12373         return PrefAlign;
12374     }
12375   }
12376 
12377   if (LoopSize <= 64)
12378     return PrefAlign;
12379 
12380   if (LoopSize <= 128)
12381     return CacheLineAlign;
12382 
12383   // If any of parent loops is surrounded by prefetch instructions do not
12384   // insert new for inner loop, which would reset parent's settings.
12385   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12386     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12387       auto I = Exit->getFirstNonDebugInstr();
12388       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12389         return CacheLineAlign;
12390     }
12391   }
12392 
12393   MachineBasicBlock *Pre = ML->getLoopPreheader();
12394   MachineBasicBlock *Exit = ML->getExitBlock();
12395 
12396   if (Pre && Exit) {
12397     auto PreTerm = Pre->getFirstTerminator();
12398     if (PreTerm == Pre->begin() ||
12399         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12400       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12401           .addImm(1); // prefetch 2 lines behind PC
12402 
12403     auto ExitHead = Exit->getFirstNonDebugInstr();
12404     if (ExitHead == Exit->end() ||
12405         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12406       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12407           .addImm(2); // prefetch 1 line behind PC
12408   }
12409 
12410   return CacheLineAlign;
12411 }
12412 
12413 LLVM_ATTRIBUTE_UNUSED
12414 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12415   assert(N->getOpcode() == ISD::CopyFromReg);
12416   do {
12417     // Follow the chain until we find an INLINEASM node.
12418     N = N->getOperand(0).getNode();
12419     if (N->getOpcode() == ISD::INLINEASM ||
12420         N->getOpcode() == ISD::INLINEASM_BR)
12421       return true;
12422   } while (N->getOpcode() == ISD::CopyFromReg);
12423   return false;
12424 }
12425 
12426 bool SITargetLowering::isSDNodeSourceOfDivergence(
12427     const SDNode *N, FunctionLoweringInfo *FLI,
12428     LegacyDivergenceAnalysis *KDA) const {
12429   switch (N->getOpcode()) {
12430   case ISD::CopyFromReg: {
12431     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12432     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12433     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12434     Register Reg = R->getReg();
12435 
12436     // FIXME: Why does this need to consider isLiveIn?
12437     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12438       return !TRI->isSGPRReg(MRI, Reg);
12439 
12440     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12441       return KDA->isDivergent(V);
12442 
12443     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12444     return !TRI->isSGPRReg(MRI, Reg);
12445   }
12446   case ISD::LOAD: {
12447     const LoadSDNode *L = cast<LoadSDNode>(N);
12448     unsigned AS = L->getAddressSpace();
12449     // A flat load may access private memory.
12450     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12451   }
12452   case ISD::CALLSEQ_END:
12453     return true;
12454   case ISD::INTRINSIC_WO_CHAIN:
12455     return AMDGPU::isIntrinsicSourceOfDivergence(
12456         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12457   case ISD::INTRINSIC_W_CHAIN:
12458     return AMDGPU::isIntrinsicSourceOfDivergence(
12459         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12460   case AMDGPUISD::ATOMIC_CMP_SWAP:
12461   case AMDGPUISD::ATOMIC_INC:
12462   case AMDGPUISD::ATOMIC_DEC:
12463   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12464   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12465   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12466   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12467   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12468   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12469   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12470   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12471   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12472   case AMDGPUISD::BUFFER_ATOMIC_AND:
12473   case AMDGPUISD::BUFFER_ATOMIC_OR:
12474   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12475   case AMDGPUISD::BUFFER_ATOMIC_INC:
12476   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12477   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12478   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12479   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12480   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12481   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12482     // Target-specific read-modify-write atomics are sources of divergence.
12483     return true;
12484   default:
12485     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12486       // Generic read-modify-write atomics are sources of divergence.
12487       return A->readMem() && A->writeMem();
12488     }
12489     return false;
12490   }
12491 }
12492 
12493 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12494                                                EVT VT) const {
12495   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12496   case MVT::f32:
12497     return hasFP32Denormals(DAG.getMachineFunction());
12498   case MVT::f64:
12499   case MVT::f16:
12500     return hasFP64FP16Denormals(DAG.getMachineFunction());
12501   default:
12502     return false;
12503   }
12504 }
12505 
12506 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12507                                                MachineFunction &MF) const {
12508   switch (Ty.getScalarSizeInBits()) {
12509   case 32:
12510     return hasFP32Denormals(MF);
12511   case 64:
12512   case 16:
12513     return hasFP64FP16Denormals(MF);
12514   default:
12515     return false;
12516   }
12517 }
12518 
12519 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12520                                                     const SelectionDAG &DAG,
12521                                                     bool SNaN,
12522                                                     unsigned Depth) const {
12523   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12524     const MachineFunction &MF = DAG.getMachineFunction();
12525     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12526 
12527     if (Info->getMode().DX10Clamp)
12528       return true; // Clamped to 0.
12529     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12530   }
12531 
12532   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12533                                                             SNaN, Depth);
12534 }
12535 
12536 // Global FP atomic instructions have a hardcoded FP mode and do not support
12537 // FP32 denormals, and only support v2f16 denormals.
12538 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12539   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12540   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12541   if (&Flt == &APFloat::IEEEsingle())
12542     return DenormMode == DenormalMode::getPreserveSign();
12543   return DenormMode == DenormalMode::getIEEE();
12544 }
12545 
12546 TargetLowering::AtomicExpansionKind
12547 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12548   unsigned AS = RMW->getPointerAddressSpace();
12549   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12550     return AtomicExpansionKind::NotAtomic;
12551 
12552   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12553     OptimizationRemarkEmitter ORE(RMW->getFunction());
12554     LLVMContext &Ctx = RMW->getFunction()->getContext();
12555     SmallVector<StringRef> SSNs;
12556     Ctx.getSyncScopeNames(SSNs);
12557     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12558                         ? "system"
12559                         : SSNs[RMW->getSyncScopeID()];
12560     ORE.emit([&]() {
12561       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12562              << "Hardware instruction generated for atomic "
12563              << RMW->getOperationName(RMW->getOperation())
12564              << " operation at memory scope " << MemScope
12565              << " due to an unsafe request.";
12566     });
12567     return Kind;
12568   };
12569 
12570   switch (RMW->getOperation()) {
12571   case AtomicRMWInst::FAdd: {
12572     Type *Ty = RMW->getType();
12573 
12574     // We don't have a way to support 16-bit atomics now, so just leave them
12575     // as-is.
12576     if (Ty->isHalfTy())
12577       return AtomicExpansionKind::None;
12578 
12579     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12580       return AtomicExpansionKind::CmpXChg;
12581 
12582     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12583          Subtarget->hasAtomicFaddInsts()) {
12584       if (Subtarget->hasGFX940Insts())
12585         return AtomicExpansionKind::None;
12586 
12587       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12588       // floating point atomic instructions. May generate more efficient code,
12589       // but may not respect rounding and denormal modes, and may give incorrect
12590       // results for certain memory destinations.
12591       if (RMW->getFunction()
12592               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12593               .getValueAsString() != "true")
12594         return AtomicExpansionKind::CmpXChg;
12595 
12596       if (Subtarget->hasGFX90AInsts()) {
12597         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12598           return AtomicExpansionKind::CmpXChg;
12599 
12600         auto SSID = RMW->getSyncScopeID();
12601         if (SSID == SyncScope::System ||
12602             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12603           return AtomicExpansionKind::CmpXChg;
12604 
12605         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12606       }
12607 
12608       if (AS == AMDGPUAS::FLAT_ADDRESS)
12609         return AtomicExpansionKind::CmpXChg;
12610 
12611       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12612                               : AtomicExpansionKind::CmpXChg;
12613     }
12614 
12615     // DS FP atomics do respect the denormal mode, but the rounding mode is
12616     // fixed to round-to-nearest-even.
12617     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12618     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12619       if (!Ty->isDoubleTy())
12620         return AtomicExpansionKind::None;
12621 
12622       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12623         return AtomicExpansionKind::None;
12624 
12625       return RMW->getFunction()
12626                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12627                          .getValueAsString() == "true"
12628                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12629                  : AtomicExpansionKind::CmpXChg;
12630     }
12631 
12632     return AtomicExpansionKind::CmpXChg;
12633   }
12634   default:
12635     break;
12636   }
12637 
12638   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12639 }
12640 
12641 TargetLowering::AtomicExpansionKind
12642 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12643   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12644              ? AtomicExpansionKind::NotAtomic
12645              : AtomicExpansionKind::None;
12646 }
12647 
12648 TargetLowering::AtomicExpansionKind
12649 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12650   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12651              ? AtomicExpansionKind::NotAtomic
12652              : AtomicExpansionKind::None;
12653 }
12654 
12655 TargetLowering::AtomicExpansionKind
12656 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12657   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12658              ? AtomicExpansionKind::NotAtomic
12659              : AtomicExpansionKind::None;
12660 }
12661 
12662 const TargetRegisterClass *
12663 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12664   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12665   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12666   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12667     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12668                                                : &AMDGPU::SReg_32RegClass;
12669   if (!TRI->isSGPRClass(RC) && !isDivergent)
12670     return TRI->getEquivalentSGPRClass(RC);
12671   else if (TRI->isSGPRClass(RC) && isDivergent)
12672     return TRI->getEquivalentVGPRClass(RC);
12673 
12674   return RC;
12675 }
12676 
12677 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12678 // uniform values (as produced by the mask results of control flow intrinsics)
12679 // used outside of divergent blocks. The phi users need to also be treated as
12680 // always uniform.
12681 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12682                       unsigned WaveSize) {
12683   // FIXME: We assume we never cast the mask results of a control flow
12684   // intrinsic.
12685   // Early exit if the type won't be consistent as a compile time hack.
12686   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12687   if (!IT || IT->getBitWidth() != WaveSize)
12688     return false;
12689 
12690   if (!isa<Instruction>(V))
12691     return false;
12692   if (!Visited.insert(V).second)
12693     return false;
12694   bool Result = false;
12695   for (auto U : V->users()) {
12696     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12697       if (V == U->getOperand(1)) {
12698         switch (Intrinsic->getIntrinsicID()) {
12699         default:
12700           Result = false;
12701           break;
12702         case Intrinsic::amdgcn_if_break:
12703         case Intrinsic::amdgcn_if:
12704         case Intrinsic::amdgcn_else:
12705           Result = true;
12706           break;
12707         }
12708       }
12709       if (V == U->getOperand(0)) {
12710         switch (Intrinsic->getIntrinsicID()) {
12711         default:
12712           Result = false;
12713           break;
12714         case Intrinsic::amdgcn_end_cf:
12715         case Intrinsic::amdgcn_loop:
12716           Result = true;
12717           break;
12718         }
12719       }
12720     } else {
12721       Result = hasCFUser(U, Visited, WaveSize);
12722     }
12723     if (Result)
12724       break;
12725   }
12726   return Result;
12727 }
12728 
12729 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12730                                                const Value *V) const {
12731   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12732     if (CI->isInlineAsm()) {
12733       // FIXME: This cannot give a correct answer. This should only trigger in
12734       // the case where inline asm returns mixed SGPR and VGPR results, used
12735       // outside the defining block. We don't have a specific result to
12736       // consider, so this assumes if any value is SGPR, the overall register
12737       // also needs to be SGPR.
12738       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12739       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12740           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12741       for (auto &TC : TargetConstraints) {
12742         if (TC.Type == InlineAsm::isOutput) {
12743           ComputeConstraintToUse(TC, SDValue());
12744           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12745               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12746           if (RC && SIRI->isSGPRClass(RC))
12747             return true;
12748         }
12749       }
12750     }
12751   }
12752   SmallPtrSet<const Value *, 16> Visited;
12753   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12754 }
12755 
12756 std::pair<InstructionCost, MVT>
12757 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12758                                           Type *Ty) const {
12759   std::pair<InstructionCost, MVT> Cost =
12760       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12761   auto Size = DL.getTypeSizeInBits(Ty);
12762   // Maximum load or store can handle 8 dwords for scalar and 4 for
12763   // vector ALU. Let's assume anything above 8 dwords is expensive
12764   // even if legal.
12765   if (Size <= 256)
12766     return Cost;
12767 
12768   Cost.first += (Size + 255) / 256;
12769   return Cost;
12770 }
12771 
12772 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12773   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12774   for (; I != E; ++I) {
12775     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12776       if (getBasePtrIndex(M) == I.getOperandNo())
12777         return true;
12778     }
12779   }
12780   return false;
12781 }
12782 
12783 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12784                                            SDValue N1) const {
12785   if (!N0.hasOneUse())
12786     return false;
12787   // Take care of the opportunity to keep N0 uniform
12788   if (N0->isDivergent() || !N1->isDivergent())
12789     return true;
12790   // Check if we have a good chance to form the memory access pattern with the
12791   // base and offset
12792   return (DAG.isBaseWithConstantOffset(N0) &&
12793           hasMemSDNodeUser(*N0->use_begin()));
12794 }
12795 
12796 MachineMemOperand::Flags
12797 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12798   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12799   if (I.getMetadata("amdgpu.noclobber"))
12800     return MONoClobber;
12801   return MachineMemOperand::MONone;
12802 }
12803