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::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
1585                                                unsigned Index) const {
1586   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
1587     return false;
1588 
1589   // TODO: Add more cases that are cheap.
1590   return Index == 0;
1591 }
1592 
1593 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1594   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1595     switch (Op) {
1596     case ISD::LOAD:
1597     case ISD::STORE:
1598 
1599     // These operations are done with 32-bit instructions anyway.
1600     case ISD::AND:
1601     case ISD::OR:
1602     case ISD::XOR:
1603     case ISD::SELECT:
1604       // TODO: Extensions?
1605       return true;
1606     default:
1607       return false;
1608     }
1609   }
1610 
1611   // SimplifySetCC uses this function to determine whether or not it should
1612   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1613   if (VT == MVT::i1 && Op == ISD::SETCC)
1614     return false;
1615 
1616   return TargetLowering::isTypeDesirableForOp(Op, VT);
1617 }
1618 
1619 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1620                                                    const SDLoc &SL,
1621                                                    SDValue Chain,
1622                                                    uint64_t Offset) const {
1623   const DataLayout &DL = DAG.getDataLayout();
1624   MachineFunction &MF = DAG.getMachineFunction();
1625   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1626 
1627   const ArgDescriptor *InputPtrReg;
1628   const TargetRegisterClass *RC;
1629   LLT ArgTy;
1630   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1631 
1632   std::tie(InputPtrReg, RC, ArgTy) =
1633       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1634 
1635   // We may not have the kernarg segment argument if we have no kernel
1636   // arguments.
1637   if (!InputPtrReg)
1638     return DAG.getConstant(0, SL, PtrVT);
1639 
1640   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1641   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1642     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1643 
1644   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1645 }
1646 
1647 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1648                                             const SDLoc &SL) const {
1649   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1650                                                FIRST_IMPLICIT);
1651   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1652 }
1653 
1654 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1655                                          const SDLoc &SL, SDValue Val,
1656                                          bool Signed,
1657                                          const ISD::InputArg *Arg) const {
1658   // First, if it is a widened vector, narrow it.
1659   if (VT.isVector() &&
1660       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1661     EVT NarrowedVT =
1662         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1663                          VT.getVectorNumElements());
1664     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1665                       DAG.getConstant(0, SL, MVT::i32));
1666   }
1667 
1668   // Then convert the vector elements or scalar value.
1669   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1670       VT.bitsLT(MemVT)) {
1671     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1672     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1673   }
1674 
1675   if (MemVT.isFloatingPoint())
1676     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1677   else if (Signed)
1678     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1679   else
1680     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1681 
1682   return Val;
1683 }
1684 
1685 SDValue SITargetLowering::lowerKernargMemParameter(
1686     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1687     uint64_t Offset, Align Alignment, bool Signed,
1688     const ISD::InputArg *Arg) const {
1689   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1690 
1691   // Try to avoid using an extload by loading earlier than the argument address,
1692   // and extracting the relevant bits. The load should hopefully be merged with
1693   // the previous argument.
1694   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1695     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1696     int64_t AlignDownOffset = alignDown(Offset, 4);
1697     int64_t OffsetDiff = Offset - AlignDownOffset;
1698 
1699     EVT IntVT = MemVT.changeTypeToInteger();
1700 
1701     // TODO: If we passed in the base kernel offset we could have a better
1702     // alignment than 4, but we don't really need it.
1703     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1704     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1705                                MachineMemOperand::MODereferenceable |
1706                                    MachineMemOperand::MOInvariant);
1707 
1708     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1709     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1710 
1711     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1712     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1713     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1714 
1715 
1716     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1717   }
1718 
1719   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1720   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1721                              MachineMemOperand::MODereferenceable |
1722                                  MachineMemOperand::MOInvariant);
1723 
1724   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1725   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1726 }
1727 
1728 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1729                                               const SDLoc &SL, SDValue Chain,
1730                                               const ISD::InputArg &Arg) const {
1731   MachineFunction &MF = DAG.getMachineFunction();
1732   MachineFrameInfo &MFI = MF.getFrameInfo();
1733 
1734   if (Arg.Flags.isByVal()) {
1735     unsigned Size = Arg.Flags.getByValSize();
1736     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1737     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1738   }
1739 
1740   unsigned ArgOffset = VA.getLocMemOffset();
1741   unsigned ArgSize = VA.getValVT().getStoreSize();
1742 
1743   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1744 
1745   // Create load nodes to retrieve arguments from the stack.
1746   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1747   SDValue ArgValue;
1748 
1749   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1750   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1751   MVT MemVT = VA.getValVT();
1752 
1753   switch (VA.getLocInfo()) {
1754   default:
1755     break;
1756   case CCValAssign::BCvt:
1757     MemVT = VA.getLocVT();
1758     break;
1759   case CCValAssign::SExt:
1760     ExtType = ISD::SEXTLOAD;
1761     break;
1762   case CCValAssign::ZExt:
1763     ExtType = ISD::ZEXTLOAD;
1764     break;
1765   case CCValAssign::AExt:
1766     ExtType = ISD::EXTLOAD;
1767     break;
1768   }
1769 
1770   ArgValue = DAG.getExtLoad(
1771     ExtType, SL, VA.getLocVT(), Chain, FIN,
1772     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1773     MemVT);
1774   return ArgValue;
1775 }
1776 
1777 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1778   const SIMachineFunctionInfo &MFI,
1779   EVT VT,
1780   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1781   const ArgDescriptor *Reg;
1782   const TargetRegisterClass *RC;
1783   LLT Ty;
1784 
1785   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1786   if (!Reg) {
1787     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1788       // It's possible for a kernarg intrinsic call to appear in a kernel with
1789       // no allocated segment, in which case we do not add the user sgpr
1790       // argument, so just return null.
1791       return DAG.getConstant(0, SDLoc(), VT);
1792     }
1793 
1794     // It's undefined behavior if a function marked with the amdgpu-no-*
1795     // attributes uses the corresponding intrinsic.
1796     return DAG.getUNDEF(VT);
1797   }
1798 
1799   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1800 }
1801 
1802 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1803                                CallingConv::ID CallConv,
1804                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1805                                FunctionType *FType,
1806                                SIMachineFunctionInfo *Info) {
1807   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1808     const ISD::InputArg *Arg = &Ins[I];
1809 
1810     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1811            "vector type argument should have been split");
1812 
1813     // First check if it's a PS input addr.
1814     if (CallConv == CallingConv::AMDGPU_PS &&
1815         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1816       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1817 
1818       // Inconveniently only the first part of the split is marked as isSplit,
1819       // so skip to the end. We only want to increment PSInputNum once for the
1820       // entire split argument.
1821       if (Arg->Flags.isSplit()) {
1822         while (!Arg->Flags.isSplitEnd()) {
1823           assert((!Arg->VT.isVector() ||
1824                   Arg->VT.getScalarSizeInBits() == 16) &&
1825                  "unexpected vector split in ps argument type");
1826           if (!SkipArg)
1827             Splits.push_back(*Arg);
1828           Arg = &Ins[++I];
1829         }
1830       }
1831 
1832       if (SkipArg) {
1833         // We can safely skip PS inputs.
1834         Skipped.set(Arg->getOrigArgIndex());
1835         ++PSInputNum;
1836         continue;
1837       }
1838 
1839       Info->markPSInputAllocated(PSInputNum);
1840       if (Arg->Used)
1841         Info->markPSInputEnabled(PSInputNum);
1842 
1843       ++PSInputNum;
1844     }
1845 
1846     Splits.push_back(*Arg);
1847   }
1848 }
1849 
1850 // Allocate special inputs passed in VGPRs.
1851 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1852                                                       MachineFunction &MF,
1853                                                       const SIRegisterInfo &TRI,
1854                                                       SIMachineFunctionInfo &Info) const {
1855   const LLT S32 = LLT::scalar(32);
1856   MachineRegisterInfo &MRI = MF.getRegInfo();
1857 
1858   if (Info.hasWorkItemIDX()) {
1859     Register Reg = AMDGPU::VGPR0;
1860     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1861 
1862     CCInfo.AllocateReg(Reg);
1863     unsigned Mask = (Subtarget->hasPackedTID() &&
1864                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1865     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1866   }
1867 
1868   if (Info.hasWorkItemIDY()) {
1869     assert(Info.hasWorkItemIDX());
1870     if (Subtarget->hasPackedTID()) {
1871       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1872                                                         0x3ff << 10));
1873     } else {
1874       unsigned Reg = AMDGPU::VGPR1;
1875       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1876 
1877       CCInfo.AllocateReg(Reg);
1878       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1879     }
1880   }
1881 
1882   if (Info.hasWorkItemIDZ()) {
1883     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1884     if (Subtarget->hasPackedTID()) {
1885       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1886                                                         0x3ff << 20));
1887     } else {
1888       unsigned Reg = AMDGPU::VGPR2;
1889       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1890 
1891       CCInfo.AllocateReg(Reg);
1892       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1893     }
1894   }
1895 }
1896 
1897 // Try to allocate a VGPR at the end of the argument list, or if no argument
1898 // VGPRs are left allocating a stack slot.
1899 // If \p Mask is is given it indicates bitfield position in the register.
1900 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1901 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1902                                          ArgDescriptor Arg = ArgDescriptor()) {
1903   if (Arg.isSet())
1904     return ArgDescriptor::createArg(Arg, Mask);
1905 
1906   ArrayRef<MCPhysReg> ArgVGPRs
1907     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1908   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1909   if (RegIdx == ArgVGPRs.size()) {
1910     // Spill to stack required.
1911     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1912 
1913     return ArgDescriptor::createStack(Offset, Mask);
1914   }
1915 
1916   unsigned Reg = ArgVGPRs[RegIdx];
1917   Reg = CCInfo.AllocateReg(Reg);
1918   assert(Reg != AMDGPU::NoRegister);
1919 
1920   MachineFunction &MF = CCInfo.getMachineFunction();
1921   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1922   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1923   return ArgDescriptor::createRegister(Reg, Mask);
1924 }
1925 
1926 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1927                                              const TargetRegisterClass *RC,
1928                                              unsigned NumArgRegs) {
1929   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1930   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1931   if (RegIdx == ArgSGPRs.size())
1932     report_fatal_error("ran out of SGPRs for arguments");
1933 
1934   unsigned Reg = ArgSGPRs[RegIdx];
1935   Reg = CCInfo.AllocateReg(Reg);
1936   assert(Reg != AMDGPU::NoRegister);
1937 
1938   MachineFunction &MF = CCInfo.getMachineFunction();
1939   MF.addLiveIn(Reg, RC);
1940   return ArgDescriptor::createRegister(Reg);
1941 }
1942 
1943 // If this has a fixed position, we still should allocate the register in the
1944 // CCInfo state. Technically we could get away with this for values passed
1945 // outside of the normal argument range.
1946 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1947                                        const TargetRegisterClass *RC,
1948                                        MCRegister Reg) {
1949   Reg = CCInfo.AllocateReg(Reg);
1950   assert(Reg != AMDGPU::NoRegister);
1951   MachineFunction &MF = CCInfo.getMachineFunction();
1952   MF.addLiveIn(Reg, RC);
1953 }
1954 
1955 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1956   if (Arg) {
1957     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1958                                Arg.getRegister());
1959   } else
1960     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1961 }
1962 
1963 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1964   if (Arg) {
1965     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1966                                Arg.getRegister());
1967   } else
1968     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1969 }
1970 
1971 /// Allocate implicit function VGPR arguments at the end of allocated user
1972 /// arguments.
1973 void SITargetLowering::allocateSpecialInputVGPRs(
1974   CCState &CCInfo, MachineFunction &MF,
1975   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1976   const unsigned Mask = 0x3ff;
1977   ArgDescriptor Arg;
1978 
1979   if (Info.hasWorkItemIDX()) {
1980     Arg = allocateVGPR32Input(CCInfo, Mask);
1981     Info.setWorkItemIDX(Arg);
1982   }
1983 
1984   if (Info.hasWorkItemIDY()) {
1985     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1986     Info.setWorkItemIDY(Arg);
1987   }
1988 
1989   if (Info.hasWorkItemIDZ())
1990     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1991 }
1992 
1993 /// Allocate implicit function VGPR arguments in fixed registers.
1994 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1995   CCState &CCInfo, MachineFunction &MF,
1996   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1997   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1998   if (!Reg)
1999     report_fatal_error("failed to allocated VGPR for implicit arguments");
2000 
2001   const unsigned Mask = 0x3ff;
2002   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2003   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2004   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2005 }
2006 
2007 void SITargetLowering::allocateSpecialInputSGPRs(
2008   CCState &CCInfo,
2009   MachineFunction &MF,
2010   const SIRegisterInfo &TRI,
2011   SIMachineFunctionInfo &Info) const {
2012   auto &ArgInfo = Info.getArgInfo();
2013 
2014   // TODO: Unify handling with private memory pointers.
2015   if (Info.hasDispatchPtr())
2016     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2017 
2018   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2019     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2020 
2021   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2022   // constant offset from the kernarg segment.
2023   if (Info.hasImplicitArgPtr())
2024     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2025 
2026   if (Info.hasDispatchID())
2027     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2028 
2029   // flat_scratch_init is not applicable for non-kernel functions.
2030 
2031   if (Info.hasWorkGroupIDX())
2032     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2033 
2034   if (Info.hasWorkGroupIDY())
2035     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2036 
2037   if (Info.hasWorkGroupIDZ())
2038     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2039 }
2040 
2041 // Allocate special inputs passed in user SGPRs.
2042 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2043                                             MachineFunction &MF,
2044                                             const SIRegisterInfo &TRI,
2045                                             SIMachineFunctionInfo &Info) const {
2046   if (Info.hasImplicitBufferPtr()) {
2047     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2048     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2049     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2050   }
2051 
2052   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2053   if (Info.hasPrivateSegmentBuffer()) {
2054     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2055     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2056     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2057   }
2058 
2059   if (Info.hasDispatchPtr()) {
2060     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2061     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2062     CCInfo.AllocateReg(DispatchPtrReg);
2063   }
2064 
2065   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2066     Register QueuePtrReg = Info.addQueuePtr(TRI);
2067     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2068     CCInfo.AllocateReg(QueuePtrReg);
2069   }
2070 
2071   if (Info.hasKernargSegmentPtr()) {
2072     MachineRegisterInfo &MRI = MF.getRegInfo();
2073     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2074     CCInfo.AllocateReg(InputPtrReg);
2075 
2076     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2077     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2078   }
2079 
2080   if (Info.hasDispatchID()) {
2081     Register DispatchIDReg = Info.addDispatchID(TRI);
2082     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2083     CCInfo.AllocateReg(DispatchIDReg);
2084   }
2085 
2086   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2087     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2088     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2089     CCInfo.AllocateReg(FlatScratchInitReg);
2090   }
2091 
2092   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2093   // these from the dispatch pointer.
2094 }
2095 
2096 // Allocate special input registers that are initialized per-wave.
2097 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2098                                            MachineFunction &MF,
2099                                            SIMachineFunctionInfo &Info,
2100                                            CallingConv::ID CallConv,
2101                                            bool IsShader) const {
2102   if (Info.hasWorkGroupIDX()) {
2103     Register Reg = Info.addWorkGroupIDX();
2104     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2105     CCInfo.AllocateReg(Reg);
2106   }
2107 
2108   if (Info.hasWorkGroupIDY()) {
2109     Register Reg = Info.addWorkGroupIDY();
2110     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2111     CCInfo.AllocateReg(Reg);
2112   }
2113 
2114   if (Info.hasWorkGroupIDZ()) {
2115     Register Reg = Info.addWorkGroupIDZ();
2116     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2117     CCInfo.AllocateReg(Reg);
2118   }
2119 
2120   if (Info.hasWorkGroupInfo()) {
2121     Register Reg = Info.addWorkGroupInfo();
2122     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2123     CCInfo.AllocateReg(Reg);
2124   }
2125 
2126   if (Info.hasPrivateSegmentWaveByteOffset()) {
2127     // Scratch wave offset passed in system SGPR.
2128     unsigned PrivateSegmentWaveByteOffsetReg;
2129 
2130     if (IsShader) {
2131       PrivateSegmentWaveByteOffsetReg =
2132         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2133 
2134       // This is true if the scratch wave byte offset doesn't have a fixed
2135       // location.
2136       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2137         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2138         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2139       }
2140     } else
2141       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2142 
2143     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2144     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2145   }
2146 }
2147 
2148 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2149                                      MachineFunction &MF,
2150                                      const SIRegisterInfo &TRI,
2151                                      SIMachineFunctionInfo &Info) {
2152   // Now that we've figured out where the scratch register inputs are, see if
2153   // should reserve the arguments and use them directly.
2154   MachineFrameInfo &MFI = MF.getFrameInfo();
2155   bool HasStackObjects = MFI.hasStackObjects();
2156   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2157 
2158   // Record that we know we have non-spill stack objects so we don't need to
2159   // check all stack objects later.
2160   if (HasStackObjects)
2161     Info.setHasNonSpillStackObjects(true);
2162 
2163   // Everything live out of a block is spilled with fast regalloc, so it's
2164   // almost certain that spilling will be required.
2165   if (TM.getOptLevel() == CodeGenOpt::None)
2166     HasStackObjects = true;
2167 
2168   // For now assume stack access is needed in any callee functions, so we need
2169   // the scratch registers to pass in.
2170   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2171 
2172   if (!ST.enableFlatScratch()) {
2173     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2174       // If we have stack objects, we unquestionably need the private buffer
2175       // resource. For the Code Object V2 ABI, this will be the first 4 user
2176       // SGPR inputs. We can reserve those and use them directly.
2177 
2178       Register PrivateSegmentBufferReg =
2179           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2180       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2181     } else {
2182       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2183       // We tentatively reserve the last registers (skipping the last registers
2184       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2185       // we'll replace these with the ones immediately after those which were
2186       // really allocated. In the prologue copies will be inserted from the
2187       // argument to these reserved registers.
2188 
2189       // Without HSA, relocations are used for the scratch pointer and the
2190       // buffer resource setup is always inserted in the prologue. Scratch wave
2191       // offset is still in an input SGPR.
2192       Info.setScratchRSrcReg(ReservedBufferReg);
2193     }
2194   }
2195 
2196   MachineRegisterInfo &MRI = MF.getRegInfo();
2197 
2198   // For entry functions we have to set up the stack pointer if we use it,
2199   // whereas non-entry functions get this "for free". This means there is no
2200   // intrinsic advantage to using S32 over S34 in cases where we do not have
2201   // calls but do need a frame pointer (i.e. if we are requested to have one
2202   // because frame pointer elimination is disabled). To keep things simple we
2203   // only ever use S32 as the call ABI stack pointer, and so using it does not
2204   // imply we need a separate frame pointer.
2205   //
2206   // Try to use s32 as the SP, but move it if it would interfere with input
2207   // arguments. This won't work with calls though.
2208   //
2209   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2210   // registers.
2211   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2212     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2213   } else {
2214     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2215 
2216     if (MFI.hasCalls())
2217       report_fatal_error("call in graphics shader with too many input SGPRs");
2218 
2219     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2220       if (!MRI.isLiveIn(Reg)) {
2221         Info.setStackPtrOffsetReg(Reg);
2222         break;
2223       }
2224     }
2225 
2226     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2227       report_fatal_error("failed to find register for SP");
2228   }
2229 
2230   // hasFP should be accurate for entry functions even before the frame is
2231   // finalized, because it does not rely on the known stack size, only
2232   // properties like whether variable sized objects are present.
2233   if (ST.getFrameLowering()->hasFP(MF)) {
2234     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2235   }
2236 }
2237 
2238 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2239   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2240   return !Info->isEntryFunction();
2241 }
2242 
2243 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2244 
2245 }
2246 
2247 void SITargetLowering::insertCopiesSplitCSR(
2248   MachineBasicBlock *Entry,
2249   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2250   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2251 
2252   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2253   if (!IStart)
2254     return;
2255 
2256   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2257   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2258   MachineBasicBlock::iterator MBBI = Entry->begin();
2259   for (const MCPhysReg *I = IStart; *I; ++I) {
2260     const TargetRegisterClass *RC = nullptr;
2261     if (AMDGPU::SReg_64RegClass.contains(*I))
2262       RC = &AMDGPU::SGPR_64RegClass;
2263     else if (AMDGPU::SReg_32RegClass.contains(*I))
2264       RC = &AMDGPU::SGPR_32RegClass;
2265     else
2266       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2267 
2268     Register NewVR = MRI->createVirtualRegister(RC);
2269     // Create copy from CSR to a virtual register.
2270     Entry->addLiveIn(*I);
2271     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2272       .addReg(*I);
2273 
2274     // Insert the copy-back instructions right before the terminator.
2275     for (auto *Exit : Exits)
2276       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2277               TII->get(TargetOpcode::COPY), *I)
2278         .addReg(NewVR);
2279   }
2280 }
2281 
2282 SDValue SITargetLowering::LowerFormalArguments(
2283     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2284     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2285     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2286   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2287 
2288   MachineFunction &MF = DAG.getMachineFunction();
2289   const Function &Fn = MF.getFunction();
2290   FunctionType *FType = MF.getFunction().getFunctionType();
2291   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2292 
2293   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2294     DiagnosticInfoUnsupported NoGraphicsHSA(
2295         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2296     DAG.getContext()->diagnose(NoGraphicsHSA);
2297     return DAG.getEntryNode();
2298   }
2299 
2300   Info->allocateModuleLDSGlobal(Fn);
2301 
2302   SmallVector<ISD::InputArg, 16> Splits;
2303   SmallVector<CCValAssign, 16> ArgLocs;
2304   BitVector Skipped(Ins.size());
2305   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2306                  *DAG.getContext());
2307 
2308   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2309   bool IsKernel = AMDGPU::isKernel(CallConv);
2310   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2311 
2312   if (IsGraphics) {
2313     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2314            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2315            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2316            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2317            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2318            !Info->hasWorkItemIDZ());
2319   }
2320 
2321   if (CallConv == CallingConv::AMDGPU_PS) {
2322     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2323 
2324     // At least one interpolation mode must be enabled or else the GPU will
2325     // hang.
2326     //
2327     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2328     // set PSInputAddr, the user wants to enable some bits after the compilation
2329     // based on run-time states. Since we can't know what the final PSInputEna
2330     // will look like, so we shouldn't do anything here and the user should take
2331     // responsibility for the correct programming.
2332     //
2333     // Otherwise, the following restrictions apply:
2334     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2335     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2336     //   enabled too.
2337     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2338         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2339       CCInfo.AllocateReg(AMDGPU::VGPR0);
2340       CCInfo.AllocateReg(AMDGPU::VGPR1);
2341       Info->markPSInputAllocated(0);
2342       Info->markPSInputEnabled(0);
2343     }
2344     if (Subtarget->isAmdPalOS()) {
2345       // For isAmdPalOS, the user does not enable some bits after compilation
2346       // based on run-time states; the register values being generated here are
2347       // the final ones set in hardware. Therefore we need to apply the
2348       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2349       // a bit is set in PSInputAddr but not PSInputEnable is where the
2350       // frontend set up an input arg for a particular interpolation mode, but
2351       // nothing uses that input arg. Really we should have an earlier pass
2352       // that removes such an arg.)
2353       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2354       if ((PsInputBits & 0x7F) == 0 ||
2355           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2356         Info->markPSInputEnabled(
2357             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2358     }
2359   } else if (IsKernel) {
2360     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2361   } else {
2362     Splits.append(Ins.begin(), Ins.end());
2363   }
2364 
2365   if (IsEntryFunc) {
2366     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2367     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2368   } else if (!IsGraphics) {
2369     // For the fixed ABI, pass workitem IDs in the last argument register.
2370     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2371   }
2372 
2373   if (IsKernel) {
2374     analyzeFormalArgumentsCompute(CCInfo, Ins);
2375   } else {
2376     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2377     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2378   }
2379 
2380   SmallVector<SDValue, 16> Chains;
2381 
2382   // FIXME: This is the minimum kernel argument alignment. We should improve
2383   // this to the maximum alignment of the arguments.
2384   //
2385   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2386   // kern arg offset.
2387   const Align KernelArgBaseAlign = Align(16);
2388 
2389   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2390     const ISD::InputArg &Arg = Ins[i];
2391     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2392       InVals.push_back(DAG.getUNDEF(Arg.VT));
2393       continue;
2394     }
2395 
2396     CCValAssign &VA = ArgLocs[ArgIdx++];
2397     MVT VT = VA.getLocVT();
2398 
2399     if (IsEntryFunc && VA.isMemLoc()) {
2400       VT = Ins[i].VT;
2401       EVT MemVT = VA.getLocVT();
2402 
2403       const uint64_t Offset = VA.getLocMemOffset();
2404       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2405 
2406       if (Arg.Flags.isByRef()) {
2407         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2408 
2409         const GCNTargetMachine &TM =
2410             static_cast<const GCNTargetMachine &>(getTargetMachine());
2411         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2412                                     Arg.Flags.getPointerAddrSpace())) {
2413           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2414                                      Arg.Flags.getPointerAddrSpace());
2415         }
2416 
2417         InVals.push_back(Ptr);
2418         continue;
2419       }
2420 
2421       SDValue Arg = lowerKernargMemParameter(
2422         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2423       Chains.push_back(Arg.getValue(1));
2424 
2425       auto *ParamTy =
2426         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2427       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2428           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2429                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2430         // On SI local pointers are just offsets into LDS, so they are always
2431         // less than 16-bits.  On CI and newer they could potentially be
2432         // real pointers, so we can't guarantee their size.
2433         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2434                           DAG.getValueType(MVT::i16));
2435       }
2436 
2437       InVals.push_back(Arg);
2438       continue;
2439     } else if (!IsEntryFunc && VA.isMemLoc()) {
2440       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2441       InVals.push_back(Val);
2442       if (!Arg.Flags.isByVal())
2443         Chains.push_back(Val.getValue(1));
2444       continue;
2445     }
2446 
2447     assert(VA.isRegLoc() && "Parameter must be in a register!");
2448 
2449     Register Reg = VA.getLocReg();
2450     const TargetRegisterClass *RC = nullptr;
2451     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2452       RC = &AMDGPU::VGPR_32RegClass;
2453     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2454       RC = &AMDGPU::SGPR_32RegClass;
2455     else
2456       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2457     EVT ValVT = VA.getValVT();
2458 
2459     Reg = MF.addLiveIn(Reg, RC);
2460     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2461 
2462     if (Arg.Flags.isSRet()) {
2463       // The return object should be reasonably addressable.
2464 
2465       // FIXME: This helps when the return is a real sret. If it is a
2466       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2467       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2468       unsigned NumBits
2469         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2470       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2471         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2472     }
2473 
2474     // If this is an 8 or 16-bit value, it is really passed promoted
2475     // to 32 bits. Insert an assert[sz]ext to capture this, then
2476     // truncate to the right size.
2477     switch (VA.getLocInfo()) {
2478     case CCValAssign::Full:
2479       break;
2480     case CCValAssign::BCvt:
2481       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2482       break;
2483     case CCValAssign::SExt:
2484       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2485                         DAG.getValueType(ValVT));
2486       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2487       break;
2488     case CCValAssign::ZExt:
2489       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2490                         DAG.getValueType(ValVT));
2491       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2492       break;
2493     case CCValAssign::AExt:
2494       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2495       break;
2496     default:
2497       llvm_unreachable("Unknown loc info!");
2498     }
2499 
2500     InVals.push_back(Val);
2501   }
2502 
2503   // Start adding system SGPRs.
2504   if (IsEntryFunc) {
2505     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2506   } else {
2507     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2508     if (!IsGraphics)
2509       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2510   }
2511 
2512   auto &ArgUsageInfo =
2513     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2514   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2515 
2516   unsigned StackArgSize = CCInfo.getNextStackOffset();
2517   Info->setBytesInStackArgArea(StackArgSize);
2518 
2519   return Chains.empty() ? Chain :
2520     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2521 }
2522 
2523 // TODO: If return values can't fit in registers, we should return as many as
2524 // possible in registers before passing on stack.
2525 bool SITargetLowering::CanLowerReturn(
2526   CallingConv::ID CallConv,
2527   MachineFunction &MF, bool IsVarArg,
2528   const SmallVectorImpl<ISD::OutputArg> &Outs,
2529   LLVMContext &Context) const {
2530   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2531   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2532   // for shaders. Vector types should be explicitly handled by CC.
2533   if (AMDGPU::isEntryFunctionCC(CallConv))
2534     return true;
2535 
2536   SmallVector<CCValAssign, 16> RVLocs;
2537   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2538   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2539 }
2540 
2541 SDValue
2542 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2543                               bool isVarArg,
2544                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2545                               const SmallVectorImpl<SDValue> &OutVals,
2546                               const SDLoc &DL, SelectionDAG &DAG) const {
2547   MachineFunction &MF = DAG.getMachineFunction();
2548   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2549 
2550   if (AMDGPU::isKernel(CallConv)) {
2551     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2552                                              OutVals, DL, DAG);
2553   }
2554 
2555   bool IsShader = AMDGPU::isShader(CallConv);
2556 
2557   Info->setIfReturnsVoid(Outs.empty());
2558   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2559 
2560   // CCValAssign - represent the assignment of the return value to a location.
2561   SmallVector<CCValAssign, 48> RVLocs;
2562   SmallVector<ISD::OutputArg, 48> Splits;
2563 
2564   // CCState - Info about the registers and stack slots.
2565   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2566                  *DAG.getContext());
2567 
2568   // Analyze outgoing return values.
2569   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2570 
2571   SDValue Flag;
2572   SmallVector<SDValue, 48> RetOps;
2573   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2574 
2575   // Copy the result values into the output registers.
2576   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2577        ++I, ++RealRVLocIdx) {
2578     CCValAssign &VA = RVLocs[I];
2579     assert(VA.isRegLoc() && "Can only return in registers!");
2580     // TODO: Partially return in registers if return values don't fit.
2581     SDValue Arg = OutVals[RealRVLocIdx];
2582 
2583     // Copied from other backends.
2584     switch (VA.getLocInfo()) {
2585     case CCValAssign::Full:
2586       break;
2587     case CCValAssign::BCvt:
2588       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2589       break;
2590     case CCValAssign::SExt:
2591       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2592       break;
2593     case CCValAssign::ZExt:
2594       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2595       break;
2596     case CCValAssign::AExt:
2597       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2598       break;
2599     default:
2600       llvm_unreachable("Unknown loc info!");
2601     }
2602 
2603     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2604     Flag = Chain.getValue(1);
2605     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2606   }
2607 
2608   // FIXME: Does sret work properly?
2609   if (!Info->isEntryFunction()) {
2610     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2611     const MCPhysReg *I =
2612       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2613     if (I) {
2614       for (; *I; ++I) {
2615         if (AMDGPU::SReg_64RegClass.contains(*I))
2616           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2617         else if (AMDGPU::SReg_32RegClass.contains(*I))
2618           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2619         else
2620           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2621       }
2622     }
2623   }
2624 
2625   // Update chain and glue.
2626   RetOps[0] = Chain;
2627   if (Flag.getNode())
2628     RetOps.push_back(Flag);
2629 
2630   unsigned Opc = AMDGPUISD::ENDPGM;
2631   if (!IsWaveEnd)
2632     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2633   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2634 }
2635 
2636 SDValue SITargetLowering::LowerCallResult(
2637     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2638     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2639     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2640     SDValue ThisVal) const {
2641   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2642 
2643   // Assign locations to each value returned by this call.
2644   SmallVector<CCValAssign, 16> RVLocs;
2645   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2646                  *DAG.getContext());
2647   CCInfo.AnalyzeCallResult(Ins, RetCC);
2648 
2649   // Copy all of the result registers out of their specified physreg.
2650   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2651     CCValAssign VA = RVLocs[i];
2652     SDValue Val;
2653 
2654     if (VA.isRegLoc()) {
2655       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2656       Chain = Val.getValue(1);
2657       InFlag = Val.getValue(2);
2658     } else if (VA.isMemLoc()) {
2659       report_fatal_error("TODO: return values in memory");
2660     } else
2661       llvm_unreachable("unknown argument location type");
2662 
2663     switch (VA.getLocInfo()) {
2664     case CCValAssign::Full:
2665       break;
2666     case CCValAssign::BCvt:
2667       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2668       break;
2669     case CCValAssign::ZExt:
2670       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2671                         DAG.getValueType(VA.getValVT()));
2672       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2673       break;
2674     case CCValAssign::SExt:
2675       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2676                         DAG.getValueType(VA.getValVT()));
2677       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2678       break;
2679     case CCValAssign::AExt:
2680       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2681       break;
2682     default:
2683       llvm_unreachable("Unknown loc info!");
2684     }
2685 
2686     InVals.push_back(Val);
2687   }
2688 
2689   return Chain;
2690 }
2691 
2692 // Add code to pass special inputs required depending on used features separate
2693 // from the explicit user arguments present in the IR.
2694 void SITargetLowering::passSpecialInputs(
2695     CallLoweringInfo &CLI,
2696     CCState &CCInfo,
2697     const SIMachineFunctionInfo &Info,
2698     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2699     SmallVectorImpl<SDValue> &MemOpChains,
2700     SDValue Chain) const {
2701   // If we don't have a call site, this was a call inserted by
2702   // legalization. These can never use special inputs.
2703   if (!CLI.CB)
2704     return;
2705 
2706   SelectionDAG &DAG = CLI.DAG;
2707   const SDLoc &DL = CLI.DL;
2708   const Function &F = DAG.getMachineFunction().getFunction();
2709 
2710   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2711   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2712 
2713   const AMDGPUFunctionArgInfo *CalleeArgInfo
2714     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2715   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2716     auto &ArgUsageInfo =
2717       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2718     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2719   }
2720 
2721   // TODO: Unify with private memory register handling. This is complicated by
2722   // the fact that at least in kernels, the input argument is not necessarily
2723   // in the same location as the input.
2724   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2725                              StringLiteral> ImplicitAttrs[] = {
2726     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2727     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2728     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2729     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2730     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2731     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2732     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2733   };
2734 
2735   for (auto Attr : ImplicitAttrs) {
2736     const ArgDescriptor *OutgoingArg;
2737     const TargetRegisterClass *ArgRC;
2738     LLT ArgTy;
2739 
2740     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2741 
2742     // If the callee does not use the attribute value, skip copying the value.
2743     if (CLI.CB->hasFnAttr(Attr.second))
2744       continue;
2745 
2746     std::tie(OutgoingArg, ArgRC, ArgTy) =
2747         CalleeArgInfo->getPreloadedValue(InputID);
2748     if (!OutgoingArg)
2749       continue;
2750 
2751     const ArgDescriptor *IncomingArg;
2752     const TargetRegisterClass *IncomingArgRC;
2753     LLT Ty;
2754     std::tie(IncomingArg, IncomingArgRC, Ty) =
2755         CallerArgInfo.getPreloadedValue(InputID);
2756     assert(IncomingArgRC == ArgRC);
2757 
2758     // All special arguments are ints for now.
2759     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2760     SDValue InputReg;
2761 
2762     if (IncomingArg) {
2763       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2764     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2765       // The implicit arg ptr is special because it doesn't have a corresponding
2766       // input for kernels, and is computed from the kernarg segment pointer.
2767       InputReg = getImplicitArgPtr(DAG, DL);
2768     } else {
2769       // We may have proven the input wasn't needed, although the ABI is
2770       // requiring it. We just need to allocate the register appropriately.
2771       InputReg = DAG.getUNDEF(ArgVT);
2772     }
2773 
2774     if (OutgoingArg->isRegister()) {
2775       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2776       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2777         report_fatal_error("failed to allocate implicit input argument");
2778     } else {
2779       unsigned SpecialArgOffset =
2780           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2781       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2782                                               SpecialArgOffset);
2783       MemOpChains.push_back(ArgStore);
2784     }
2785   }
2786 
2787   // Pack workitem IDs into a single register or pass it as is if already
2788   // packed.
2789   const ArgDescriptor *OutgoingArg;
2790   const TargetRegisterClass *ArgRC;
2791   LLT Ty;
2792 
2793   std::tie(OutgoingArg, ArgRC, Ty) =
2794       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2795   if (!OutgoingArg)
2796     std::tie(OutgoingArg, ArgRC, Ty) =
2797         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2798   if (!OutgoingArg)
2799     std::tie(OutgoingArg, ArgRC, Ty) =
2800         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2801   if (!OutgoingArg)
2802     return;
2803 
2804   const ArgDescriptor *IncomingArgX = std::get<0>(
2805       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2806   const ArgDescriptor *IncomingArgY = std::get<0>(
2807       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2808   const ArgDescriptor *IncomingArgZ = std::get<0>(
2809       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2810 
2811   SDValue InputReg;
2812   SDLoc SL;
2813 
2814   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2815   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2816   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2817 
2818   // If incoming ids are not packed we need to pack them.
2819   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2820       NeedWorkItemIDX) {
2821     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2822       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2823     } else {
2824       InputReg = DAG.getConstant(0, DL, MVT::i32);
2825     }
2826   }
2827 
2828   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2829       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2830     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2831     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2832                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2833     InputReg = InputReg.getNode() ?
2834                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2835   }
2836 
2837   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2838       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2839     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2840     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2841                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2842     InputReg = InputReg.getNode() ?
2843                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2844   }
2845 
2846   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2847     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2848       // We're in a situation where the outgoing function requires the workitem
2849       // ID, but the calling function does not have it (e.g a graphics function
2850       // calling a C calling convention function). This is illegal, but we need
2851       // to produce something.
2852       InputReg = DAG.getUNDEF(MVT::i32);
2853     } else {
2854       // Workitem ids are already packed, any of present incoming arguments
2855       // will carry all required fields.
2856       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2857         IncomingArgX ? *IncomingArgX :
2858         IncomingArgY ? *IncomingArgY :
2859         *IncomingArgZ, ~0u);
2860       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2861     }
2862   }
2863 
2864   if (OutgoingArg->isRegister()) {
2865     if (InputReg)
2866       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2867 
2868     CCInfo.AllocateReg(OutgoingArg->getRegister());
2869   } else {
2870     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2871     if (InputReg) {
2872       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2873                                               SpecialArgOffset);
2874       MemOpChains.push_back(ArgStore);
2875     }
2876   }
2877 }
2878 
2879 static bool canGuaranteeTCO(CallingConv::ID CC) {
2880   return CC == CallingConv::Fast;
2881 }
2882 
2883 /// Return true if we might ever do TCO for calls with this calling convention.
2884 static bool mayTailCallThisCC(CallingConv::ID CC) {
2885   switch (CC) {
2886   case CallingConv::C:
2887   case CallingConv::AMDGPU_Gfx:
2888     return true;
2889   default:
2890     return canGuaranteeTCO(CC);
2891   }
2892 }
2893 
2894 bool SITargetLowering::isEligibleForTailCallOptimization(
2895     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2896     const SmallVectorImpl<ISD::OutputArg> &Outs,
2897     const SmallVectorImpl<SDValue> &OutVals,
2898     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2899   if (!mayTailCallThisCC(CalleeCC))
2900     return false;
2901 
2902   // For a divergent call target, we need to do a waterfall loop over the
2903   // possible callees which precludes us from using a simple jump.
2904   if (Callee->isDivergent())
2905     return false;
2906 
2907   MachineFunction &MF = DAG.getMachineFunction();
2908   const Function &CallerF = MF.getFunction();
2909   CallingConv::ID CallerCC = CallerF.getCallingConv();
2910   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2911   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2912 
2913   // Kernels aren't callable, and don't have a live in return address so it
2914   // doesn't make sense to do a tail call with entry functions.
2915   if (!CallerPreserved)
2916     return false;
2917 
2918   bool CCMatch = CallerCC == CalleeCC;
2919 
2920   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2921     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2922       return true;
2923     return false;
2924   }
2925 
2926   // TODO: Can we handle var args?
2927   if (IsVarArg)
2928     return false;
2929 
2930   for (const Argument &Arg : CallerF.args()) {
2931     if (Arg.hasByValAttr())
2932       return false;
2933   }
2934 
2935   LLVMContext &Ctx = *DAG.getContext();
2936 
2937   // Check that the call results are passed in the same way.
2938   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2939                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2940                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2941     return false;
2942 
2943   // The callee has to preserve all registers the caller needs to preserve.
2944   if (!CCMatch) {
2945     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2946     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2947       return false;
2948   }
2949 
2950   // Nothing more to check if the callee is taking no arguments.
2951   if (Outs.empty())
2952     return true;
2953 
2954   SmallVector<CCValAssign, 16> ArgLocs;
2955   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2956 
2957   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2958 
2959   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2960   // If the stack arguments for this call do not fit into our own save area then
2961   // the call cannot be made tail.
2962   // TODO: Is this really necessary?
2963   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2964     return false;
2965 
2966   const MachineRegisterInfo &MRI = MF.getRegInfo();
2967   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2968 }
2969 
2970 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2971   if (!CI->isTailCall())
2972     return false;
2973 
2974   const Function *ParentFn = CI->getParent()->getParent();
2975   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2976     return false;
2977   return true;
2978 }
2979 
2980 // The wave scratch offset register is used as the global base pointer.
2981 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2982                                     SmallVectorImpl<SDValue> &InVals) const {
2983   SelectionDAG &DAG = CLI.DAG;
2984   const SDLoc &DL = CLI.DL;
2985   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2986   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2987   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2988   SDValue Chain = CLI.Chain;
2989   SDValue Callee = CLI.Callee;
2990   bool &IsTailCall = CLI.IsTailCall;
2991   CallingConv::ID CallConv = CLI.CallConv;
2992   bool IsVarArg = CLI.IsVarArg;
2993   bool IsSibCall = false;
2994   bool IsThisReturn = false;
2995   MachineFunction &MF = DAG.getMachineFunction();
2996 
2997   if (Callee.isUndef() || isNullConstant(Callee)) {
2998     if (!CLI.IsTailCall) {
2999       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3000         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3001     }
3002 
3003     return Chain;
3004   }
3005 
3006   if (IsVarArg) {
3007     return lowerUnhandledCall(CLI, InVals,
3008                               "unsupported call to variadic function ");
3009   }
3010 
3011   if (!CLI.CB)
3012     report_fatal_error("unsupported libcall legalization");
3013 
3014   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3015     return lowerUnhandledCall(CLI, InVals,
3016                               "unsupported required tail call to function ");
3017   }
3018 
3019   if (AMDGPU::isShader(CallConv)) {
3020     // Note the issue is with the CC of the called function, not of the call
3021     // itself.
3022     return lowerUnhandledCall(CLI, InVals,
3023                               "unsupported call to a shader function ");
3024   }
3025 
3026   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3027       CallConv != CallingConv::AMDGPU_Gfx) {
3028     // Only allow calls with specific calling conventions.
3029     return lowerUnhandledCall(CLI, InVals,
3030                               "unsupported calling convention for call from "
3031                               "graphics shader of function ");
3032   }
3033 
3034   if (IsTailCall) {
3035     IsTailCall = isEligibleForTailCallOptimization(
3036       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3037     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3038       report_fatal_error("failed to perform tail call elimination on a call "
3039                          "site marked musttail");
3040     }
3041 
3042     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3043 
3044     // A sibling call is one where we're under the usual C ABI and not planning
3045     // to change that but can still do a tail call:
3046     if (!TailCallOpt && IsTailCall)
3047       IsSibCall = true;
3048 
3049     if (IsTailCall)
3050       ++NumTailCalls;
3051   }
3052 
3053   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3054   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3055   SmallVector<SDValue, 8> MemOpChains;
3056 
3057   // Analyze operands of the call, assigning locations to each operand.
3058   SmallVector<CCValAssign, 16> ArgLocs;
3059   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3060   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3061 
3062   if (CallConv != CallingConv::AMDGPU_Gfx) {
3063     // With a fixed ABI, allocate fixed registers before user arguments.
3064     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3065   }
3066 
3067   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3068 
3069   // Get a count of how many bytes are to be pushed on the stack.
3070   unsigned NumBytes = CCInfo.getNextStackOffset();
3071 
3072   if (IsSibCall) {
3073     // Since we're not changing the ABI to make this a tail call, the memory
3074     // operands are already available in the caller's incoming argument space.
3075     NumBytes = 0;
3076   }
3077 
3078   // FPDiff is the byte offset of the call's argument area from the callee's.
3079   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3080   // by this amount for a tail call. In a sibling call it must be 0 because the
3081   // caller will deallocate the entire stack and the callee still expects its
3082   // arguments to begin at SP+0. Completely unused for non-tail calls.
3083   int32_t FPDiff = 0;
3084   MachineFrameInfo &MFI = MF.getFrameInfo();
3085 
3086   // Adjust the stack pointer for the new arguments...
3087   // These operations are automatically eliminated by the prolog/epilog pass
3088   if (!IsSibCall) {
3089     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3090 
3091     if (!Subtarget->enableFlatScratch()) {
3092       SmallVector<SDValue, 4> CopyFromChains;
3093 
3094       // In the HSA case, this should be an identity copy.
3095       SDValue ScratchRSrcReg
3096         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3097       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3098       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3099       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3100     }
3101   }
3102 
3103   MVT PtrVT = MVT::i32;
3104 
3105   // Walk the register/memloc assignments, inserting copies/loads.
3106   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3107     CCValAssign &VA = ArgLocs[i];
3108     SDValue Arg = OutVals[i];
3109 
3110     // Promote the value if needed.
3111     switch (VA.getLocInfo()) {
3112     case CCValAssign::Full:
3113       break;
3114     case CCValAssign::BCvt:
3115       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3116       break;
3117     case CCValAssign::ZExt:
3118       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3119       break;
3120     case CCValAssign::SExt:
3121       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3122       break;
3123     case CCValAssign::AExt:
3124       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3125       break;
3126     case CCValAssign::FPExt:
3127       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3128       break;
3129     default:
3130       llvm_unreachable("Unknown loc info!");
3131     }
3132 
3133     if (VA.isRegLoc()) {
3134       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3135     } else {
3136       assert(VA.isMemLoc());
3137 
3138       SDValue DstAddr;
3139       MachinePointerInfo DstInfo;
3140 
3141       unsigned LocMemOffset = VA.getLocMemOffset();
3142       int32_t Offset = LocMemOffset;
3143 
3144       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3145       MaybeAlign Alignment;
3146 
3147       if (IsTailCall) {
3148         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3149         unsigned OpSize = Flags.isByVal() ?
3150           Flags.getByValSize() : VA.getValVT().getStoreSize();
3151 
3152         // FIXME: We can have better than the minimum byval required alignment.
3153         Alignment =
3154             Flags.isByVal()
3155                 ? Flags.getNonZeroByValAlign()
3156                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3157 
3158         Offset = Offset + FPDiff;
3159         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3160 
3161         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3162         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3163 
3164         // Make sure any stack arguments overlapping with where we're storing
3165         // are loaded before this eventual operation. Otherwise they'll be
3166         // clobbered.
3167 
3168         // FIXME: Why is this really necessary? This seems to just result in a
3169         // lot of code to copy the stack and write them back to the same
3170         // locations, which are supposed to be immutable?
3171         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3172       } else {
3173         // Stores to the argument stack area are relative to the stack pointer.
3174         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3175                                         MVT::i32);
3176         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3177         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3178         Alignment =
3179             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3180       }
3181 
3182       if (Outs[i].Flags.isByVal()) {
3183         SDValue SizeNode =
3184             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3185         SDValue Cpy =
3186             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3187                           Outs[i].Flags.getNonZeroByValAlign(),
3188                           /*isVol = */ false, /*AlwaysInline = */ true,
3189                           /*isTailCall = */ false, DstInfo,
3190                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3191 
3192         MemOpChains.push_back(Cpy);
3193       } else {
3194         SDValue Store =
3195             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3196         MemOpChains.push_back(Store);
3197       }
3198     }
3199   }
3200 
3201   if (!MemOpChains.empty())
3202     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3203 
3204   // Build a sequence of copy-to-reg nodes chained together with token chain
3205   // and flag operands which copy the outgoing args into the appropriate regs.
3206   SDValue InFlag;
3207   for (auto &RegToPass : RegsToPass) {
3208     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3209                              RegToPass.second, InFlag);
3210     InFlag = Chain.getValue(1);
3211   }
3212 
3213 
3214   // We don't usually want to end the call-sequence here because we would tidy
3215   // the frame up *after* the call, however in the ABI-changing tail-call case
3216   // we've carefully laid out the parameters so that when sp is reset they'll be
3217   // in the correct location.
3218   if (IsTailCall && !IsSibCall) {
3219     Chain = DAG.getCALLSEQ_END(Chain,
3220                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3221                                DAG.getTargetConstant(0, DL, MVT::i32),
3222                                InFlag, DL);
3223     InFlag = Chain.getValue(1);
3224   }
3225 
3226   std::vector<SDValue> Ops;
3227   Ops.push_back(Chain);
3228   Ops.push_back(Callee);
3229   // Add a redundant copy of the callee global which will not be legalized, as
3230   // we need direct access to the callee later.
3231   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3232     const GlobalValue *GV = GSD->getGlobal();
3233     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3234   } else {
3235     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3236   }
3237 
3238   if (IsTailCall) {
3239     // Each tail call may have to adjust the stack by a different amount, so
3240     // this information must travel along with the operation for eventual
3241     // consumption by emitEpilogue.
3242     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3243   }
3244 
3245   // Add argument registers to the end of the list so that they are known live
3246   // into the call.
3247   for (auto &RegToPass : RegsToPass) {
3248     Ops.push_back(DAG.getRegister(RegToPass.first,
3249                                   RegToPass.second.getValueType()));
3250   }
3251 
3252   // Add a register mask operand representing the call-preserved registers.
3253 
3254   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3255   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3256   assert(Mask && "Missing call preserved mask for calling convention");
3257   Ops.push_back(DAG.getRegisterMask(Mask));
3258 
3259   if (InFlag.getNode())
3260     Ops.push_back(InFlag);
3261 
3262   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3263 
3264   // If we're doing a tall call, use a TC_RETURN here rather than an
3265   // actual call instruction.
3266   if (IsTailCall) {
3267     MFI.setHasTailCall();
3268     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3269   }
3270 
3271   // Returns a chain and a flag for retval copy to use.
3272   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3273   Chain = Call.getValue(0);
3274   InFlag = Call.getValue(1);
3275 
3276   uint64_t CalleePopBytes = NumBytes;
3277   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3278                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3279                              InFlag, DL);
3280   if (!Ins.empty())
3281     InFlag = Chain.getValue(1);
3282 
3283   // Handle result values, copying them out of physregs into vregs that we
3284   // return.
3285   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3286                          InVals, IsThisReturn,
3287                          IsThisReturn ? OutVals[0] : SDValue());
3288 }
3289 
3290 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3291 // except for applying the wave size scale to the increment amount.
3292 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3293     SDValue Op, SelectionDAG &DAG) const {
3294   const MachineFunction &MF = DAG.getMachineFunction();
3295   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3296 
3297   SDLoc dl(Op);
3298   EVT VT = Op.getValueType();
3299   SDValue Tmp1 = Op;
3300   SDValue Tmp2 = Op.getValue(1);
3301   SDValue Tmp3 = Op.getOperand(2);
3302   SDValue Chain = Tmp1.getOperand(0);
3303 
3304   Register SPReg = Info->getStackPtrOffsetReg();
3305 
3306   // Chain the dynamic stack allocation so that it doesn't modify the stack
3307   // pointer when other instructions are using the stack.
3308   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3309 
3310   SDValue Size  = Tmp2.getOperand(1);
3311   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3312   Chain = SP.getValue(1);
3313   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3314   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3315   const TargetFrameLowering *TFL = ST.getFrameLowering();
3316   unsigned Opc =
3317     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3318     ISD::ADD : ISD::SUB;
3319 
3320   SDValue ScaledSize = DAG.getNode(
3321       ISD::SHL, dl, VT, Size,
3322       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3323 
3324   Align StackAlign = TFL->getStackAlign();
3325   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3326   if (Alignment && *Alignment > StackAlign) {
3327     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3328                        DAG.getConstant(-(uint64_t)Alignment->value()
3329                                            << ST.getWavefrontSizeLog2(),
3330                                        dl, VT));
3331   }
3332 
3333   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3334   Tmp2 = DAG.getCALLSEQ_END(
3335       Chain, DAG.getIntPtrConstant(0, dl, true),
3336       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3337 
3338   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3339 }
3340 
3341 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3342                                                   SelectionDAG &DAG) const {
3343   // We only handle constant sizes here to allow non-entry block, static sized
3344   // allocas. A truly dynamic value is more difficult to support because we
3345   // don't know if the size value is uniform or not. If the size isn't uniform,
3346   // we would need to do a wave reduction to get the maximum size to know how
3347   // much to increment the uniform stack pointer.
3348   SDValue Size = Op.getOperand(1);
3349   if (isa<ConstantSDNode>(Size))
3350       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3351 
3352   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3353 }
3354 
3355 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3356                                              const MachineFunction &MF) const {
3357   Register Reg = StringSwitch<Register>(RegName)
3358     .Case("m0", AMDGPU::M0)
3359     .Case("exec", AMDGPU::EXEC)
3360     .Case("exec_lo", AMDGPU::EXEC_LO)
3361     .Case("exec_hi", AMDGPU::EXEC_HI)
3362     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3363     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3364     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3365     .Default(Register());
3366 
3367   if (Reg == AMDGPU::NoRegister) {
3368     report_fatal_error(Twine("invalid register name \""
3369                              + StringRef(RegName)  + "\"."));
3370 
3371   }
3372 
3373   if (!Subtarget->hasFlatScrRegister() &&
3374        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3375     report_fatal_error(Twine("invalid register \""
3376                              + StringRef(RegName)  + "\" for subtarget."));
3377   }
3378 
3379   switch (Reg) {
3380   case AMDGPU::M0:
3381   case AMDGPU::EXEC_LO:
3382   case AMDGPU::EXEC_HI:
3383   case AMDGPU::FLAT_SCR_LO:
3384   case AMDGPU::FLAT_SCR_HI:
3385     if (VT.getSizeInBits() == 32)
3386       return Reg;
3387     break;
3388   case AMDGPU::EXEC:
3389   case AMDGPU::FLAT_SCR:
3390     if (VT.getSizeInBits() == 64)
3391       return Reg;
3392     break;
3393   default:
3394     llvm_unreachable("missing register type checking");
3395   }
3396 
3397   report_fatal_error(Twine("invalid type for register \""
3398                            + StringRef(RegName) + "\"."));
3399 }
3400 
3401 // If kill is not the last instruction, split the block so kill is always a
3402 // proper terminator.
3403 MachineBasicBlock *
3404 SITargetLowering::splitKillBlock(MachineInstr &MI,
3405                                  MachineBasicBlock *BB) const {
3406   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3407   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3408   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3409   return SplitBB;
3410 }
3411 
3412 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3413 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3414 // be the first instruction in the remainder block.
3415 //
3416 /// \returns { LoopBody, Remainder }
3417 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3418 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3419   MachineFunction *MF = MBB.getParent();
3420   MachineBasicBlock::iterator I(&MI);
3421 
3422   // To insert the loop we need to split the block. Move everything after this
3423   // point to a new block, and insert a new empty block between the two.
3424   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3425   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3426   MachineFunction::iterator MBBI(MBB);
3427   ++MBBI;
3428 
3429   MF->insert(MBBI, LoopBB);
3430   MF->insert(MBBI, RemainderBB);
3431 
3432   LoopBB->addSuccessor(LoopBB);
3433   LoopBB->addSuccessor(RemainderBB);
3434 
3435   // Move the rest of the block into a new block.
3436   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3437 
3438   if (InstInLoop) {
3439     auto Next = std::next(I);
3440 
3441     // Move instruction to loop body.
3442     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3443 
3444     // Move the rest of the block.
3445     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3446   } else {
3447     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3448   }
3449 
3450   MBB.addSuccessor(LoopBB);
3451 
3452   return std::make_pair(LoopBB, RemainderBB);
3453 }
3454 
3455 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3456 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3457   MachineBasicBlock *MBB = MI.getParent();
3458   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3459   auto I = MI.getIterator();
3460   auto E = std::next(I);
3461 
3462   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3463     .addImm(0);
3464 
3465   MIBundleBuilder Bundler(*MBB, I, E);
3466   finalizeBundle(*MBB, Bundler.begin());
3467 }
3468 
3469 MachineBasicBlock *
3470 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3471                                          MachineBasicBlock *BB) const {
3472   const DebugLoc &DL = MI.getDebugLoc();
3473 
3474   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3475 
3476   MachineBasicBlock *LoopBB;
3477   MachineBasicBlock *RemainderBB;
3478   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3479 
3480   // Apparently kill flags are only valid if the def is in the same block?
3481   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3482     Src->setIsKill(false);
3483 
3484   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3485 
3486   MachineBasicBlock::iterator I = LoopBB->end();
3487 
3488   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3489     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3490 
3491   // Clear TRAP_STS.MEM_VIOL
3492   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3493     .addImm(0)
3494     .addImm(EncodedReg);
3495 
3496   bundleInstWithWaitcnt(MI);
3497 
3498   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3499 
3500   // Load and check TRAP_STS.MEM_VIOL
3501   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3502     .addImm(EncodedReg);
3503 
3504   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3505   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3506     .addReg(Reg, RegState::Kill)
3507     .addImm(0);
3508   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3509     .addMBB(LoopBB);
3510 
3511   return RemainderBB;
3512 }
3513 
3514 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3515 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3516 // will only do one iteration. In the worst case, this will loop 64 times.
3517 //
3518 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3519 static MachineBasicBlock::iterator
3520 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3521                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3522                        const DebugLoc &DL, const MachineOperand &Idx,
3523                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3524                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3525                        Register &SGPRIdxReg) {
3526 
3527   MachineFunction *MF = OrigBB.getParent();
3528   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3529   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3530   MachineBasicBlock::iterator I = LoopBB.begin();
3531 
3532   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3533   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3534   Register NewExec = MRI.createVirtualRegister(BoolRC);
3535   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3536   Register CondReg = MRI.createVirtualRegister(BoolRC);
3537 
3538   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3539     .addReg(InitReg)
3540     .addMBB(&OrigBB)
3541     .addReg(ResultReg)
3542     .addMBB(&LoopBB);
3543 
3544   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3545     .addReg(InitSaveExecReg)
3546     .addMBB(&OrigBB)
3547     .addReg(NewExec)
3548     .addMBB(&LoopBB);
3549 
3550   // Read the next variant <- also loop target.
3551   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3552       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3553 
3554   // Compare the just read M0 value to all possible Idx values.
3555   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3556       .addReg(CurrentIdxReg)
3557       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3558 
3559   // Update EXEC, save the original EXEC value to VCC.
3560   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3561                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3562           NewExec)
3563     .addReg(CondReg, RegState::Kill);
3564 
3565   MRI.setSimpleHint(NewExec, CondReg);
3566 
3567   if (UseGPRIdxMode) {
3568     if (Offset == 0) {
3569       SGPRIdxReg = CurrentIdxReg;
3570     } else {
3571       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3572       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3573           .addReg(CurrentIdxReg, RegState::Kill)
3574           .addImm(Offset);
3575     }
3576   } else {
3577     // Move index from VCC into M0
3578     if (Offset == 0) {
3579       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3580         .addReg(CurrentIdxReg, RegState::Kill);
3581     } else {
3582       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3583         .addReg(CurrentIdxReg, RegState::Kill)
3584         .addImm(Offset);
3585     }
3586   }
3587 
3588   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3589   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3590   MachineInstr *InsertPt =
3591     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3592                                                   : AMDGPU::S_XOR_B64_term), Exec)
3593       .addReg(Exec)
3594       .addReg(NewExec);
3595 
3596   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3597   // s_cbranch_scc0?
3598 
3599   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3600   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3601     .addMBB(&LoopBB);
3602 
3603   return InsertPt->getIterator();
3604 }
3605 
3606 // This has slightly sub-optimal regalloc when the source vector is killed by
3607 // the read. The register allocator does not understand that the kill is
3608 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3609 // subregister from it, using 1 more VGPR than necessary. This was saved when
3610 // this was expanded after register allocation.
3611 static MachineBasicBlock::iterator
3612 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3613                unsigned InitResultReg, unsigned PhiReg, int Offset,
3614                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3615   MachineFunction *MF = MBB.getParent();
3616   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3617   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3618   MachineRegisterInfo &MRI = MF->getRegInfo();
3619   const DebugLoc &DL = MI.getDebugLoc();
3620   MachineBasicBlock::iterator I(&MI);
3621 
3622   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3623   Register DstReg = MI.getOperand(0).getReg();
3624   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3625   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3626   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3627   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3628 
3629   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3630 
3631   // Save the EXEC mask
3632   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3633     .addReg(Exec);
3634 
3635   MachineBasicBlock *LoopBB;
3636   MachineBasicBlock *RemainderBB;
3637   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3638 
3639   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3640 
3641   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3642                                       InitResultReg, DstReg, PhiReg, TmpExec,
3643                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3644 
3645   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3646   MachineFunction::iterator MBBI(LoopBB);
3647   ++MBBI;
3648   MF->insert(MBBI, LandingPad);
3649   LoopBB->removeSuccessor(RemainderBB);
3650   LandingPad->addSuccessor(RemainderBB);
3651   LoopBB->addSuccessor(LandingPad);
3652   MachineBasicBlock::iterator First = LandingPad->begin();
3653   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3654     .addReg(SaveExec);
3655 
3656   return InsPt;
3657 }
3658 
3659 // Returns subreg index, offset
3660 static std::pair<unsigned, int>
3661 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3662                             const TargetRegisterClass *SuperRC,
3663                             unsigned VecReg,
3664                             int Offset) {
3665   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3666 
3667   // Skip out of bounds offsets, or else we would end up using an undefined
3668   // register.
3669   if (Offset >= NumElts || Offset < 0)
3670     return std::make_pair(AMDGPU::sub0, Offset);
3671 
3672   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3673 }
3674 
3675 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3676                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3677                                  int Offset) {
3678   MachineBasicBlock *MBB = MI.getParent();
3679   const DebugLoc &DL = MI.getDebugLoc();
3680   MachineBasicBlock::iterator I(&MI);
3681 
3682   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3683 
3684   assert(Idx->getReg() != AMDGPU::NoRegister);
3685 
3686   if (Offset == 0) {
3687     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3688   } else {
3689     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3690         .add(*Idx)
3691         .addImm(Offset);
3692   }
3693 }
3694 
3695 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3696                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3697                                    int Offset) {
3698   MachineBasicBlock *MBB = MI.getParent();
3699   const DebugLoc &DL = MI.getDebugLoc();
3700   MachineBasicBlock::iterator I(&MI);
3701 
3702   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3703 
3704   if (Offset == 0)
3705     return Idx->getReg();
3706 
3707   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3708   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3709       .add(*Idx)
3710       .addImm(Offset);
3711   return Tmp;
3712 }
3713 
3714 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3715                                           MachineBasicBlock &MBB,
3716                                           const GCNSubtarget &ST) {
3717   const SIInstrInfo *TII = ST.getInstrInfo();
3718   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3719   MachineFunction *MF = MBB.getParent();
3720   MachineRegisterInfo &MRI = MF->getRegInfo();
3721 
3722   Register Dst = MI.getOperand(0).getReg();
3723   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3724   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3725   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3726 
3727   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3728   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3729 
3730   unsigned SubReg;
3731   std::tie(SubReg, Offset)
3732     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3733 
3734   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3735 
3736   // Check for a SGPR index.
3737   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3738     MachineBasicBlock::iterator I(&MI);
3739     const DebugLoc &DL = MI.getDebugLoc();
3740 
3741     if (UseGPRIdxMode) {
3742       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3743       // to avoid interfering with other uses, so probably requires a new
3744       // optimization pass.
3745       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3746 
3747       const MCInstrDesc &GPRIDXDesc =
3748           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3749       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3750           .addReg(SrcReg)
3751           .addReg(Idx)
3752           .addImm(SubReg);
3753     } else {
3754       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3755 
3756       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3757         .addReg(SrcReg, 0, SubReg)
3758         .addReg(SrcReg, RegState::Implicit);
3759     }
3760 
3761     MI.eraseFromParent();
3762 
3763     return &MBB;
3764   }
3765 
3766   // Control flow needs to be inserted if indexing with a VGPR.
3767   const DebugLoc &DL = MI.getDebugLoc();
3768   MachineBasicBlock::iterator I(&MI);
3769 
3770   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3771   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3772 
3773   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3774 
3775   Register SGPRIdxReg;
3776   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3777                               UseGPRIdxMode, SGPRIdxReg);
3778 
3779   MachineBasicBlock *LoopBB = InsPt->getParent();
3780 
3781   if (UseGPRIdxMode) {
3782     const MCInstrDesc &GPRIDXDesc =
3783         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3784 
3785     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3786         .addReg(SrcReg)
3787         .addReg(SGPRIdxReg)
3788         .addImm(SubReg);
3789   } else {
3790     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3791       .addReg(SrcReg, 0, SubReg)
3792       .addReg(SrcReg, RegState::Implicit);
3793   }
3794 
3795   MI.eraseFromParent();
3796 
3797   return LoopBB;
3798 }
3799 
3800 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3801                                           MachineBasicBlock &MBB,
3802                                           const GCNSubtarget &ST) {
3803   const SIInstrInfo *TII = ST.getInstrInfo();
3804   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3805   MachineFunction *MF = MBB.getParent();
3806   MachineRegisterInfo &MRI = MF->getRegInfo();
3807 
3808   Register Dst = MI.getOperand(0).getReg();
3809   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3810   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3811   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3812   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3813   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3814   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3815 
3816   // This can be an immediate, but will be folded later.
3817   assert(Val->getReg());
3818 
3819   unsigned SubReg;
3820   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3821                                                          SrcVec->getReg(),
3822                                                          Offset);
3823   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3824 
3825   if (Idx->getReg() == AMDGPU::NoRegister) {
3826     MachineBasicBlock::iterator I(&MI);
3827     const DebugLoc &DL = MI.getDebugLoc();
3828 
3829     assert(Offset == 0);
3830 
3831     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3832         .add(*SrcVec)
3833         .add(*Val)
3834         .addImm(SubReg);
3835 
3836     MI.eraseFromParent();
3837     return &MBB;
3838   }
3839 
3840   // Check for a SGPR index.
3841   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3842     MachineBasicBlock::iterator I(&MI);
3843     const DebugLoc &DL = MI.getDebugLoc();
3844 
3845     if (UseGPRIdxMode) {
3846       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3847 
3848       const MCInstrDesc &GPRIDXDesc =
3849           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3850       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3851           .addReg(SrcVec->getReg())
3852           .add(*Val)
3853           .addReg(Idx)
3854           .addImm(SubReg);
3855     } else {
3856       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3857 
3858       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3859           TRI.getRegSizeInBits(*VecRC), 32, false);
3860       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3861           .addReg(SrcVec->getReg())
3862           .add(*Val)
3863           .addImm(SubReg);
3864     }
3865     MI.eraseFromParent();
3866     return &MBB;
3867   }
3868 
3869   // Control flow needs to be inserted if indexing with a VGPR.
3870   if (Val->isReg())
3871     MRI.clearKillFlags(Val->getReg());
3872 
3873   const DebugLoc &DL = MI.getDebugLoc();
3874 
3875   Register PhiReg = MRI.createVirtualRegister(VecRC);
3876 
3877   Register SGPRIdxReg;
3878   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3879                               UseGPRIdxMode, SGPRIdxReg);
3880   MachineBasicBlock *LoopBB = InsPt->getParent();
3881 
3882   if (UseGPRIdxMode) {
3883     const MCInstrDesc &GPRIDXDesc =
3884         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3885 
3886     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3887         .addReg(PhiReg)
3888         .add(*Val)
3889         .addReg(SGPRIdxReg)
3890         .addImm(AMDGPU::sub0);
3891   } else {
3892     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3893         TRI.getRegSizeInBits(*VecRC), 32, false);
3894     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3895         .addReg(PhiReg)
3896         .add(*Val)
3897         .addImm(AMDGPU::sub0);
3898   }
3899 
3900   MI.eraseFromParent();
3901   return LoopBB;
3902 }
3903 
3904 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3905   MachineInstr &MI, MachineBasicBlock *BB) const {
3906 
3907   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3908   MachineFunction *MF = BB->getParent();
3909   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3910 
3911   switch (MI.getOpcode()) {
3912   case AMDGPU::S_UADDO_PSEUDO:
3913   case AMDGPU::S_USUBO_PSEUDO: {
3914     const DebugLoc &DL = MI.getDebugLoc();
3915     MachineOperand &Dest0 = MI.getOperand(0);
3916     MachineOperand &Dest1 = MI.getOperand(1);
3917     MachineOperand &Src0 = MI.getOperand(2);
3918     MachineOperand &Src1 = MI.getOperand(3);
3919 
3920     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3921                        ? AMDGPU::S_ADD_I32
3922                        : AMDGPU::S_SUB_I32;
3923     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3924 
3925     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3926         .addImm(1)
3927         .addImm(0);
3928 
3929     MI.eraseFromParent();
3930     return BB;
3931   }
3932   case AMDGPU::S_ADD_U64_PSEUDO:
3933   case AMDGPU::S_SUB_U64_PSEUDO: {
3934     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3935     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3936     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3937     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3938     const DebugLoc &DL = MI.getDebugLoc();
3939 
3940     MachineOperand &Dest = MI.getOperand(0);
3941     MachineOperand &Src0 = MI.getOperand(1);
3942     MachineOperand &Src1 = MI.getOperand(2);
3943 
3944     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3945     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3946 
3947     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3948         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3949     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3950         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3951 
3952     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3953         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3954     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3955         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3956 
3957     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3958 
3959     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3960     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3961     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3962     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3963     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3964         .addReg(DestSub0)
3965         .addImm(AMDGPU::sub0)
3966         .addReg(DestSub1)
3967         .addImm(AMDGPU::sub1);
3968     MI.eraseFromParent();
3969     return BB;
3970   }
3971   case AMDGPU::V_ADD_U64_PSEUDO:
3972   case AMDGPU::V_SUB_U64_PSEUDO: {
3973     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3974     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3975     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3976     const DebugLoc &DL = MI.getDebugLoc();
3977 
3978     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3979 
3980     MachineOperand &Dest = MI.getOperand(0);
3981     MachineOperand &Src0 = MI.getOperand(1);
3982     MachineOperand &Src1 = MI.getOperand(2);
3983 
3984     if (IsAdd && ST.hasLshlAddB64()) {
3985       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
3986                          Dest.getReg())
3987                      .add(Src0)
3988                      .addImm(0)
3989                      .add(Src1);
3990       TII->legalizeOperands(*Add);
3991       MI.eraseFromParent();
3992       return BB;
3993     }
3994 
3995     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3996 
3997     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3998     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3999 
4000     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4001     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4002 
4003     const TargetRegisterClass *Src0RC = Src0.isReg()
4004                                             ? MRI.getRegClass(Src0.getReg())
4005                                             : &AMDGPU::VReg_64RegClass;
4006     const TargetRegisterClass *Src1RC = Src1.isReg()
4007                                             ? MRI.getRegClass(Src1.getReg())
4008                                             : &AMDGPU::VReg_64RegClass;
4009 
4010     const TargetRegisterClass *Src0SubRC =
4011         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4012     const TargetRegisterClass *Src1SubRC =
4013         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4014 
4015     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4016         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4017     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4018         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4019 
4020     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4021         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4022     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4023         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4024 
4025     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4026     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4027                                .addReg(CarryReg, RegState::Define)
4028                                .add(SrcReg0Sub0)
4029                                .add(SrcReg1Sub0)
4030                                .addImm(0); // clamp bit
4031 
4032     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4033     MachineInstr *HiHalf =
4034         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4035             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4036             .add(SrcReg0Sub1)
4037             .add(SrcReg1Sub1)
4038             .addReg(CarryReg, RegState::Kill)
4039             .addImm(0); // clamp bit
4040 
4041     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4042         .addReg(DestSub0)
4043         .addImm(AMDGPU::sub0)
4044         .addReg(DestSub1)
4045         .addImm(AMDGPU::sub1);
4046     TII->legalizeOperands(*LoHalf);
4047     TII->legalizeOperands(*HiHalf);
4048     MI.eraseFromParent();
4049     return BB;
4050   }
4051   case AMDGPU::S_ADD_CO_PSEUDO:
4052   case AMDGPU::S_SUB_CO_PSEUDO: {
4053     // This pseudo has a chance to be selected
4054     // only from uniform add/subcarry node. All the VGPR operands
4055     // therefore assumed to be splat vectors.
4056     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4057     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4058     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4059     MachineBasicBlock::iterator MII = MI;
4060     const DebugLoc &DL = MI.getDebugLoc();
4061     MachineOperand &Dest = MI.getOperand(0);
4062     MachineOperand &CarryDest = MI.getOperand(1);
4063     MachineOperand &Src0 = MI.getOperand(2);
4064     MachineOperand &Src1 = MI.getOperand(3);
4065     MachineOperand &Src2 = MI.getOperand(4);
4066     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4067                        ? AMDGPU::S_ADDC_U32
4068                        : AMDGPU::S_SUBB_U32;
4069     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4070       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4071       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4072           .addReg(Src0.getReg());
4073       Src0.setReg(RegOp0);
4074     }
4075     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4076       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4077       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4078           .addReg(Src1.getReg());
4079       Src1.setReg(RegOp1);
4080     }
4081     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4082     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4083       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4084           .addReg(Src2.getReg());
4085       Src2.setReg(RegOp2);
4086     }
4087 
4088     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4089     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4090     assert(WaveSize == 64 || WaveSize == 32);
4091 
4092     if (WaveSize == 64) {
4093       if (ST.hasScalarCompareEq64()) {
4094         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4095             .addReg(Src2.getReg())
4096             .addImm(0);
4097       } else {
4098         const TargetRegisterClass *SubRC =
4099             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4100         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4101             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4102         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4103             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4104         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4105 
4106         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4107             .add(Src2Sub0)
4108             .add(Src2Sub1);
4109 
4110         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4111             .addReg(Src2_32, RegState::Kill)
4112             .addImm(0);
4113       }
4114     } else {
4115       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4116           .addReg(Src2.getReg())
4117           .addImm(0);
4118     }
4119 
4120     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4121 
4122     unsigned SelOpc =
4123         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4124 
4125     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4126         .addImm(-1)
4127         .addImm(0);
4128 
4129     MI.eraseFromParent();
4130     return BB;
4131   }
4132   case AMDGPU::SI_INIT_M0: {
4133     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4134             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4135         .add(MI.getOperand(0));
4136     MI.eraseFromParent();
4137     return BB;
4138   }
4139   case AMDGPU::GET_GROUPSTATICSIZE: {
4140     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4141            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4142     DebugLoc DL = MI.getDebugLoc();
4143     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4144         .add(MI.getOperand(0))
4145         .addImm(MFI->getLDSSize());
4146     MI.eraseFromParent();
4147     return BB;
4148   }
4149   case AMDGPU::SI_INDIRECT_SRC_V1:
4150   case AMDGPU::SI_INDIRECT_SRC_V2:
4151   case AMDGPU::SI_INDIRECT_SRC_V4:
4152   case AMDGPU::SI_INDIRECT_SRC_V8:
4153   case AMDGPU::SI_INDIRECT_SRC_V16:
4154   case AMDGPU::SI_INDIRECT_SRC_V32:
4155     return emitIndirectSrc(MI, *BB, *getSubtarget());
4156   case AMDGPU::SI_INDIRECT_DST_V1:
4157   case AMDGPU::SI_INDIRECT_DST_V2:
4158   case AMDGPU::SI_INDIRECT_DST_V4:
4159   case AMDGPU::SI_INDIRECT_DST_V8:
4160   case AMDGPU::SI_INDIRECT_DST_V16:
4161   case AMDGPU::SI_INDIRECT_DST_V32:
4162     return emitIndirectDst(MI, *BB, *getSubtarget());
4163   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4164   case AMDGPU::SI_KILL_I1_PSEUDO:
4165     return splitKillBlock(MI, BB);
4166   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4167     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4168     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4169     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4170 
4171     Register Dst = MI.getOperand(0).getReg();
4172     Register Src0 = MI.getOperand(1).getReg();
4173     Register Src1 = MI.getOperand(2).getReg();
4174     const DebugLoc &DL = MI.getDebugLoc();
4175     Register SrcCond = MI.getOperand(3).getReg();
4176 
4177     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4178     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4179     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4180     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4181 
4182     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4183       .addReg(SrcCond);
4184     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4185       .addImm(0)
4186       .addReg(Src0, 0, AMDGPU::sub0)
4187       .addImm(0)
4188       .addReg(Src1, 0, AMDGPU::sub0)
4189       .addReg(SrcCondCopy);
4190     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4191       .addImm(0)
4192       .addReg(Src0, 0, AMDGPU::sub1)
4193       .addImm(0)
4194       .addReg(Src1, 0, AMDGPU::sub1)
4195       .addReg(SrcCondCopy);
4196 
4197     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4198       .addReg(DstLo)
4199       .addImm(AMDGPU::sub0)
4200       .addReg(DstHi)
4201       .addImm(AMDGPU::sub1);
4202     MI.eraseFromParent();
4203     return BB;
4204   }
4205   case AMDGPU::SI_BR_UNDEF: {
4206     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4207     const DebugLoc &DL = MI.getDebugLoc();
4208     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4209                            .add(MI.getOperand(0));
4210     Br->getOperand(1).setIsUndef(true); // read undef SCC
4211     MI.eraseFromParent();
4212     return BB;
4213   }
4214   case AMDGPU::ADJCALLSTACKUP:
4215   case AMDGPU::ADJCALLSTACKDOWN: {
4216     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4217     MachineInstrBuilder MIB(*MF, &MI);
4218     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4219        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4220     return BB;
4221   }
4222   case AMDGPU::SI_CALL_ISEL: {
4223     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4224     const DebugLoc &DL = MI.getDebugLoc();
4225 
4226     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4227 
4228     MachineInstrBuilder MIB;
4229     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4230 
4231     for (const MachineOperand &MO : MI.operands())
4232       MIB.add(MO);
4233 
4234     MIB.cloneMemRefs(MI);
4235     MI.eraseFromParent();
4236     return BB;
4237   }
4238   case AMDGPU::V_ADD_CO_U32_e32:
4239   case AMDGPU::V_SUB_CO_U32_e32:
4240   case AMDGPU::V_SUBREV_CO_U32_e32: {
4241     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4242     const DebugLoc &DL = MI.getDebugLoc();
4243     unsigned Opc = MI.getOpcode();
4244 
4245     bool NeedClampOperand = false;
4246     if (TII->pseudoToMCOpcode(Opc) == -1) {
4247       Opc = AMDGPU::getVOPe64(Opc);
4248       NeedClampOperand = true;
4249     }
4250 
4251     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4252     if (TII->isVOP3(*I)) {
4253       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4254       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4255       I.addReg(TRI->getVCC(), RegState::Define);
4256     }
4257     I.add(MI.getOperand(1))
4258      .add(MI.getOperand(2));
4259     if (NeedClampOperand)
4260       I.addImm(0); // clamp bit for e64 encoding
4261 
4262     TII->legalizeOperands(*I);
4263 
4264     MI.eraseFromParent();
4265     return BB;
4266   }
4267   case AMDGPU::V_ADDC_U32_e32:
4268   case AMDGPU::V_SUBB_U32_e32:
4269   case AMDGPU::V_SUBBREV_U32_e32:
4270     // These instructions have an implicit use of vcc which counts towards the
4271     // constant bus limit.
4272     TII->legalizeOperands(MI);
4273     return BB;
4274   case AMDGPU::DS_GWS_INIT:
4275   case AMDGPU::DS_GWS_SEMA_BR:
4276   case AMDGPU::DS_GWS_BARRIER:
4277     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
4278     LLVM_FALLTHROUGH;
4279   case AMDGPU::DS_GWS_SEMA_V:
4280   case AMDGPU::DS_GWS_SEMA_P:
4281   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4282     // A s_waitcnt 0 is required to be the instruction immediately following.
4283     if (getSubtarget()->hasGWSAutoReplay()) {
4284       bundleInstWithWaitcnt(MI);
4285       return BB;
4286     }
4287 
4288     return emitGWSMemViolTestLoop(MI, BB);
4289   case AMDGPU::S_SETREG_B32: {
4290     // Try to optimize cases that only set the denormal mode or rounding mode.
4291     //
4292     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4293     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4294     // instead.
4295     //
4296     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4297     // allow you to have a no side effect instruction in the output of a
4298     // sideeffecting pattern.
4299     unsigned ID, Offset, Width;
4300     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4301     if (ID != AMDGPU::Hwreg::ID_MODE)
4302       return BB;
4303 
4304     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4305     const unsigned SetMask = WidthMask << Offset;
4306 
4307     if (getSubtarget()->hasDenormModeInst()) {
4308       unsigned SetDenormOp = 0;
4309       unsigned SetRoundOp = 0;
4310 
4311       // The dedicated instructions can only set the whole denorm or round mode
4312       // at once, not a subset of bits in either.
4313       if (SetMask ==
4314           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4315         // If this fully sets both the round and denorm mode, emit the two
4316         // dedicated instructions for these.
4317         SetRoundOp = AMDGPU::S_ROUND_MODE;
4318         SetDenormOp = AMDGPU::S_DENORM_MODE;
4319       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4320         SetRoundOp = AMDGPU::S_ROUND_MODE;
4321       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4322         SetDenormOp = AMDGPU::S_DENORM_MODE;
4323       }
4324 
4325       if (SetRoundOp || SetDenormOp) {
4326         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4327         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4328         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4329           unsigned ImmVal = Def->getOperand(1).getImm();
4330           if (SetRoundOp) {
4331             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4332                 .addImm(ImmVal & 0xf);
4333 
4334             // If we also have the denorm mode, get just the denorm mode bits.
4335             ImmVal >>= 4;
4336           }
4337 
4338           if (SetDenormOp) {
4339             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4340                 .addImm(ImmVal & 0xf);
4341           }
4342 
4343           MI.eraseFromParent();
4344           return BB;
4345         }
4346       }
4347     }
4348 
4349     // If only FP bits are touched, used the no side effects pseudo.
4350     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4351                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4352       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4353 
4354     return BB;
4355   }
4356   default:
4357     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4358   }
4359 }
4360 
4361 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4362   return isTypeLegal(VT.getScalarType());
4363 }
4364 
4365 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4366   // This currently forces unfolding various combinations of fsub into fma with
4367   // free fneg'd operands. As long as we have fast FMA (controlled by
4368   // isFMAFasterThanFMulAndFAdd), we should perform these.
4369 
4370   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4371   // most of these combines appear to be cycle neutral but save on instruction
4372   // count / code size.
4373   return true;
4374 }
4375 
4376 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4377 
4378 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4379                                          EVT VT) const {
4380   if (!VT.isVector()) {
4381     return MVT::i1;
4382   }
4383   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4384 }
4385 
4386 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4387   // TODO: Should i16 be used always if legal? For now it would force VALU
4388   // shifts.
4389   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4390 }
4391 
4392 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4393   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4394              ? Ty.changeElementSize(16)
4395              : Ty.changeElementSize(32);
4396 }
4397 
4398 // Answering this is somewhat tricky and depends on the specific device which
4399 // have different rates for fma or all f64 operations.
4400 //
4401 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4402 // regardless of which device (although the number of cycles differs between
4403 // devices), so it is always profitable for f64.
4404 //
4405 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4406 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4407 // which we can always do even without fused FP ops since it returns the same
4408 // result as the separate operations and since it is always full
4409 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4410 // however does not support denormals, so we do report fma as faster if we have
4411 // a fast fma device and require denormals.
4412 //
4413 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4414                                                   EVT VT) const {
4415   VT = VT.getScalarType();
4416 
4417   switch (VT.getSimpleVT().SimpleTy) {
4418   case MVT::f32: {
4419     // If mad is not available this depends only on if f32 fma is full rate.
4420     if (!Subtarget->hasMadMacF32Insts())
4421       return Subtarget->hasFastFMAF32();
4422 
4423     // Otherwise f32 mad is always full rate and returns the same result as
4424     // the separate operations so should be preferred over fma.
4425     // However does not support denormals.
4426     if (hasFP32Denormals(MF))
4427       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4428 
4429     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4430     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4431   }
4432   case MVT::f64:
4433     return true;
4434   case MVT::f16:
4435     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4436   default:
4437     break;
4438   }
4439 
4440   return false;
4441 }
4442 
4443 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4444                                                   LLT Ty) const {
4445   switch (Ty.getScalarSizeInBits()) {
4446   case 16:
4447     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4448   case 32:
4449     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4450   case 64:
4451     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4452   default:
4453     break;
4454   }
4455 
4456   return false;
4457 }
4458 
4459 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4460   if (!Ty.isScalar())
4461     return false;
4462 
4463   if (Ty.getScalarSizeInBits() == 16)
4464     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4465   if (Ty.getScalarSizeInBits() == 32)
4466     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4467 
4468   return false;
4469 }
4470 
4471 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4472                                    const SDNode *N) const {
4473   // TODO: Check future ftz flag
4474   // v_mad_f32/v_mac_f32 do not support denormals.
4475   EVT VT = N->getValueType(0);
4476   if (VT == MVT::f32)
4477     return Subtarget->hasMadMacF32Insts() &&
4478            !hasFP32Denormals(DAG.getMachineFunction());
4479   if (VT == MVT::f16) {
4480     return Subtarget->hasMadF16() &&
4481            !hasFP64FP16Denormals(DAG.getMachineFunction());
4482   }
4483 
4484   return false;
4485 }
4486 
4487 //===----------------------------------------------------------------------===//
4488 // Custom DAG Lowering Operations
4489 //===----------------------------------------------------------------------===//
4490 
4491 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4492 // wider vector type is legal.
4493 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4494                                              SelectionDAG &DAG) const {
4495   unsigned Opc = Op.getOpcode();
4496   EVT VT = Op.getValueType();
4497   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4498 
4499   SDValue Lo, Hi;
4500   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4501 
4502   SDLoc SL(Op);
4503   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4504                              Op->getFlags());
4505   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4506                              Op->getFlags());
4507 
4508   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4509 }
4510 
4511 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4512 // wider vector type is legal.
4513 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4514                                               SelectionDAG &DAG) const {
4515   unsigned Opc = Op.getOpcode();
4516   EVT VT = Op.getValueType();
4517   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4518          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4519          VT == MVT::v16f32 || VT == MVT::v32f32);
4520 
4521   SDValue Lo0, Hi0;
4522   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4523   SDValue Lo1, Hi1;
4524   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4525 
4526   SDLoc SL(Op);
4527 
4528   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4529                              Op->getFlags());
4530   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4531                              Op->getFlags());
4532 
4533   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4534 }
4535 
4536 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4537                                               SelectionDAG &DAG) const {
4538   unsigned Opc = Op.getOpcode();
4539   EVT VT = Op.getValueType();
4540   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4541          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4542          VT == MVT::v16f32 || VT == MVT::v32f32);
4543 
4544   SDValue Lo0, Hi0;
4545   SDValue Op0 = Op.getOperand(0);
4546   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4547                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4548                          : std::make_pair(Op0, Op0);
4549   SDValue Lo1, Hi1;
4550   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4551   SDValue Lo2, Hi2;
4552   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4553 
4554   SDLoc SL(Op);
4555   auto ResVT = DAG.GetSplitDestVTs(VT);
4556 
4557   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4558                              Op->getFlags());
4559   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4560                              Op->getFlags());
4561 
4562   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4563 }
4564 
4565 
4566 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4567   switch (Op.getOpcode()) {
4568   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4569   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4570   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4571   case ISD::LOAD: {
4572     SDValue Result = LowerLOAD(Op, DAG);
4573     assert((!Result.getNode() ||
4574             Result.getNode()->getNumValues() == 2) &&
4575            "Load should return a value and a chain");
4576     return Result;
4577   }
4578 
4579   case ISD::FSIN:
4580   case ISD::FCOS:
4581     return LowerTrig(Op, DAG);
4582   case ISD::SELECT: return LowerSELECT(Op, DAG);
4583   case ISD::FDIV: return LowerFDIV(Op, DAG);
4584   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4585   case ISD::STORE: return LowerSTORE(Op, DAG);
4586   case ISD::GlobalAddress: {
4587     MachineFunction &MF = DAG.getMachineFunction();
4588     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4589     return LowerGlobalAddress(MFI, Op, DAG);
4590   }
4591   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4592   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4593   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4594   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4595   case ISD::INSERT_SUBVECTOR:
4596     return lowerINSERT_SUBVECTOR(Op, DAG);
4597   case ISD::INSERT_VECTOR_ELT:
4598     return lowerINSERT_VECTOR_ELT(Op, DAG);
4599   case ISD::EXTRACT_VECTOR_ELT:
4600     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4601   case ISD::VECTOR_SHUFFLE:
4602     return lowerVECTOR_SHUFFLE(Op, DAG);
4603   case ISD::SCALAR_TO_VECTOR:
4604     return lowerSCALAR_TO_VECTOR(Op, DAG);
4605   case ISD::BUILD_VECTOR:
4606     return lowerBUILD_VECTOR(Op, DAG);
4607   case ISD::FP_ROUND:
4608     return lowerFP_ROUND(Op, DAG);
4609   case ISD::FPTRUNC_ROUND: {
4610     unsigned Opc;
4611     SDLoc DL(Op);
4612 
4613     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4614       return SDValue();
4615 
4616     // Get the rounding mode from the last operand
4617     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4618     if (RoundMode == (int)RoundingMode::TowardPositive)
4619       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4620     else if (RoundMode == (int)RoundingMode::TowardNegative)
4621       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4622     else
4623       return SDValue();
4624 
4625     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4626   }
4627   case ISD::TRAP:
4628     return lowerTRAP(Op, DAG);
4629   case ISD::DEBUGTRAP:
4630     return lowerDEBUGTRAP(Op, DAG);
4631   case ISD::FABS:
4632   case ISD::FNEG:
4633   case ISD::FCANONICALIZE:
4634   case ISD::BSWAP:
4635     return splitUnaryVectorOp(Op, DAG);
4636   case ISD::FMINNUM:
4637   case ISD::FMAXNUM:
4638     return lowerFMINNUM_FMAXNUM(Op, DAG);
4639   case ISD::FMA:
4640     return splitTernaryVectorOp(Op, DAG);
4641   case ISD::FP_TO_SINT:
4642   case ISD::FP_TO_UINT:
4643     return LowerFP_TO_INT(Op, DAG);
4644   case ISD::SHL:
4645   case ISD::SRA:
4646   case ISD::SRL:
4647   case ISD::ADD:
4648   case ISD::SUB:
4649   case ISD::MUL:
4650   case ISD::SMIN:
4651   case ISD::SMAX:
4652   case ISD::UMIN:
4653   case ISD::UMAX:
4654   case ISD::FADD:
4655   case ISD::FMUL:
4656   case ISD::FMINNUM_IEEE:
4657   case ISD::FMAXNUM_IEEE:
4658   case ISD::UADDSAT:
4659   case ISD::USUBSAT:
4660   case ISD::SADDSAT:
4661   case ISD::SSUBSAT:
4662     return splitBinaryVectorOp(Op, DAG);
4663   case ISD::SMULO:
4664   case ISD::UMULO:
4665     return lowerXMULO(Op, DAG);
4666   case ISD::SMUL_LOHI:
4667   case ISD::UMUL_LOHI:
4668     return lowerXMUL_LOHI(Op, DAG);
4669   case ISD::DYNAMIC_STACKALLOC:
4670     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4671   }
4672   return SDValue();
4673 }
4674 
4675 // Used for D16: Casts the result of an instruction into the right vector,
4676 // packs values if loads return unpacked values.
4677 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4678                                        const SDLoc &DL,
4679                                        SelectionDAG &DAG, bool Unpacked) {
4680   if (!LoadVT.isVector())
4681     return Result;
4682 
4683   // Cast back to the original packed type or to a larger type that is a
4684   // multiple of 32 bit for D16. Widening the return type is a required for
4685   // legalization.
4686   EVT FittingLoadVT = LoadVT;
4687   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4688     FittingLoadVT =
4689         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4690                          LoadVT.getVectorNumElements() + 1);
4691   }
4692 
4693   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4694     // Truncate to v2i16/v4i16.
4695     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4696 
4697     // Workaround legalizer not scalarizing truncate after vector op
4698     // legalization but not creating intermediate vector trunc.
4699     SmallVector<SDValue, 4> Elts;
4700     DAG.ExtractVectorElements(Result, Elts);
4701     for (SDValue &Elt : Elts)
4702       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4703 
4704     // Pad illegal v1i16/v3fi6 to v4i16
4705     if ((LoadVT.getVectorNumElements() % 2) == 1)
4706       Elts.push_back(DAG.getUNDEF(MVT::i16));
4707 
4708     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4709 
4710     // Bitcast to original type (v2f16/v4f16).
4711     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4712   }
4713 
4714   // Cast back to the original packed type.
4715   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4716 }
4717 
4718 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4719                                               MemSDNode *M,
4720                                               SelectionDAG &DAG,
4721                                               ArrayRef<SDValue> Ops,
4722                                               bool IsIntrinsic) const {
4723   SDLoc DL(M);
4724 
4725   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4726   EVT LoadVT = M->getValueType(0);
4727 
4728   EVT EquivLoadVT = LoadVT;
4729   if (LoadVT.isVector()) {
4730     if (Unpacked) {
4731       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4732                                      LoadVT.getVectorNumElements());
4733     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4734       // Widen v3f16 to legal type
4735       EquivLoadVT =
4736           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4737                            LoadVT.getVectorNumElements() + 1);
4738     }
4739   }
4740 
4741   // Change from v4f16/v2f16 to EquivLoadVT.
4742   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4743 
4744   SDValue Load
4745     = DAG.getMemIntrinsicNode(
4746       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4747       VTList, Ops, M->getMemoryVT(),
4748       M->getMemOperand());
4749 
4750   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4751 
4752   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4753 }
4754 
4755 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4756                                              SelectionDAG &DAG,
4757                                              ArrayRef<SDValue> Ops) const {
4758   SDLoc DL(M);
4759   EVT LoadVT = M->getValueType(0);
4760   EVT EltType = LoadVT.getScalarType();
4761   EVT IntVT = LoadVT.changeTypeToInteger();
4762 
4763   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4764 
4765   unsigned Opc =
4766       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4767 
4768   if (IsD16) {
4769     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4770   }
4771 
4772   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4773   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4774     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4775 
4776   if (isTypeLegal(LoadVT)) {
4777     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4778                                M->getMemOperand(), DAG);
4779   }
4780 
4781   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4782   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4783   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4784                                         M->getMemOperand(), DAG);
4785   return DAG.getMergeValues(
4786       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4787       DL);
4788 }
4789 
4790 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4791                                   SDNode *N, SelectionDAG &DAG) {
4792   EVT VT = N->getValueType(0);
4793   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4794   unsigned CondCode = CD->getZExtValue();
4795   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4796     return DAG.getUNDEF(VT);
4797 
4798   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4799 
4800   SDValue LHS = N->getOperand(1);
4801   SDValue RHS = N->getOperand(2);
4802 
4803   SDLoc DL(N);
4804 
4805   EVT CmpVT = LHS.getValueType();
4806   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4807     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4808       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4809     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4810     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4811   }
4812 
4813   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4814 
4815   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4816   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4817 
4818   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4819                               DAG.getCondCode(CCOpcode));
4820   if (VT.bitsEq(CCVT))
4821     return SetCC;
4822   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4823 }
4824 
4825 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4826                                   SDNode *N, SelectionDAG &DAG) {
4827   EVT VT = N->getValueType(0);
4828   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4829 
4830   unsigned CondCode = CD->getZExtValue();
4831   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4832     return DAG.getUNDEF(VT);
4833 
4834   SDValue Src0 = N->getOperand(1);
4835   SDValue Src1 = N->getOperand(2);
4836   EVT CmpVT = Src0.getValueType();
4837   SDLoc SL(N);
4838 
4839   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4840     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4841     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4842   }
4843 
4844   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4845   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4846   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4847   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4848   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4849                               Src1, DAG.getCondCode(CCOpcode));
4850   if (VT.bitsEq(CCVT))
4851     return SetCC;
4852   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4853 }
4854 
4855 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4856                                     SelectionDAG &DAG) {
4857   EVT VT = N->getValueType(0);
4858   SDValue Src = N->getOperand(1);
4859   SDLoc SL(N);
4860 
4861   if (Src.getOpcode() == ISD::SETCC) {
4862     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4863     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4864                        Src.getOperand(1), Src.getOperand(2));
4865   }
4866   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4867     // (ballot 0) -> 0
4868     if (Arg->isZero())
4869       return DAG.getConstant(0, SL, VT);
4870 
4871     // (ballot 1) -> EXEC/EXEC_LO
4872     if (Arg->isOne()) {
4873       Register Exec;
4874       if (VT.getScalarSizeInBits() == 32)
4875         Exec = AMDGPU::EXEC_LO;
4876       else if (VT.getScalarSizeInBits() == 64)
4877         Exec = AMDGPU::EXEC;
4878       else
4879         return SDValue();
4880 
4881       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4882     }
4883   }
4884 
4885   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4886   // ISD::SETNE)
4887   return DAG.getNode(
4888       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4889       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4890 }
4891 
4892 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4893                                           SmallVectorImpl<SDValue> &Results,
4894                                           SelectionDAG &DAG) const {
4895   switch (N->getOpcode()) {
4896   case ISD::INSERT_VECTOR_ELT: {
4897     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4898       Results.push_back(Res);
4899     return;
4900   }
4901   case ISD::EXTRACT_VECTOR_ELT: {
4902     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4903       Results.push_back(Res);
4904     return;
4905   }
4906   case ISD::INTRINSIC_WO_CHAIN: {
4907     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4908     switch (IID) {
4909     case Intrinsic::amdgcn_cvt_pkrtz: {
4910       SDValue Src0 = N->getOperand(1);
4911       SDValue Src1 = N->getOperand(2);
4912       SDLoc SL(N);
4913       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4914                                 Src0, Src1);
4915       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4916       return;
4917     }
4918     case Intrinsic::amdgcn_cvt_pknorm_i16:
4919     case Intrinsic::amdgcn_cvt_pknorm_u16:
4920     case Intrinsic::amdgcn_cvt_pk_i16:
4921     case Intrinsic::amdgcn_cvt_pk_u16: {
4922       SDValue Src0 = N->getOperand(1);
4923       SDValue Src1 = N->getOperand(2);
4924       SDLoc SL(N);
4925       unsigned Opcode;
4926 
4927       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4928         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4929       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4930         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4931       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4932         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4933       else
4934         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4935 
4936       EVT VT = N->getValueType(0);
4937       if (isTypeLegal(VT))
4938         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4939       else {
4940         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4941         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4942       }
4943       return;
4944     }
4945     }
4946     break;
4947   }
4948   case ISD::INTRINSIC_W_CHAIN: {
4949     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4950       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4951         // FIXME: Hacky
4952         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4953           Results.push_back(Res.getOperand(I));
4954         }
4955       } else {
4956         Results.push_back(Res);
4957         Results.push_back(Res.getValue(1));
4958       }
4959       return;
4960     }
4961 
4962     break;
4963   }
4964   case ISD::SELECT: {
4965     SDLoc SL(N);
4966     EVT VT = N->getValueType(0);
4967     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4968     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4969     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4970 
4971     EVT SelectVT = NewVT;
4972     if (NewVT.bitsLT(MVT::i32)) {
4973       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4974       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4975       SelectVT = MVT::i32;
4976     }
4977 
4978     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4979                                     N->getOperand(0), LHS, RHS);
4980 
4981     if (NewVT != SelectVT)
4982       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4983     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4984     return;
4985   }
4986   case ISD::FNEG: {
4987     if (N->getValueType(0) != MVT::v2f16)
4988       break;
4989 
4990     SDLoc SL(N);
4991     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4992 
4993     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4994                              BC,
4995                              DAG.getConstant(0x80008000, SL, MVT::i32));
4996     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4997     return;
4998   }
4999   case ISD::FABS: {
5000     if (N->getValueType(0) != MVT::v2f16)
5001       break;
5002 
5003     SDLoc SL(N);
5004     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5005 
5006     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5007                              BC,
5008                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5009     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5010     return;
5011   }
5012   default:
5013     break;
5014   }
5015 }
5016 
5017 /// Helper function for LowerBRCOND
5018 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5019 
5020   SDNode *Parent = Value.getNode();
5021   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5022        I != E; ++I) {
5023 
5024     if (I.getUse().get() != Value)
5025       continue;
5026 
5027     if (I->getOpcode() == Opcode)
5028       return *I;
5029   }
5030   return nullptr;
5031 }
5032 
5033 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5034   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5035     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5036     case Intrinsic::amdgcn_if:
5037       return AMDGPUISD::IF;
5038     case Intrinsic::amdgcn_else:
5039       return AMDGPUISD::ELSE;
5040     case Intrinsic::amdgcn_loop:
5041       return AMDGPUISD::LOOP;
5042     case Intrinsic::amdgcn_end_cf:
5043       llvm_unreachable("should not occur");
5044     default:
5045       return 0;
5046     }
5047   }
5048 
5049   // break, if_break, else_break are all only used as inputs to loop, not
5050   // directly as branch conditions.
5051   return 0;
5052 }
5053 
5054 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5055   const Triple &TT = getTargetMachine().getTargetTriple();
5056   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5057           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5058          AMDGPU::shouldEmitConstantsToTextSection(TT);
5059 }
5060 
5061 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5062   // FIXME: Either avoid relying on address space here or change the default
5063   // address space for functions to avoid the explicit check.
5064   return (GV->getValueType()->isFunctionTy() ||
5065           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5066          !shouldEmitFixup(GV) &&
5067          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5068 }
5069 
5070 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5071   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5072 }
5073 
5074 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5075   if (!GV->hasExternalLinkage())
5076     return true;
5077 
5078   const auto OS = getTargetMachine().getTargetTriple().getOS();
5079   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5080 }
5081 
5082 /// This transforms the control flow intrinsics to get the branch destination as
5083 /// last parameter, also switches branch target with BR if the need arise
5084 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5085                                       SelectionDAG &DAG) const {
5086   SDLoc DL(BRCOND);
5087 
5088   SDNode *Intr = BRCOND.getOperand(1).getNode();
5089   SDValue Target = BRCOND.getOperand(2);
5090   SDNode *BR = nullptr;
5091   SDNode *SetCC = nullptr;
5092 
5093   if (Intr->getOpcode() == ISD::SETCC) {
5094     // As long as we negate the condition everything is fine
5095     SetCC = Intr;
5096     Intr = SetCC->getOperand(0).getNode();
5097 
5098   } else {
5099     // Get the target from BR if we don't negate the condition
5100     BR = findUser(BRCOND, ISD::BR);
5101     assert(BR && "brcond missing unconditional branch user");
5102     Target = BR->getOperand(1);
5103   }
5104 
5105   unsigned CFNode = isCFIntrinsic(Intr);
5106   if (CFNode == 0) {
5107     // This is a uniform branch so we don't need to legalize.
5108     return BRCOND;
5109   }
5110 
5111   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5112                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5113 
5114   assert(!SetCC ||
5115         (SetCC->getConstantOperandVal(1) == 1 &&
5116          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5117                                                              ISD::SETNE));
5118 
5119   // operands of the new intrinsic call
5120   SmallVector<SDValue, 4> Ops;
5121   if (HaveChain)
5122     Ops.push_back(BRCOND.getOperand(0));
5123 
5124   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5125   Ops.push_back(Target);
5126 
5127   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5128 
5129   // build the new intrinsic call
5130   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5131 
5132   if (!HaveChain) {
5133     SDValue Ops[] =  {
5134       SDValue(Result, 0),
5135       BRCOND.getOperand(0)
5136     };
5137 
5138     Result = DAG.getMergeValues(Ops, DL).getNode();
5139   }
5140 
5141   if (BR) {
5142     // Give the branch instruction our target
5143     SDValue Ops[] = {
5144       BR->getOperand(0),
5145       BRCOND.getOperand(2)
5146     };
5147     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5148     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5149   }
5150 
5151   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5152 
5153   // Copy the intrinsic results to registers
5154   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5155     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5156     if (!CopyToReg)
5157       continue;
5158 
5159     Chain = DAG.getCopyToReg(
5160       Chain, DL,
5161       CopyToReg->getOperand(1),
5162       SDValue(Result, i - 1),
5163       SDValue());
5164 
5165     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5166   }
5167 
5168   // Remove the old intrinsic from the chain
5169   DAG.ReplaceAllUsesOfValueWith(
5170     SDValue(Intr, Intr->getNumValues() - 1),
5171     Intr->getOperand(0));
5172 
5173   return Chain;
5174 }
5175 
5176 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5177                                           SelectionDAG &DAG) const {
5178   MVT VT = Op.getSimpleValueType();
5179   SDLoc DL(Op);
5180   // Checking the depth
5181   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5182     return DAG.getConstant(0, DL, VT);
5183 
5184   MachineFunction &MF = DAG.getMachineFunction();
5185   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5186   // Check for kernel and shader functions
5187   if (Info->isEntryFunction())
5188     return DAG.getConstant(0, DL, VT);
5189 
5190   MachineFrameInfo &MFI = MF.getFrameInfo();
5191   // There is a call to @llvm.returnaddress in this function
5192   MFI.setReturnAddressIsTaken(true);
5193 
5194   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5195   // Get the return address reg and mark it as an implicit live-in
5196   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5197 
5198   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5199 }
5200 
5201 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5202                                             SDValue Op,
5203                                             const SDLoc &DL,
5204                                             EVT VT) const {
5205   return Op.getValueType().bitsLE(VT) ?
5206       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5207     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5208                 DAG.getTargetConstant(0, DL, MVT::i32));
5209 }
5210 
5211 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5212   assert(Op.getValueType() == MVT::f16 &&
5213          "Do not know how to custom lower FP_ROUND for non-f16 type");
5214 
5215   SDValue Src = Op.getOperand(0);
5216   EVT SrcVT = Src.getValueType();
5217   if (SrcVT != MVT::f64)
5218     return Op;
5219 
5220   SDLoc DL(Op);
5221 
5222   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5223   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5224   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5225 }
5226 
5227 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5228                                                SelectionDAG &DAG) const {
5229   EVT VT = Op.getValueType();
5230   const MachineFunction &MF = DAG.getMachineFunction();
5231   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5232   bool IsIEEEMode = Info->getMode().IEEE;
5233 
5234   // FIXME: Assert during selection that this is only selected for
5235   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5236   // mode functions, but this happens to be OK since it's only done in cases
5237   // where there is known no sNaN.
5238   if (IsIEEEMode)
5239     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5240 
5241   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5242     return splitBinaryVectorOp(Op, DAG);
5243   return Op;
5244 }
5245 
5246 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5247   EVT VT = Op.getValueType();
5248   SDLoc SL(Op);
5249   SDValue LHS = Op.getOperand(0);
5250   SDValue RHS = Op.getOperand(1);
5251   bool isSigned = Op.getOpcode() == ISD::SMULO;
5252 
5253   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5254     const APInt &C = RHSC->getAPIntValue();
5255     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5256     if (C.isPowerOf2()) {
5257       // smulo(x, signed_min) is same as umulo(x, signed_min).
5258       bool UseArithShift = isSigned && !C.isMinSignedValue();
5259       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5260       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5261       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5262           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5263                       SL, VT, Result, ShiftAmt),
5264           LHS, ISD::SETNE);
5265       return DAG.getMergeValues({ Result, Overflow }, SL);
5266     }
5267   }
5268 
5269   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5270   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5271                             SL, VT, LHS, RHS);
5272 
5273   SDValue Sign = isSigned
5274     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5275                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5276     : DAG.getConstant(0, SL, VT);
5277   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5278 
5279   return DAG.getMergeValues({ Result, Overflow }, SL);
5280 }
5281 
5282 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5283   if (Op->isDivergent()) {
5284     // Select to V_MAD_[IU]64_[IU]32.
5285     return Op;
5286   }
5287   if (Subtarget->hasSMulHi()) {
5288     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5289     return SDValue();
5290   }
5291   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5292   // calculate the high part, so we might as well do the whole thing with
5293   // V_MAD_[IU]64_[IU]32.
5294   return Op;
5295 }
5296 
5297 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5298   if (!Subtarget->isTrapHandlerEnabled() ||
5299       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5300     return lowerTrapEndpgm(Op, DAG);
5301 
5302   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5303     switch (*HsaAbiVer) {
5304     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5305     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5306       return lowerTrapHsaQueuePtr(Op, DAG);
5307     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5308     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5309       return Subtarget->supportsGetDoorbellID() ?
5310           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5311     }
5312   }
5313 
5314   llvm_unreachable("Unknown trap handler");
5315 }
5316 
5317 SDValue SITargetLowering::lowerTrapEndpgm(
5318     SDValue Op, SelectionDAG &DAG) const {
5319   SDLoc SL(Op);
5320   SDValue Chain = Op.getOperand(0);
5321   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5322 }
5323 
5324 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5325     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5326   MachineFunction &MF = DAG.getMachineFunction();
5327   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5328   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5329   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5330   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5331                      MachineMemOperand::MODereferenceable |
5332                          MachineMemOperand::MOInvariant);
5333 }
5334 
5335 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5336     SDValue Op, SelectionDAG &DAG) const {
5337   SDLoc SL(Op);
5338   SDValue Chain = Op.getOperand(0);
5339 
5340   SDValue QueuePtr;
5341   // For code object version 5, QueuePtr is passed through implicit kernarg.
5342   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5343     QueuePtr =
5344         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5345   } else {
5346     MachineFunction &MF = DAG.getMachineFunction();
5347     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5348     Register UserSGPR = Info->getQueuePtrUserSGPR();
5349 
5350     if (UserSGPR == AMDGPU::NoRegister) {
5351       // We probably are in a function incorrectly marked with
5352       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5353       // trap, so just use a null pointer.
5354       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5355     } else {
5356       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5357                                       MVT::i64);
5358     }
5359   }
5360 
5361   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5362   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5363                                    QueuePtr, SDValue());
5364 
5365   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5366   SDValue Ops[] = {
5367     ToReg,
5368     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5369     SGPR01,
5370     ToReg.getValue(1)
5371   };
5372   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5373 }
5374 
5375 SDValue SITargetLowering::lowerTrapHsa(
5376     SDValue Op, SelectionDAG &DAG) const {
5377   SDLoc SL(Op);
5378   SDValue Chain = Op.getOperand(0);
5379 
5380   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5381   SDValue Ops[] = {
5382     Chain,
5383     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5384   };
5385   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5386 }
5387 
5388 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5389   SDLoc SL(Op);
5390   SDValue Chain = Op.getOperand(0);
5391   MachineFunction &MF = DAG.getMachineFunction();
5392 
5393   if (!Subtarget->isTrapHandlerEnabled() ||
5394       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5395     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5396                                      "debugtrap handler not supported",
5397                                      Op.getDebugLoc(),
5398                                      DS_Warning);
5399     LLVMContext &Ctx = MF.getFunction().getContext();
5400     Ctx.diagnose(NoTrap);
5401     return Chain;
5402   }
5403 
5404   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5405   SDValue Ops[] = {
5406     Chain,
5407     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5408   };
5409   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5410 }
5411 
5412 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5413                                              SelectionDAG &DAG) const {
5414   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5415   if (Subtarget->hasApertureRegs()) {
5416     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5417         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5418         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5419     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5420         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5421         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5422     unsigned Encoding =
5423         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5424         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5425         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5426 
5427     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5428     SDValue ApertureReg = SDValue(
5429         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5430     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5431     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5432   }
5433 
5434   // For code object version 5, private_base and shared_base are passed through
5435   // implicit kernargs.
5436   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5437     ImplicitParameter Param =
5438         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5439     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5440   }
5441 
5442   MachineFunction &MF = DAG.getMachineFunction();
5443   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5444   Register UserSGPR = Info->getQueuePtrUserSGPR();
5445   if (UserSGPR == AMDGPU::NoRegister) {
5446     // We probably are in a function incorrectly marked with
5447     // amdgpu-no-queue-ptr. This is undefined.
5448     return DAG.getUNDEF(MVT::i32);
5449   }
5450 
5451   SDValue QueuePtr = CreateLiveInRegister(
5452     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5453 
5454   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5455   // private_segment_aperture_base_hi.
5456   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5457 
5458   SDValue Ptr =
5459       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5460 
5461   // TODO: Use custom target PseudoSourceValue.
5462   // TODO: We should use the value from the IR intrinsic call, but it might not
5463   // be available and how do we get it?
5464   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5465   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5466                      commonAlignment(Align(64), StructOffset),
5467                      MachineMemOperand::MODereferenceable |
5468                          MachineMemOperand::MOInvariant);
5469 }
5470 
5471 /// Return true if the value is a known valid address, such that a null check is
5472 /// not necessary.
5473 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5474                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5475   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5476       isa<BasicBlockSDNode>(Val))
5477     return true;
5478 
5479   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5480     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5481 
5482   // TODO: Search through arithmetic, handle arguments and loads
5483   // marked nonnull.
5484   return false;
5485 }
5486 
5487 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5488                                              SelectionDAG &DAG) const {
5489   SDLoc SL(Op);
5490   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5491 
5492   SDValue Src = ASC->getOperand(0);
5493   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5494   unsigned SrcAS = ASC->getSrcAddressSpace();
5495 
5496   const AMDGPUTargetMachine &TM =
5497     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5498 
5499   // flat -> local/private
5500   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5501     unsigned DestAS = ASC->getDestAddressSpace();
5502 
5503     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5504         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5505       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5506 
5507       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5508         return Ptr;
5509 
5510       unsigned NullVal = TM.getNullPointerValue(DestAS);
5511       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5512       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5513 
5514       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5515                          SegmentNullPtr);
5516     }
5517   }
5518 
5519   // local/private -> flat
5520   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5521     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5522         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5523 
5524       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5525       SDValue CvtPtr =
5526           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5527       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5528 
5529       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5530         return CvtPtr;
5531 
5532       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5533       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5534 
5535       SDValue NonNull
5536         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5537 
5538       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5539                          FlatNullPtr);
5540     }
5541   }
5542 
5543   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5544       Op.getValueType() == MVT::i64) {
5545     const SIMachineFunctionInfo *Info =
5546         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5547     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5548     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5549     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5550   }
5551 
5552   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5553       Src.getValueType() == MVT::i64)
5554     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5555 
5556   // global <-> flat are no-ops and never emitted.
5557 
5558   const MachineFunction &MF = DAG.getMachineFunction();
5559   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5560     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5561   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5562 
5563   return DAG.getUNDEF(ASC->getValueType(0));
5564 }
5565 
5566 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5567 // the small vector and inserting them into the big vector. That is better than
5568 // the default expansion of doing it via a stack slot. Even though the use of
5569 // the stack slot would be optimized away afterwards, the stack slot itself
5570 // remains.
5571 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5572                                                 SelectionDAG &DAG) const {
5573   SDValue Vec = Op.getOperand(0);
5574   SDValue Ins = Op.getOperand(1);
5575   SDValue Idx = Op.getOperand(2);
5576   EVT VecVT = Vec.getValueType();
5577   EVT InsVT = Ins.getValueType();
5578   EVT EltVT = VecVT.getVectorElementType();
5579   unsigned InsNumElts = InsVT.getVectorNumElements();
5580   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5581   SDLoc SL(Op);
5582 
5583   for (unsigned I = 0; I != InsNumElts; ++I) {
5584     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5585                               DAG.getConstant(I, SL, MVT::i32));
5586     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5587                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5588   }
5589   return Vec;
5590 }
5591 
5592 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5593                                                  SelectionDAG &DAG) const {
5594   SDValue Vec = Op.getOperand(0);
5595   SDValue InsVal = Op.getOperand(1);
5596   SDValue Idx = Op.getOperand(2);
5597   EVT VecVT = Vec.getValueType();
5598   EVT EltVT = VecVT.getVectorElementType();
5599   unsigned VecSize = VecVT.getSizeInBits();
5600   unsigned EltSize = EltVT.getSizeInBits();
5601   SDLoc SL(Op);
5602 
5603   // Specially handle the case of v4i16 with static indexing.
5604   unsigned NumElts = VecVT.getVectorNumElements();
5605   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5606   if (NumElts == 4 && EltSize == 16 && KIdx) {
5607     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5608 
5609     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5610                                  DAG.getConstant(0, SL, MVT::i32));
5611     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5612                                  DAG.getConstant(1, SL, MVT::i32));
5613 
5614     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5615     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5616 
5617     unsigned Idx = KIdx->getZExtValue();
5618     bool InsertLo = Idx < 2;
5619     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5620       InsertLo ? LoVec : HiVec,
5621       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5622       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5623 
5624     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5625 
5626     SDValue Concat = InsertLo ?
5627       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5628       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5629 
5630     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5631   }
5632 
5633   // Static indexing does not lower to stack access, and hence there is no need
5634   // for special custom lowering to avoid stack access.
5635   if (isa<ConstantSDNode>(Idx))
5636     return SDValue();
5637 
5638   // Avoid stack access for dynamic indexing by custom lowering to
5639   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5640 
5641   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5642 
5643   MVT IntVT = MVT::getIntegerVT(VecSize);
5644 
5645   // Convert vector index to bit-index and get the required bit mask.
5646   assert(isPowerOf2_32(EltSize));
5647   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5648   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5649   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5650                             DAG.getConstant(0xffff, SL, IntVT),
5651                             ScaledIdx);
5652 
5653   // 1. Create a congruent vector with the target value in each element.
5654   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5655                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5656 
5657   // 2. Mask off all other indicies except the required index within (1).
5658   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5659 
5660   // 3. Mask off the required index within the target vector.
5661   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5662   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5663                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5664 
5665   // 4. Get (2) and (3) ORed into the target vector.
5666   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5667 
5668   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5669 }
5670 
5671 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5672                                                   SelectionDAG &DAG) const {
5673   SDLoc SL(Op);
5674 
5675   EVT ResultVT = Op.getValueType();
5676   SDValue Vec = Op.getOperand(0);
5677   SDValue Idx = Op.getOperand(1);
5678   EVT VecVT = Vec.getValueType();
5679   unsigned VecSize = VecVT.getSizeInBits();
5680   EVT EltVT = VecVT.getVectorElementType();
5681 
5682   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5683 
5684   // Make sure we do any optimizations that will make it easier to fold
5685   // source modifiers before obscuring it with bit operations.
5686 
5687   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5688   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5689     return Combined;
5690 
5691   if (VecSize == 128) {
5692     SDValue Lo, Hi;
5693     EVT LoVT, HiVT;
5694     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5695     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5696     Lo =
5697         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5698                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5699     Hi =
5700         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5701                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5702     EVT IdxVT = Idx.getValueType();
5703     unsigned NElem = VecVT.getVectorNumElements();
5704     assert(isPowerOf2_32(NElem));
5705     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5706     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5707     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5708     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5709   }
5710 
5711   assert(VecSize <= 64);
5712 
5713   MVT IntVT = MVT::getIntegerVT(VecSize);
5714 
5715   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5716   SDValue VecBC = peekThroughBitcasts(Vec);
5717   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5718     SDValue Src = VecBC.getOperand(0);
5719     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5720     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5721   }
5722 
5723   unsigned EltSize = EltVT.getSizeInBits();
5724   assert(isPowerOf2_32(EltSize));
5725 
5726   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5727 
5728   // Convert vector index to bit-index (* EltSize)
5729   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5730 
5731   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5732   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5733 
5734   if (ResultVT == MVT::f16) {
5735     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5736     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5737   }
5738 
5739   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5740 }
5741 
5742 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5743   assert(Elt % 2 == 0);
5744   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5745 }
5746 
5747 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5748                                               SelectionDAG &DAG) const {
5749   SDLoc SL(Op);
5750   EVT ResultVT = Op.getValueType();
5751   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5752 
5753   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5754   EVT EltVT = PackVT.getVectorElementType();
5755   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5756 
5757   // vector_shuffle <0,1,6,7> lhs, rhs
5758   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5759   //
5760   // vector_shuffle <6,7,2,3> lhs, rhs
5761   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5762   //
5763   // vector_shuffle <6,7,0,1> lhs, rhs
5764   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5765 
5766   // Avoid scalarizing when both halves are reading from consecutive elements.
5767   SmallVector<SDValue, 4> Pieces;
5768   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5769     if (elementPairIsContiguous(SVN->getMask(), I)) {
5770       const int Idx = SVN->getMaskElt(I);
5771       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5772       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5773       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5774                                     PackVT, SVN->getOperand(VecIdx),
5775                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5776       Pieces.push_back(SubVec);
5777     } else {
5778       const int Idx0 = SVN->getMaskElt(I);
5779       const int Idx1 = SVN->getMaskElt(I + 1);
5780       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5781       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5782       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5783       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5784 
5785       SDValue Vec0 = SVN->getOperand(VecIdx0);
5786       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5787                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5788 
5789       SDValue Vec1 = SVN->getOperand(VecIdx1);
5790       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5791                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5792       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5793     }
5794   }
5795 
5796   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5797 }
5798 
5799 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5800                                                 SelectionDAG &DAG) const {
5801   SDValue SVal = Op.getOperand(0);
5802   EVT ResultVT = Op.getValueType();
5803   EVT SValVT = SVal.getValueType();
5804   SDValue UndefVal = DAG.getUNDEF(SValVT);
5805   SDLoc SL(Op);
5806 
5807   SmallVector<SDValue, 8> VElts;
5808   VElts.push_back(SVal);
5809   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5810     VElts.push_back(UndefVal);
5811 
5812   return DAG.getBuildVector(ResultVT, SL, VElts);
5813 }
5814 
5815 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5816                                             SelectionDAG &DAG) const {
5817   SDLoc SL(Op);
5818   EVT VT = Op.getValueType();
5819 
5820   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5821       VT == MVT::v8i16 || VT == MVT::v8f16) {
5822     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5823                                   VT.getVectorNumElements() / 2);
5824     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5825 
5826     // Turn into pair of packed build_vectors.
5827     // TODO: Special case for constants that can be materialized with s_mov_b64.
5828     SmallVector<SDValue, 4> LoOps, HiOps;
5829     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5830       LoOps.push_back(Op.getOperand(I));
5831       HiOps.push_back(Op.getOperand(I + E));
5832     }
5833     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5834     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5835 
5836     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5837     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5838 
5839     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5840                                        { CastLo, CastHi });
5841     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5842   }
5843 
5844   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5845   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5846 
5847   SDValue Lo = Op.getOperand(0);
5848   SDValue Hi = Op.getOperand(1);
5849 
5850   // Avoid adding defined bits with the zero_extend.
5851   if (Hi.isUndef()) {
5852     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5853     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5854     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5855   }
5856 
5857   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5858   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5859 
5860   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5861                               DAG.getConstant(16, SL, MVT::i32));
5862   if (Lo.isUndef())
5863     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5864 
5865   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5866   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5867 
5868   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5869   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5870 }
5871 
5872 bool
5873 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5874   // We can fold offsets for anything that doesn't require a GOT relocation.
5875   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5876           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5877           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5878          !shouldEmitGOTReloc(GA->getGlobal());
5879 }
5880 
5881 static SDValue
5882 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5883                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5884                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5885   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5886   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5887   // lowered to the following code sequence:
5888   //
5889   // For constant address space:
5890   //   s_getpc_b64 s[0:1]
5891   //   s_add_u32 s0, s0, $symbol
5892   //   s_addc_u32 s1, s1, 0
5893   //
5894   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5895   //   a fixup or relocation is emitted to replace $symbol with a literal
5896   //   constant, which is a pc-relative offset from the encoding of the $symbol
5897   //   operand to the global variable.
5898   //
5899   // For global address space:
5900   //   s_getpc_b64 s[0:1]
5901   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5902   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5903   //
5904   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5905   //   fixups or relocations are emitted to replace $symbol@*@lo and
5906   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5907   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5908   //   operand to the global variable.
5909   //
5910   // What we want here is an offset from the value returned by s_getpc
5911   // (which is the address of the s_add_u32 instruction) to the global
5912   // variable, but since the encoding of $symbol starts 4 bytes after the start
5913   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5914   // small. This requires us to add 4 to the global variable offset in order to
5915   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5916   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5917   // instruction.
5918   SDValue PtrLo =
5919       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5920   SDValue PtrHi;
5921   if (GAFlags == SIInstrInfo::MO_NONE) {
5922     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5923   } else {
5924     PtrHi =
5925         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5926   }
5927   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5928 }
5929 
5930 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5931                                              SDValue Op,
5932                                              SelectionDAG &DAG) const {
5933   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5934   SDLoc DL(GSD);
5935   EVT PtrVT = Op.getValueType();
5936 
5937   const GlobalValue *GV = GSD->getGlobal();
5938   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5939        shouldUseLDSConstAddress(GV)) ||
5940       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5941       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5942     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5943         GV->hasExternalLinkage()) {
5944       Type *Ty = GV->getValueType();
5945       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5946       // zero-sized type in other languages to declare the dynamic shared
5947       // memory which size is not known at the compile time. They will be
5948       // allocated by the runtime and placed directly after the static
5949       // allocated ones. They all share the same offset.
5950       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5951         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5952         // Adjust alignment for that dynamic shared memory array.
5953         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5954         return SDValue(
5955             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5956       }
5957     }
5958     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5959   }
5960 
5961   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5962     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5963                                             SIInstrInfo::MO_ABS32_LO);
5964     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5965   }
5966 
5967   if (shouldEmitFixup(GV))
5968     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5969   else if (shouldEmitPCReloc(GV))
5970     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5971                                    SIInstrInfo::MO_REL32);
5972 
5973   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5974                                             SIInstrInfo::MO_GOTPCREL32);
5975 
5976   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5977   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5978   const DataLayout &DataLayout = DAG.getDataLayout();
5979   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5980   MachinePointerInfo PtrInfo
5981     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5982 
5983   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5984                      MachineMemOperand::MODereferenceable |
5985                          MachineMemOperand::MOInvariant);
5986 }
5987 
5988 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5989                                    const SDLoc &DL, SDValue V) const {
5990   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5991   // the destination register.
5992   //
5993   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5994   // so we will end up with redundant moves to m0.
5995   //
5996   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5997 
5998   // A Null SDValue creates a glue result.
5999   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6000                                   V, Chain);
6001   return SDValue(M0, 0);
6002 }
6003 
6004 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6005                                                  SDValue Op,
6006                                                  MVT VT,
6007                                                  unsigned Offset) const {
6008   SDLoc SL(Op);
6009   SDValue Param = lowerKernargMemParameter(
6010       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6011   // The local size values will have the hi 16-bits as zero.
6012   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6013                      DAG.getValueType(VT));
6014 }
6015 
6016 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6017                                         EVT VT) {
6018   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6019                                       "non-hsa intrinsic with hsa target",
6020                                       DL.getDebugLoc());
6021   DAG.getContext()->diagnose(BadIntrin);
6022   return DAG.getUNDEF(VT);
6023 }
6024 
6025 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6026                                          EVT VT) {
6027   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6028                                       "intrinsic not supported on subtarget",
6029                                       DL.getDebugLoc());
6030   DAG.getContext()->diagnose(BadIntrin);
6031   return DAG.getUNDEF(VT);
6032 }
6033 
6034 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6035                                     ArrayRef<SDValue> Elts) {
6036   assert(!Elts.empty());
6037   MVT Type;
6038   unsigned NumElts = Elts.size();
6039 
6040   if (NumElts <= 8) {
6041     Type = MVT::getVectorVT(MVT::f32, NumElts);
6042   } else {
6043     assert(Elts.size() <= 16);
6044     Type = MVT::v16f32;
6045     NumElts = 16;
6046   }
6047 
6048   SmallVector<SDValue, 16> VecElts(NumElts);
6049   for (unsigned i = 0; i < Elts.size(); ++i) {
6050     SDValue Elt = Elts[i];
6051     if (Elt.getValueType() != MVT::f32)
6052       Elt = DAG.getBitcast(MVT::f32, Elt);
6053     VecElts[i] = Elt;
6054   }
6055   for (unsigned i = Elts.size(); i < NumElts; ++i)
6056     VecElts[i] = DAG.getUNDEF(MVT::f32);
6057 
6058   if (NumElts == 1)
6059     return VecElts[0];
6060   return DAG.getBuildVector(Type, DL, VecElts);
6061 }
6062 
6063 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6064                               SDValue Src, int ExtraElts) {
6065   EVT SrcVT = Src.getValueType();
6066 
6067   SmallVector<SDValue, 8> Elts;
6068 
6069   if (SrcVT.isVector())
6070     DAG.ExtractVectorElements(Src, Elts);
6071   else
6072     Elts.push_back(Src);
6073 
6074   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6075   while (ExtraElts--)
6076     Elts.push_back(Undef);
6077 
6078   return DAG.getBuildVector(CastVT, DL, Elts);
6079 }
6080 
6081 // Re-construct the required return value for a image load intrinsic.
6082 // This is more complicated due to the optional use TexFailCtrl which means the required
6083 // return type is an aggregate
6084 static SDValue constructRetValue(SelectionDAG &DAG,
6085                                  MachineSDNode *Result,
6086                                  ArrayRef<EVT> ResultTypes,
6087                                  bool IsTexFail, bool Unpacked, bool IsD16,
6088                                  int DMaskPop, int NumVDataDwords,
6089                                  const SDLoc &DL) {
6090   // Determine the required return type. This is the same regardless of IsTexFail flag
6091   EVT ReqRetVT = ResultTypes[0];
6092   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6093   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6094     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6095 
6096   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6097     DMaskPop : (DMaskPop + 1) / 2;
6098 
6099   MVT DataDwordVT = NumDataDwords == 1 ?
6100     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6101 
6102   MVT MaskPopVT = MaskPopDwords == 1 ?
6103     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6104 
6105   SDValue Data(Result, 0);
6106   SDValue TexFail;
6107 
6108   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6109     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6110     if (MaskPopVT.isVector()) {
6111       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6112                          SDValue(Result, 0), ZeroIdx);
6113     } else {
6114       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6115                          SDValue(Result, 0), ZeroIdx);
6116     }
6117   }
6118 
6119   if (DataDwordVT.isVector())
6120     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6121                           NumDataDwords - MaskPopDwords);
6122 
6123   if (IsD16)
6124     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6125 
6126   EVT LegalReqRetVT = ReqRetVT;
6127   if (!ReqRetVT.isVector()) {
6128     if (!Data.getValueType().isInteger())
6129       Data = DAG.getNode(ISD::BITCAST, DL,
6130                          Data.getValueType().changeTypeToInteger(), Data);
6131     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6132   } else {
6133     // We need to widen the return vector to a legal type
6134     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6135         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6136       LegalReqRetVT =
6137           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6138                            ReqRetVT.getVectorNumElements() + 1);
6139     }
6140   }
6141   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6142 
6143   if (IsTexFail) {
6144     TexFail =
6145         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6146                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6147 
6148     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6149   }
6150 
6151   if (Result->getNumValues() == 1)
6152     return Data;
6153 
6154   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6155 }
6156 
6157 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6158                          SDValue *LWE, bool &IsTexFail) {
6159   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6160 
6161   uint64_t Value = TexFailCtrlConst->getZExtValue();
6162   if (Value) {
6163     IsTexFail = true;
6164   }
6165 
6166   SDLoc DL(TexFailCtrlConst);
6167   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6168   Value &= ~(uint64_t)0x1;
6169   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6170   Value &= ~(uint64_t)0x2;
6171 
6172   return Value == 0;
6173 }
6174 
6175 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6176                                       MVT PackVectorVT,
6177                                       SmallVectorImpl<SDValue> &PackedAddrs,
6178                                       unsigned DimIdx, unsigned EndIdx,
6179                                       unsigned NumGradients) {
6180   SDLoc DL(Op);
6181   for (unsigned I = DimIdx; I < EndIdx; I++) {
6182     SDValue Addr = Op.getOperand(I);
6183 
6184     // Gradients are packed with undef for each coordinate.
6185     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6186     // 1D: undef,dx/dh; undef,dx/dv
6187     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6188     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6189     if (((I + 1) >= EndIdx) ||
6190         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6191                                          I == DimIdx + NumGradients - 1))) {
6192       if (Addr.getValueType() != MVT::i16)
6193         Addr = DAG.getBitcast(MVT::i16, Addr);
6194       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6195     } else {
6196       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6197       I++;
6198     }
6199     Addr = DAG.getBitcast(MVT::f32, Addr);
6200     PackedAddrs.push_back(Addr);
6201   }
6202 }
6203 
6204 SDValue SITargetLowering::lowerImage(SDValue Op,
6205                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6206                                      SelectionDAG &DAG, bool WithChain) const {
6207   SDLoc DL(Op);
6208   MachineFunction &MF = DAG.getMachineFunction();
6209   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6210   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6211       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6212   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6213   unsigned IntrOpcode = Intr->BaseOpcode;
6214   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6215   bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
6216 
6217   SmallVector<EVT, 3> ResultTypes(Op->values());
6218   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6219   bool IsD16 = false;
6220   bool IsG16 = false;
6221   bool IsA16 = false;
6222   SDValue VData;
6223   int NumVDataDwords;
6224   bool AdjustRetType = false;
6225 
6226   // Offset of intrinsic arguments
6227   const unsigned ArgOffset = WithChain ? 2 : 1;
6228 
6229   unsigned DMask;
6230   unsigned DMaskLanes = 0;
6231 
6232   if (BaseOpcode->Atomic) {
6233     VData = Op.getOperand(2);
6234 
6235     bool Is64Bit = VData.getValueType() == MVT::i64;
6236     if (BaseOpcode->AtomicX2) {
6237       SDValue VData2 = Op.getOperand(3);
6238       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6239                                  {VData, VData2});
6240       if (Is64Bit)
6241         VData = DAG.getBitcast(MVT::v4i32, VData);
6242 
6243       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6244       DMask = Is64Bit ? 0xf : 0x3;
6245       NumVDataDwords = Is64Bit ? 4 : 2;
6246     } else {
6247       DMask = Is64Bit ? 0x3 : 0x1;
6248       NumVDataDwords = Is64Bit ? 2 : 1;
6249     }
6250   } else {
6251     auto *DMaskConst =
6252         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6253     DMask = DMaskConst->getZExtValue();
6254     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6255 
6256     if (BaseOpcode->Store) {
6257       VData = Op.getOperand(2);
6258 
6259       MVT StoreVT = VData.getSimpleValueType();
6260       if (StoreVT.getScalarType() == MVT::f16) {
6261         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6262           return Op; // D16 is unsupported for this instruction
6263 
6264         IsD16 = true;
6265         VData = handleD16VData(VData, DAG, true);
6266       }
6267 
6268       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6269     } else {
6270       // Work out the num dwords based on the dmask popcount and underlying type
6271       // and whether packing is supported.
6272       MVT LoadVT = ResultTypes[0].getSimpleVT();
6273       if (LoadVT.getScalarType() == MVT::f16) {
6274         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6275           return Op; // D16 is unsupported for this instruction
6276 
6277         IsD16 = true;
6278       }
6279 
6280       // Confirm that the return type is large enough for the dmask specified
6281       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6282           (!LoadVT.isVector() && DMaskLanes > 1))
6283           return Op;
6284 
6285       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6286       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6287       // instructions.
6288       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6289           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6290         NumVDataDwords = (DMaskLanes + 1) / 2;
6291       else
6292         NumVDataDwords = DMaskLanes;
6293 
6294       AdjustRetType = true;
6295     }
6296   }
6297 
6298   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6299   SmallVector<SDValue, 4> VAddrs;
6300 
6301   // Check for 16 bit addresses or derivatives and pack if true.
6302   MVT VAddrVT =
6303       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6304   MVT VAddrScalarVT = VAddrVT.getScalarType();
6305   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6306   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6307 
6308   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6309   VAddrScalarVT = VAddrVT.getScalarType();
6310   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6311   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6312 
6313   // Push back extra arguments.
6314   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6315     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6316       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6317       // Special handling of bias when A16 is on. Bias is of type half but
6318       // occupies full 32-bit.
6319       SDValue Bias = DAG.getBuildVector(
6320           MVT::v2f16, DL,
6321           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6322       VAddrs.push_back(Bias);
6323     } else {
6324       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6325              "Bias needs to be converted to 16 bit in A16 mode");
6326       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6327     }
6328   }
6329 
6330   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6331     // 16 bit gradients are supported, but are tied to the A16 control
6332     // so both gradients and addresses must be 16 bit
6333     LLVM_DEBUG(
6334         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6335                   "require 16 bit args for both gradients and addresses");
6336     return Op;
6337   }
6338 
6339   if (IsA16) {
6340     if (!ST->hasA16()) {
6341       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6342                            "support 16 bit addresses\n");
6343       return Op;
6344     }
6345   }
6346 
6347   // We've dealt with incorrect input so we know that if IsA16, IsG16
6348   // are set then we have to compress/pack operands (either address,
6349   // gradient or both)
6350   // In the case where a16 and gradients are tied (no G16 support) then we
6351   // have already verified that both IsA16 and IsG16 are true
6352   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6353     // Activate g16
6354     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6355         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6356     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6357   }
6358 
6359   // Add gradients (packed or unpacked)
6360   if (IsG16) {
6361     // Pack the gradients
6362     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6363     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6364                               ArgOffset + Intr->GradientStart,
6365                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6366   } else {
6367     for (unsigned I = ArgOffset + Intr->GradientStart;
6368          I < ArgOffset + Intr->CoordStart; I++)
6369       VAddrs.push_back(Op.getOperand(I));
6370   }
6371 
6372   // Add addresses (packed or unpacked)
6373   if (IsA16) {
6374     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6375                               ArgOffset + Intr->CoordStart, VAddrEnd,
6376                               0 /* No gradients */);
6377   } else {
6378     // Add uncompressed address
6379     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6380       VAddrs.push_back(Op.getOperand(I));
6381   }
6382 
6383   // If the register allocator cannot place the address registers contiguously
6384   // without introducing moves, then using the non-sequential address encoding
6385   // is always preferable, since it saves VALU instructions and is usually a
6386   // wash in terms of code size or even better.
6387   //
6388   // However, we currently have no way of hinting to the register allocator that
6389   // MIMG addresses should be placed contiguously when it is possible to do so,
6390   // so force non-NSA for the common 2-address case as a heuristic.
6391   //
6392   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6393   // allocation when possible.
6394   //
6395   // TODO: we can actually allow partial NSA where the final register is a
6396   // contiguous set of the remaining addresses.
6397   // This could help where there are more addresses than supported.
6398   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6399                 VAddrs.size() >= 3 &&
6400                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6401   SDValue VAddr;
6402   if (!UseNSA)
6403     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6404 
6405   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6406   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6407   SDValue Unorm;
6408   if (!BaseOpcode->Sampler) {
6409     Unorm = True;
6410   } else {
6411     auto UnormConst =
6412         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6413 
6414     Unorm = UnormConst->getZExtValue() ? True : False;
6415   }
6416 
6417   SDValue TFE;
6418   SDValue LWE;
6419   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6420   bool IsTexFail = false;
6421   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6422     return Op;
6423 
6424   if (IsTexFail) {
6425     if (!DMaskLanes) {
6426       // Expecting to get an error flag since TFC is on - and dmask is 0
6427       // Force dmask to be at least 1 otherwise the instruction will fail
6428       DMask = 0x1;
6429       DMaskLanes = 1;
6430       NumVDataDwords = 1;
6431     }
6432     NumVDataDwords += 1;
6433     AdjustRetType = true;
6434   }
6435 
6436   // Has something earlier tagged that the return type needs adjusting
6437   // This happens if the instruction is a load or has set TexFailCtrl flags
6438   if (AdjustRetType) {
6439     // NumVDataDwords reflects the true number of dwords required in the return type
6440     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6441       // This is a no-op load. This can be eliminated
6442       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6443       if (isa<MemSDNode>(Op))
6444         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6445       return Undef;
6446     }
6447 
6448     EVT NewVT = NumVDataDwords > 1 ?
6449                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6450                 : MVT::i32;
6451 
6452     ResultTypes[0] = NewVT;
6453     if (ResultTypes.size() == 3) {
6454       // Original result was aggregate type used for TexFailCtrl results
6455       // The actual instruction returns as a vector type which has now been
6456       // created. Remove the aggregate result.
6457       ResultTypes.erase(&ResultTypes[1]);
6458     }
6459   }
6460 
6461   unsigned CPol = cast<ConstantSDNode>(
6462       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6463   if (BaseOpcode->Atomic)
6464     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6465   if (CPol & ~AMDGPU::CPol::ALL)
6466     return Op;
6467 
6468   SmallVector<SDValue, 26> Ops;
6469   if (BaseOpcode->Store || BaseOpcode->Atomic)
6470     Ops.push_back(VData); // vdata
6471   if (UseNSA)
6472     append_range(Ops, VAddrs);
6473   else
6474     Ops.push_back(VAddr);
6475   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6476   if (BaseOpcode->Sampler)
6477     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6478   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6479   if (IsGFX10Plus)
6480     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6481   Ops.push_back(Unorm);
6482   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6483   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6484                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6485   if (IsGFX10Plus)
6486     Ops.push_back(IsA16 ? True : False);
6487   if (!Subtarget->hasGFX90AInsts()) {
6488     Ops.push_back(TFE); //tfe
6489   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6490     report_fatal_error("TFE is not supported on this GPU");
6491   }
6492   Ops.push_back(LWE); // lwe
6493   if (!IsGFX10Plus)
6494     Ops.push_back(DimInfo->DA ? True : False);
6495   if (BaseOpcode->HasD16)
6496     Ops.push_back(IsD16 ? True : False);
6497   if (isa<MemSDNode>(Op))
6498     Ops.push_back(Op.getOperand(0)); // chain
6499 
6500   int NumVAddrDwords =
6501       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6502   int Opcode = -1;
6503 
6504   if (IsGFX11Plus) {
6505     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6506                                    UseNSA ? AMDGPU::MIMGEncGfx11NSA
6507                                           : AMDGPU::MIMGEncGfx11Default,
6508                                    NumVDataDwords, NumVAddrDwords);
6509   } else if (IsGFX10Plus) {
6510     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6511                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6512                                           : AMDGPU::MIMGEncGfx10Default,
6513                                    NumVDataDwords, NumVAddrDwords);
6514   } else {
6515     if (Subtarget->hasGFX90AInsts()) {
6516       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6517                                      NumVDataDwords, NumVAddrDwords);
6518       if (Opcode == -1)
6519         report_fatal_error(
6520             "requested image instruction is not supported on this GPU");
6521     }
6522     if (Opcode == -1 &&
6523         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6524       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6525                                      NumVDataDwords, NumVAddrDwords);
6526     if (Opcode == -1)
6527       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6528                                      NumVDataDwords, NumVAddrDwords);
6529   }
6530   assert(Opcode != -1);
6531 
6532   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6533   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6534     MachineMemOperand *MemRef = MemOp->getMemOperand();
6535     DAG.setNodeMemRefs(NewNode, {MemRef});
6536   }
6537 
6538   if (BaseOpcode->AtomicX2) {
6539     SmallVector<SDValue, 1> Elt;
6540     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6541     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6542   }
6543   if (BaseOpcode->Store)
6544     return SDValue(NewNode, 0);
6545   return constructRetValue(DAG, NewNode,
6546                            OrigResultTypes, IsTexFail,
6547                            Subtarget->hasUnpackedD16VMem(), IsD16,
6548                            DMaskLanes, NumVDataDwords, DL);
6549 }
6550 
6551 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6552                                        SDValue Offset, SDValue CachePolicy,
6553                                        SelectionDAG &DAG) const {
6554   MachineFunction &MF = DAG.getMachineFunction();
6555 
6556   const DataLayout &DataLayout = DAG.getDataLayout();
6557   Align Alignment =
6558       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6559 
6560   MachineMemOperand *MMO = MF.getMachineMemOperand(
6561       MachinePointerInfo(),
6562       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6563           MachineMemOperand::MOInvariant,
6564       VT.getStoreSize(), Alignment);
6565 
6566   if (!Offset->isDivergent()) {
6567     SDValue Ops[] = {
6568         Rsrc,
6569         Offset, // Offset
6570         CachePolicy
6571     };
6572 
6573     // Widen vec3 load to vec4.
6574     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6575       EVT WidenedVT =
6576           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6577       auto WidenedOp = DAG.getMemIntrinsicNode(
6578           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6579           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6580       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6581                                    DAG.getVectorIdxConstant(0, DL));
6582       return Subvector;
6583     }
6584 
6585     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6586                                    DAG.getVTList(VT), Ops, VT, MMO);
6587   }
6588 
6589   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6590   // assume that the buffer is unswizzled.
6591   SmallVector<SDValue, 4> Loads;
6592   unsigned NumLoads = 1;
6593   MVT LoadVT = VT.getSimpleVT();
6594   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6595   assert((LoadVT.getScalarType() == MVT::i32 ||
6596           LoadVT.getScalarType() == MVT::f32));
6597 
6598   if (NumElts == 8 || NumElts == 16) {
6599     NumLoads = NumElts / 4;
6600     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6601   }
6602 
6603   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6604   SDValue Ops[] = {
6605       DAG.getEntryNode(),                               // Chain
6606       Rsrc,                                             // rsrc
6607       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6608       {},                                               // voffset
6609       {},                                               // soffset
6610       {},                                               // offset
6611       CachePolicy,                                      // cachepolicy
6612       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6613   };
6614 
6615   // Use the alignment to ensure that the required offsets will fit into the
6616   // immediate offsets.
6617   setBufferOffsets(Offset, DAG, &Ops[3],
6618                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6619 
6620   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6621   for (unsigned i = 0; i < NumLoads; ++i) {
6622     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6623     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6624                                         LoadVT, MMO, DAG));
6625   }
6626 
6627   if (NumElts == 8 || NumElts == 16)
6628     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6629 
6630   return Loads[0];
6631 }
6632 
6633 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6634                                           unsigned Dim,
6635                                           const ArgDescriptor &Arg) const {
6636   SDLoc SL(Op);
6637   MachineFunction &MF = DAG.getMachineFunction();
6638   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6639   if (MaxID == 0)
6640     return DAG.getConstant(0, SL, MVT::i32);
6641 
6642   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6643                                SDLoc(DAG.getEntryNode()), Arg);
6644 
6645   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6646   // masking operations anyway.
6647   //
6648   // TODO: We could assert the top bit is 0 for the source copy.
6649   if (Arg.isMasked())
6650     return Val;
6651 
6652   // Preserve the known bits after expansion to a copy.
6653   EVT SmallVT =
6654       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6655   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6656                      DAG.getValueType(SmallVT));
6657 }
6658 
6659 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6660                                                   SelectionDAG &DAG) const {
6661   MachineFunction &MF = DAG.getMachineFunction();
6662   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6663 
6664   EVT VT = Op.getValueType();
6665   SDLoc DL(Op);
6666   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6667 
6668   // TODO: Should this propagate fast-math-flags?
6669 
6670   switch (IntrinsicID) {
6671   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6672     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6673       return emitNonHSAIntrinsicError(DAG, DL, VT);
6674     return getPreloadedValue(DAG, *MFI, VT,
6675                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6676   }
6677   case Intrinsic::amdgcn_dispatch_ptr:
6678   case Intrinsic::amdgcn_queue_ptr: {
6679     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6680       DiagnosticInfoUnsupported BadIntrin(
6681           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6682           DL.getDebugLoc());
6683       DAG.getContext()->diagnose(BadIntrin);
6684       return DAG.getUNDEF(VT);
6685     }
6686 
6687     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6688       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6689     return getPreloadedValue(DAG, *MFI, VT, RegID);
6690   }
6691   case Intrinsic::amdgcn_implicitarg_ptr: {
6692     if (MFI->isEntryFunction())
6693       return getImplicitArgPtr(DAG, DL);
6694     return getPreloadedValue(DAG, *MFI, VT,
6695                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6696   }
6697   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6698     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6699       // This only makes sense to call in a kernel, so just lower to null.
6700       return DAG.getConstant(0, DL, VT);
6701     }
6702 
6703     return getPreloadedValue(DAG, *MFI, VT,
6704                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6705   }
6706   case Intrinsic::amdgcn_dispatch_id: {
6707     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6708   }
6709   case Intrinsic::amdgcn_rcp:
6710     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6711   case Intrinsic::amdgcn_rsq:
6712     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6713   case Intrinsic::amdgcn_rsq_legacy:
6714     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6715       return emitRemovedIntrinsicError(DAG, DL, VT);
6716     return SDValue();
6717   case Intrinsic::amdgcn_rcp_legacy:
6718     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6719       return emitRemovedIntrinsicError(DAG, DL, VT);
6720     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6721   case Intrinsic::amdgcn_rsq_clamp: {
6722     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6723       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6724 
6725     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6726     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6727     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6728 
6729     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6730     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6731                               DAG.getConstantFP(Max, DL, VT));
6732     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6733                        DAG.getConstantFP(Min, DL, VT));
6734   }
6735   case Intrinsic::r600_read_ngroups_x:
6736     if (Subtarget->isAmdHsaOS())
6737       return emitNonHSAIntrinsicError(DAG, DL, VT);
6738 
6739     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6740                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6741                                     false);
6742   case Intrinsic::r600_read_ngroups_y:
6743     if (Subtarget->isAmdHsaOS())
6744       return emitNonHSAIntrinsicError(DAG, DL, VT);
6745 
6746     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6747                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6748                                     false);
6749   case Intrinsic::r600_read_ngroups_z:
6750     if (Subtarget->isAmdHsaOS())
6751       return emitNonHSAIntrinsicError(DAG, DL, VT);
6752 
6753     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6754                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6755                                     false);
6756   case Intrinsic::r600_read_global_size_x:
6757     if (Subtarget->isAmdHsaOS())
6758       return emitNonHSAIntrinsicError(DAG, DL, VT);
6759 
6760     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6761                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6762                                     Align(4), false);
6763   case Intrinsic::r600_read_global_size_y:
6764     if (Subtarget->isAmdHsaOS())
6765       return emitNonHSAIntrinsicError(DAG, DL, VT);
6766 
6767     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6768                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6769                                     Align(4), false);
6770   case Intrinsic::r600_read_global_size_z:
6771     if (Subtarget->isAmdHsaOS())
6772       return emitNonHSAIntrinsicError(DAG, DL, VT);
6773 
6774     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6775                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6776                                     Align(4), false);
6777   case Intrinsic::r600_read_local_size_x:
6778     if (Subtarget->isAmdHsaOS())
6779       return emitNonHSAIntrinsicError(DAG, DL, VT);
6780 
6781     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6782                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6783   case Intrinsic::r600_read_local_size_y:
6784     if (Subtarget->isAmdHsaOS())
6785       return emitNonHSAIntrinsicError(DAG, DL, VT);
6786 
6787     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6788                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6789   case Intrinsic::r600_read_local_size_z:
6790     if (Subtarget->isAmdHsaOS())
6791       return emitNonHSAIntrinsicError(DAG, DL, VT);
6792 
6793     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6794                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6795   case Intrinsic::amdgcn_workgroup_id_x:
6796     return getPreloadedValue(DAG, *MFI, VT,
6797                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6798   case Intrinsic::amdgcn_workgroup_id_y:
6799     return getPreloadedValue(DAG, *MFI, VT,
6800                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6801   case Intrinsic::amdgcn_workgroup_id_z:
6802     return getPreloadedValue(DAG, *MFI, VT,
6803                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6804   case Intrinsic::amdgcn_workitem_id_x:
6805     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6806   case Intrinsic::amdgcn_workitem_id_y:
6807     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6808   case Intrinsic::amdgcn_workitem_id_z:
6809     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6810   case Intrinsic::amdgcn_wavefrontsize:
6811     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6812                            SDLoc(Op), MVT::i32);
6813   case Intrinsic::amdgcn_s_buffer_load: {
6814     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6815     if (CPol & ~AMDGPU::CPol::ALL)
6816       return Op;
6817     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6818                         DAG);
6819   }
6820   case Intrinsic::amdgcn_fdiv_fast:
6821     return lowerFDIV_FAST(Op, DAG);
6822   case Intrinsic::amdgcn_sin:
6823     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6824 
6825   case Intrinsic::amdgcn_cos:
6826     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6827 
6828   case Intrinsic::amdgcn_mul_u24:
6829     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6830   case Intrinsic::amdgcn_mul_i24:
6831     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6832 
6833   case Intrinsic::amdgcn_log_clamp: {
6834     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6835       return SDValue();
6836 
6837     return emitRemovedIntrinsicError(DAG, DL, VT);
6838   }
6839   case Intrinsic::amdgcn_ldexp:
6840     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6841                        Op.getOperand(1), Op.getOperand(2));
6842 
6843   case Intrinsic::amdgcn_fract:
6844     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6845 
6846   case Intrinsic::amdgcn_class:
6847     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6848                        Op.getOperand(1), Op.getOperand(2));
6849   case Intrinsic::amdgcn_div_fmas:
6850     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6851                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6852                        Op.getOperand(4));
6853 
6854   case Intrinsic::amdgcn_div_fixup:
6855     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6856                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6857 
6858   case Intrinsic::amdgcn_div_scale: {
6859     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6860 
6861     // Translate to the operands expected by the machine instruction. The
6862     // first parameter must be the same as the first instruction.
6863     SDValue Numerator = Op.getOperand(1);
6864     SDValue Denominator = Op.getOperand(2);
6865 
6866     // Note this order is opposite of the machine instruction's operations,
6867     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6868     // intrinsic has the numerator as the first operand to match a normal
6869     // division operation.
6870 
6871     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6872 
6873     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6874                        Denominator, Numerator);
6875   }
6876   case Intrinsic::amdgcn_icmp: {
6877     // There is a Pat that handles this variant, so return it as-is.
6878     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6879         Op.getConstantOperandVal(2) == 0 &&
6880         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6881       return Op;
6882     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6883   }
6884   case Intrinsic::amdgcn_fcmp: {
6885     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6886   }
6887   case Intrinsic::amdgcn_ballot:
6888     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6889   case Intrinsic::amdgcn_fmed3:
6890     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6891                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6892   case Intrinsic::amdgcn_fdot2:
6893     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6894                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6895                        Op.getOperand(4));
6896   case Intrinsic::amdgcn_fmul_legacy:
6897     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6898                        Op.getOperand(1), Op.getOperand(2));
6899   case Intrinsic::amdgcn_sffbh:
6900     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6901   case Intrinsic::amdgcn_sbfe:
6902     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6903                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6904   case Intrinsic::amdgcn_ubfe:
6905     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6906                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6907   case Intrinsic::amdgcn_cvt_pkrtz:
6908   case Intrinsic::amdgcn_cvt_pknorm_i16:
6909   case Intrinsic::amdgcn_cvt_pknorm_u16:
6910   case Intrinsic::amdgcn_cvt_pk_i16:
6911   case Intrinsic::amdgcn_cvt_pk_u16: {
6912     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6913     EVT VT = Op.getValueType();
6914     unsigned Opcode;
6915 
6916     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6917       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6918     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6919       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6920     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6921       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6922     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6923       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6924     else
6925       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6926 
6927     if (isTypeLegal(VT))
6928       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6929 
6930     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6931                                Op.getOperand(1), Op.getOperand(2));
6932     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6933   }
6934   case Intrinsic::amdgcn_fmad_ftz:
6935     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6936                        Op.getOperand(2), Op.getOperand(3));
6937 
6938   case Intrinsic::amdgcn_if_break:
6939     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6940                                       Op->getOperand(1), Op->getOperand(2)), 0);
6941 
6942   case Intrinsic::amdgcn_groupstaticsize: {
6943     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6944     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6945       return Op;
6946 
6947     const Module *M = MF.getFunction().getParent();
6948     const GlobalValue *GV =
6949         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6950     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6951                                             SIInstrInfo::MO_ABS32_LO);
6952     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6953   }
6954   case Intrinsic::amdgcn_is_shared:
6955   case Intrinsic::amdgcn_is_private: {
6956     SDLoc SL(Op);
6957     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6958       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6959     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6960     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6961                                  Op.getOperand(1));
6962 
6963     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6964                                 DAG.getConstant(1, SL, MVT::i32));
6965     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6966   }
6967   case Intrinsic::amdgcn_perm:
6968     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6969                        Op.getOperand(2), Op.getOperand(3));
6970   case Intrinsic::amdgcn_reloc_constant: {
6971     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6972     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6973     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6974     auto RelocSymbol = cast<GlobalVariable>(
6975         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6976     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6977                                             SIInstrInfo::MO_ABS32_LO);
6978     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6979   }
6980   default:
6981     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6982             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6983       return lowerImage(Op, ImageDimIntr, DAG, false);
6984 
6985     return Op;
6986   }
6987 }
6988 
6989 /// Update \p MMO based on the offset inputs to an intrinsic.
6990 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6991                             SDValue SOffset, SDValue Offset,
6992                             SDValue VIndex = SDValue()) {
6993   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6994       !isa<ConstantSDNode>(Offset)) {
6995     // The combined offset is not known to be constant, so we cannot represent
6996     // it in the MMO. Give up.
6997     MMO->setValue((Value *)nullptr);
6998     return;
6999   }
7000 
7001   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7002                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7003     // The strided index component of the address is not known to be zero, so we
7004     // cannot represent it in the MMO. Give up.
7005     MMO->setValue((Value *)nullptr);
7006     return;
7007   }
7008 
7009   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7010                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7011                  cast<ConstantSDNode>(Offset)->getSExtValue());
7012 }
7013 
7014 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7015                                                      SelectionDAG &DAG,
7016                                                      unsigned NewOpcode) const {
7017   SDLoc DL(Op);
7018 
7019   SDValue VData = Op.getOperand(2);
7020   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7021   SDValue Ops[] = {
7022     Op.getOperand(0), // Chain
7023     VData,            // vdata
7024     Op.getOperand(3), // rsrc
7025     DAG.getConstant(0, DL, MVT::i32), // vindex
7026     Offsets.first,    // voffset
7027     Op.getOperand(5), // soffset
7028     Offsets.second,   // offset
7029     Op.getOperand(6), // cachepolicy
7030     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7031   };
7032 
7033   auto *M = cast<MemSDNode>(Op);
7034   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7035 
7036   EVT MemVT = VData.getValueType();
7037   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7038                                  M->getMemOperand());
7039 }
7040 
7041 // Return a value to use for the idxen operand by examining the vindex operand.
7042 static unsigned getIdxEn(SDValue VIndex) {
7043   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7044     // No need to set idxen if vindex is known to be zero.
7045     return VIndexC->getZExtValue() != 0;
7046   return 1;
7047 }
7048 
7049 SDValue
7050 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7051                                                 unsigned NewOpcode) const {
7052   SDLoc DL(Op);
7053 
7054   SDValue VData = Op.getOperand(2);
7055   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7056   SDValue Ops[] = {
7057     Op.getOperand(0), // Chain
7058     VData,            // vdata
7059     Op.getOperand(3), // rsrc
7060     Op.getOperand(4), // vindex
7061     Offsets.first,    // voffset
7062     Op.getOperand(6), // soffset
7063     Offsets.second,   // offset
7064     Op.getOperand(7), // cachepolicy
7065     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7066   };
7067 
7068   auto *M = cast<MemSDNode>(Op);
7069   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7070 
7071   EVT MemVT = VData.getValueType();
7072   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7073                                  M->getMemOperand());
7074 }
7075 
7076 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7077                                                  SelectionDAG &DAG) const {
7078   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7079   SDLoc DL(Op);
7080 
7081   switch (IntrID) {
7082   case Intrinsic::amdgcn_ds_ordered_add:
7083   case Intrinsic::amdgcn_ds_ordered_swap: {
7084     MemSDNode *M = cast<MemSDNode>(Op);
7085     SDValue Chain = M->getOperand(0);
7086     SDValue M0 = M->getOperand(2);
7087     SDValue Value = M->getOperand(3);
7088     unsigned IndexOperand = M->getConstantOperandVal(7);
7089     unsigned WaveRelease = M->getConstantOperandVal(8);
7090     unsigned WaveDone = M->getConstantOperandVal(9);
7091 
7092     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7093     IndexOperand &= ~0x3f;
7094     unsigned CountDw = 0;
7095 
7096     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7097       CountDw = (IndexOperand >> 24) & 0xf;
7098       IndexOperand &= ~(0xf << 24);
7099 
7100       if (CountDw < 1 || CountDw > 4) {
7101         report_fatal_error(
7102             "ds_ordered_count: dword count must be between 1 and 4");
7103       }
7104     }
7105 
7106     if (IndexOperand)
7107       report_fatal_error("ds_ordered_count: bad index operand");
7108 
7109     if (WaveDone && !WaveRelease)
7110       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7111 
7112     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7113     unsigned ShaderType =
7114         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7115     unsigned Offset0 = OrderedCountIndex << 2;
7116     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7117                        (Instruction << 4);
7118 
7119     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7120       Offset1 |= (CountDw - 1) << 6;
7121 
7122     unsigned Offset = Offset0 | (Offset1 << 8);
7123 
7124     SDValue Ops[] = {
7125       Chain,
7126       Value,
7127       DAG.getTargetConstant(Offset, DL, MVT::i16),
7128       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7129     };
7130     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7131                                    M->getVTList(), Ops, M->getMemoryVT(),
7132                                    M->getMemOperand());
7133   }
7134   case Intrinsic::amdgcn_ds_fadd: {
7135     MemSDNode *M = cast<MemSDNode>(Op);
7136     unsigned Opc;
7137     switch (IntrID) {
7138     case Intrinsic::amdgcn_ds_fadd:
7139       Opc = ISD::ATOMIC_LOAD_FADD;
7140       break;
7141     }
7142 
7143     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7144                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7145                          M->getMemOperand());
7146   }
7147   case Intrinsic::amdgcn_atomic_inc:
7148   case Intrinsic::amdgcn_atomic_dec:
7149   case Intrinsic::amdgcn_ds_fmin:
7150   case Intrinsic::amdgcn_ds_fmax: {
7151     MemSDNode *M = cast<MemSDNode>(Op);
7152     unsigned Opc;
7153     switch (IntrID) {
7154     case Intrinsic::amdgcn_atomic_inc:
7155       Opc = AMDGPUISD::ATOMIC_INC;
7156       break;
7157     case Intrinsic::amdgcn_atomic_dec:
7158       Opc = AMDGPUISD::ATOMIC_DEC;
7159       break;
7160     case Intrinsic::amdgcn_ds_fmin:
7161       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7162       break;
7163     case Intrinsic::amdgcn_ds_fmax:
7164       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7165       break;
7166     default:
7167       llvm_unreachable("Unknown intrinsic!");
7168     }
7169     SDValue Ops[] = {
7170       M->getOperand(0), // Chain
7171       M->getOperand(2), // Ptr
7172       M->getOperand(3)  // Value
7173     };
7174 
7175     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7176                                    M->getMemoryVT(), M->getMemOperand());
7177   }
7178   case Intrinsic::amdgcn_buffer_load:
7179   case Intrinsic::amdgcn_buffer_load_format: {
7180     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7181     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7182     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7183     SDValue Ops[] = {
7184       Op.getOperand(0), // Chain
7185       Op.getOperand(2), // rsrc
7186       Op.getOperand(3), // vindex
7187       SDValue(),        // voffset -- will be set by setBufferOffsets
7188       SDValue(),        // soffset -- will be set by setBufferOffsets
7189       SDValue(),        // offset -- will be set by setBufferOffsets
7190       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7191       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7192     };
7193     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7194 
7195     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7196         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7197 
7198     EVT VT = Op.getValueType();
7199     EVT IntVT = VT.changeTypeToInteger();
7200     auto *M = cast<MemSDNode>(Op);
7201     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7202     EVT LoadVT = Op.getValueType();
7203 
7204     if (LoadVT.getScalarType() == MVT::f16)
7205       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7206                                  M, DAG, Ops);
7207 
7208     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7209     if (LoadVT.getScalarType() == MVT::i8 ||
7210         LoadVT.getScalarType() == MVT::i16)
7211       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7212 
7213     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7214                                M->getMemOperand(), DAG);
7215   }
7216   case Intrinsic::amdgcn_raw_buffer_load:
7217   case Intrinsic::amdgcn_raw_buffer_load_format: {
7218     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7219 
7220     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7221     SDValue Ops[] = {
7222       Op.getOperand(0), // Chain
7223       Op.getOperand(2), // rsrc
7224       DAG.getConstant(0, DL, MVT::i32), // vindex
7225       Offsets.first,    // voffset
7226       Op.getOperand(4), // soffset
7227       Offsets.second,   // offset
7228       Op.getOperand(5), // cachepolicy, swizzled buffer
7229       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7230     };
7231 
7232     auto *M = cast<MemSDNode>(Op);
7233     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7234     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7235   }
7236   case Intrinsic::amdgcn_struct_buffer_load:
7237   case Intrinsic::amdgcn_struct_buffer_load_format: {
7238     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7239 
7240     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7241     SDValue Ops[] = {
7242       Op.getOperand(0), // Chain
7243       Op.getOperand(2), // rsrc
7244       Op.getOperand(3), // vindex
7245       Offsets.first,    // voffset
7246       Op.getOperand(5), // soffset
7247       Offsets.second,   // offset
7248       Op.getOperand(6), // cachepolicy, swizzled buffer
7249       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7250     };
7251 
7252     auto *M = cast<MemSDNode>(Op);
7253     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7254     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7255   }
7256   case Intrinsic::amdgcn_tbuffer_load: {
7257     MemSDNode *M = cast<MemSDNode>(Op);
7258     EVT LoadVT = Op.getValueType();
7259 
7260     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7261     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7262     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7263     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7264     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7265     SDValue Ops[] = {
7266       Op.getOperand(0),  // Chain
7267       Op.getOperand(2),  // rsrc
7268       Op.getOperand(3),  // vindex
7269       Op.getOperand(4),  // voffset
7270       Op.getOperand(5),  // soffset
7271       Op.getOperand(6),  // offset
7272       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7273       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7274       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7275     };
7276 
7277     if (LoadVT.getScalarType() == MVT::f16)
7278       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7279                                  M, DAG, Ops);
7280     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7281                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7282                                DAG);
7283   }
7284   case Intrinsic::amdgcn_raw_tbuffer_load: {
7285     MemSDNode *M = cast<MemSDNode>(Op);
7286     EVT LoadVT = Op.getValueType();
7287     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7288 
7289     SDValue Ops[] = {
7290       Op.getOperand(0),  // Chain
7291       Op.getOperand(2),  // rsrc
7292       DAG.getConstant(0, DL, MVT::i32), // vindex
7293       Offsets.first,     // voffset
7294       Op.getOperand(4),  // soffset
7295       Offsets.second,    // offset
7296       Op.getOperand(5),  // format
7297       Op.getOperand(6),  // cachepolicy, swizzled buffer
7298       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7299     };
7300 
7301     if (LoadVT.getScalarType() == MVT::f16)
7302       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7303                                  M, DAG, Ops);
7304     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7305                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7306                                DAG);
7307   }
7308   case Intrinsic::amdgcn_struct_tbuffer_load: {
7309     MemSDNode *M = cast<MemSDNode>(Op);
7310     EVT LoadVT = Op.getValueType();
7311     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7312 
7313     SDValue Ops[] = {
7314       Op.getOperand(0),  // Chain
7315       Op.getOperand(2),  // rsrc
7316       Op.getOperand(3),  // vindex
7317       Offsets.first,     // voffset
7318       Op.getOperand(5),  // soffset
7319       Offsets.second,    // offset
7320       Op.getOperand(6),  // format
7321       Op.getOperand(7),  // cachepolicy, swizzled buffer
7322       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7323     };
7324 
7325     if (LoadVT.getScalarType() == MVT::f16)
7326       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7327                                  M, DAG, Ops);
7328     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7329                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7330                                DAG);
7331   }
7332   case Intrinsic::amdgcn_buffer_atomic_swap:
7333   case Intrinsic::amdgcn_buffer_atomic_add:
7334   case Intrinsic::amdgcn_buffer_atomic_sub:
7335   case Intrinsic::amdgcn_buffer_atomic_csub:
7336   case Intrinsic::amdgcn_buffer_atomic_smin:
7337   case Intrinsic::amdgcn_buffer_atomic_umin:
7338   case Intrinsic::amdgcn_buffer_atomic_smax:
7339   case Intrinsic::amdgcn_buffer_atomic_umax:
7340   case Intrinsic::amdgcn_buffer_atomic_and:
7341   case Intrinsic::amdgcn_buffer_atomic_or:
7342   case Intrinsic::amdgcn_buffer_atomic_xor:
7343   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7344     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7345     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7346     SDValue Ops[] = {
7347       Op.getOperand(0), // Chain
7348       Op.getOperand(2), // vdata
7349       Op.getOperand(3), // rsrc
7350       Op.getOperand(4), // vindex
7351       SDValue(),        // voffset -- will be set by setBufferOffsets
7352       SDValue(),        // soffset -- will be set by setBufferOffsets
7353       SDValue(),        // offset -- will be set by setBufferOffsets
7354       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7355       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7356     };
7357     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7358 
7359     EVT VT = Op.getValueType();
7360 
7361     auto *M = cast<MemSDNode>(Op);
7362     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7363     unsigned Opcode = 0;
7364 
7365     switch (IntrID) {
7366     case Intrinsic::amdgcn_buffer_atomic_swap:
7367       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7368       break;
7369     case Intrinsic::amdgcn_buffer_atomic_add:
7370       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7371       break;
7372     case Intrinsic::amdgcn_buffer_atomic_sub:
7373       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7374       break;
7375     case Intrinsic::amdgcn_buffer_atomic_csub:
7376       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7377       break;
7378     case Intrinsic::amdgcn_buffer_atomic_smin:
7379       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7380       break;
7381     case Intrinsic::amdgcn_buffer_atomic_umin:
7382       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7383       break;
7384     case Intrinsic::amdgcn_buffer_atomic_smax:
7385       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7386       break;
7387     case Intrinsic::amdgcn_buffer_atomic_umax:
7388       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7389       break;
7390     case Intrinsic::amdgcn_buffer_atomic_and:
7391       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7392       break;
7393     case Intrinsic::amdgcn_buffer_atomic_or:
7394       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7395       break;
7396     case Intrinsic::amdgcn_buffer_atomic_xor:
7397       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7398       break;
7399     case Intrinsic::amdgcn_buffer_atomic_fadd:
7400       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7401         DiagnosticInfoUnsupported
7402           NoFpRet(DAG.getMachineFunction().getFunction(),
7403                   "return versions of fp atomics not supported",
7404                   DL.getDebugLoc(), DS_Error);
7405         DAG.getContext()->diagnose(NoFpRet);
7406         return SDValue();
7407       }
7408       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7409       break;
7410     default:
7411       llvm_unreachable("unhandled atomic opcode");
7412     }
7413 
7414     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7415                                    M->getMemOperand());
7416   }
7417   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7418     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7419   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7420     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7421   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7422     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7423   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7424     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7425   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7426     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7427   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7428     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7429   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7430     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7431   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7432     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7433   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7434     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7435   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7436     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7437   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7438     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7439   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7440     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7441   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7442     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7443   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7444     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7445   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7446     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7447   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7448     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7449   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7450     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7451   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7452     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7453   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7454     return lowerStructBufferAtomicIntrin(Op, DAG,
7455                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7456   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7457     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7458   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7459     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7460   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7461     return lowerStructBufferAtomicIntrin(Op, DAG,
7462                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7463   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7464     return lowerStructBufferAtomicIntrin(Op, DAG,
7465                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7466   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7467     return lowerStructBufferAtomicIntrin(Op, DAG,
7468                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7469   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7470     return lowerStructBufferAtomicIntrin(Op, DAG,
7471                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7472   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7473     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7474   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7475     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7476   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7477     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7478   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7479     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7480   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7481     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7482 
7483   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7484     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7485     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7486     SDValue Ops[] = {
7487       Op.getOperand(0), // Chain
7488       Op.getOperand(2), // src
7489       Op.getOperand(3), // cmp
7490       Op.getOperand(4), // rsrc
7491       Op.getOperand(5), // vindex
7492       SDValue(),        // voffset -- will be set by setBufferOffsets
7493       SDValue(),        // soffset -- will be set by setBufferOffsets
7494       SDValue(),        // offset -- will be set by setBufferOffsets
7495       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7496       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7497     };
7498     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7499 
7500     EVT VT = Op.getValueType();
7501     auto *M = cast<MemSDNode>(Op);
7502     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7503 
7504     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7505                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7506   }
7507   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7508     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7509     SDValue Ops[] = {
7510       Op.getOperand(0), // Chain
7511       Op.getOperand(2), // src
7512       Op.getOperand(3), // cmp
7513       Op.getOperand(4), // rsrc
7514       DAG.getConstant(0, DL, MVT::i32), // vindex
7515       Offsets.first,    // voffset
7516       Op.getOperand(6), // soffset
7517       Offsets.second,   // offset
7518       Op.getOperand(7), // cachepolicy
7519       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7520     };
7521     EVT VT = Op.getValueType();
7522     auto *M = cast<MemSDNode>(Op);
7523     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7524 
7525     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7526                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7527   }
7528   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7529     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7530     SDValue Ops[] = {
7531       Op.getOperand(0), // Chain
7532       Op.getOperand(2), // src
7533       Op.getOperand(3), // cmp
7534       Op.getOperand(4), // rsrc
7535       Op.getOperand(5), // vindex
7536       Offsets.first,    // voffset
7537       Op.getOperand(7), // soffset
7538       Offsets.second,   // offset
7539       Op.getOperand(8), // cachepolicy
7540       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7541     };
7542     EVT VT = Op.getValueType();
7543     auto *M = cast<MemSDNode>(Op);
7544     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7545 
7546     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7547                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7548   }
7549   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7550     MemSDNode *M = cast<MemSDNode>(Op);
7551     SDValue NodePtr = M->getOperand(2);
7552     SDValue RayExtent = M->getOperand(3);
7553     SDValue RayOrigin = M->getOperand(4);
7554     SDValue RayDir = M->getOperand(5);
7555     SDValue RayInvDir = M->getOperand(6);
7556     SDValue TDescr = M->getOperand(7);
7557 
7558     assert(NodePtr.getValueType() == MVT::i32 ||
7559            NodePtr.getValueType() == MVT::i64);
7560     assert(RayDir.getValueType() == MVT::v3f16 ||
7561            RayDir.getValueType() == MVT::v3f32);
7562 
7563     if (!Subtarget->hasGFX10_AEncoding()) {
7564       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7565       return SDValue();
7566     }
7567 
7568     const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
7569     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7570     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7571     const unsigned NumVDataDwords = 4;
7572     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7573     const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
7574     const bool UseNSA =
7575         Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize();
7576     const unsigned BaseOpcodes[2][2] = {
7577         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7578         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7579          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7580     int Opcode;
7581     if (UseNSA) {
7582       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7583                                      IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA
7584                                                  : AMDGPU::MIMGEncGfx10NSA,
7585                                      NumVDataDwords, NumVAddrDwords);
7586     } else {
7587       Opcode =
7588           AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7589                                 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default
7590                                             : AMDGPU::MIMGEncGfx10Default,
7591                                 NumVDataDwords, PowerOf2Ceil(NumVAddrDwords));
7592     }
7593     assert(Opcode != -1);
7594 
7595     SmallVector<SDValue, 16> Ops;
7596 
7597     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7598       SmallVector<SDValue, 3> Lanes;
7599       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7600       if (Lanes[0].getValueSizeInBits() == 32) {
7601         for (unsigned I = 0; I < 3; ++I)
7602           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7603       } else {
7604         if (IsAligned) {
7605           Ops.push_back(
7606             DAG.getBitcast(MVT::i32,
7607                            DAG.getBuildVector(MVT::v2f16, DL,
7608                                               { Lanes[0], Lanes[1] })));
7609           Ops.push_back(Lanes[2]);
7610         } else {
7611           SDValue Elt0 = Ops.pop_back_val();
7612           Ops.push_back(
7613             DAG.getBitcast(MVT::i32,
7614                            DAG.getBuildVector(MVT::v2f16, DL,
7615                                               { Elt0, Lanes[0] })));
7616           Ops.push_back(
7617             DAG.getBitcast(MVT::i32,
7618                            DAG.getBuildVector(MVT::v2f16, DL,
7619                                               { Lanes[1], Lanes[2] })));
7620         }
7621       }
7622     };
7623 
7624     if (UseNSA && IsGFX11Plus) {
7625       Ops.push_back(NodePtr);
7626       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7627       Ops.push_back(RayOrigin);
7628       if (IsA16) {
7629         SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
7630         DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
7631         DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
7632         for (unsigned I = 0; I < 3; ++I) {
7633           MergedLanes.push_back(DAG.getBitcast(
7634               MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
7635                                            {DirLanes[I], InvDirLanes[I]})));
7636         }
7637         Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
7638       } else {
7639         Ops.push_back(RayDir);
7640         Ops.push_back(RayInvDir);
7641       }
7642     } else {
7643       if (Is64)
7644         DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
7645                                   2);
7646       else
7647         Ops.push_back(NodePtr);
7648 
7649       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7650       packLanes(RayOrigin, true);
7651       packLanes(RayDir, true);
7652       packLanes(RayInvDir, false);
7653     }
7654 
7655     if (!UseNSA) {
7656       // Build a single vector containing all the operands so far prepared.
7657       if (NumVAddrDwords > 8) {
7658         SDValue Undef = DAG.getUNDEF(MVT::i32);
7659         Ops.append(16 - Ops.size(), Undef);
7660       }
7661       assert(Ops.size() == 8 || Ops.size() == 16);
7662       SDValue MergedOps = DAG.getBuildVector(
7663           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7664       Ops.clear();
7665       Ops.push_back(MergedOps);
7666     }
7667 
7668     Ops.push_back(TDescr);
7669     if (IsA16)
7670       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7671     Ops.push_back(M->getChain());
7672 
7673     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7674     MachineMemOperand *MemRef = M->getMemOperand();
7675     DAG.setNodeMemRefs(NewNode, {MemRef});
7676     return SDValue(NewNode, 0);
7677   }
7678   case Intrinsic::amdgcn_global_atomic_fadd:
7679     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7680       DiagnosticInfoUnsupported
7681         NoFpRet(DAG.getMachineFunction().getFunction(),
7682                 "return versions of fp atomics not supported",
7683                 DL.getDebugLoc(), DS_Error);
7684       DAG.getContext()->diagnose(NoFpRet);
7685       return SDValue();
7686     }
7687     LLVM_FALLTHROUGH;
7688   case Intrinsic::amdgcn_global_atomic_fmin:
7689   case Intrinsic::amdgcn_global_atomic_fmax:
7690   case Intrinsic::amdgcn_flat_atomic_fadd:
7691   case Intrinsic::amdgcn_flat_atomic_fmin:
7692   case Intrinsic::amdgcn_flat_atomic_fmax: {
7693     MemSDNode *M = cast<MemSDNode>(Op);
7694     SDValue Ops[] = {
7695       M->getOperand(0), // Chain
7696       M->getOperand(2), // Ptr
7697       M->getOperand(3)  // Value
7698     };
7699     unsigned Opcode = 0;
7700     switch (IntrID) {
7701     case Intrinsic::amdgcn_global_atomic_fadd:
7702     case Intrinsic::amdgcn_flat_atomic_fadd: {
7703       EVT VT = Op.getOperand(3).getValueType();
7704       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7705                            DAG.getVTList(VT, MVT::Other), Ops,
7706                            M->getMemOperand());
7707     }
7708     case Intrinsic::amdgcn_global_atomic_fmin:
7709     case Intrinsic::amdgcn_flat_atomic_fmin: {
7710       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7711       break;
7712     }
7713     case Intrinsic::amdgcn_global_atomic_fmax:
7714     case Intrinsic::amdgcn_flat_atomic_fmax: {
7715       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7716       break;
7717     }
7718     default:
7719       llvm_unreachable("unhandled atomic opcode");
7720     }
7721     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7722                                    M->getVTList(), Ops, M->getMemoryVT(),
7723                                    M->getMemOperand());
7724   }
7725   default:
7726 
7727     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7728             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7729       return lowerImage(Op, ImageDimIntr, DAG, true);
7730 
7731     return SDValue();
7732   }
7733 }
7734 
7735 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7736 // dwordx4 if on SI.
7737 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7738                                               SDVTList VTList,
7739                                               ArrayRef<SDValue> Ops, EVT MemVT,
7740                                               MachineMemOperand *MMO,
7741                                               SelectionDAG &DAG) const {
7742   EVT VT = VTList.VTs[0];
7743   EVT WidenedVT = VT;
7744   EVT WidenedMemVT = MemVT;
7745   if (!Subtarget->hasDwordx3LoadStores() &&
7746       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7747     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7748                                  WidenedVT.getVectorElementType(), 4);
7749     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7750                                     WidenedMemVT.getVectorElementType(), 4);
7751     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7752   }
7753 
7754   assert(VTList.NumVTs == 2);
7755   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7756 
7757   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7758                                        WidenedMemVT, MMO);
7759   if (WidenedVT != VT) {
7760     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7761                                DAG.getVectorIdxConstant(0, DL));
7762     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7763   }
7764   return NewOp;
7765 }
7766 
7767 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7768                                          bool ImageStore) const {
7769   EVT StoreVT = VData.getValueType();
7770 
7771   // No change for f16 and legal vector D16 types.
7772   if (!StoreVT.isVector())
7773     return VData;
7774 
7775   SDLoc DL(VData);
7776   unsigned NumElements = StoreVT.getVectorNumElements();
7777 
7778   if (Subtarget->hasUnpackedD16VMem()) {
7779     // We need to unpack the packed data to store.
7780     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7781     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7782 
7783     EVT EquivStoreVT =
7784         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7785     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7786     return DAG.UnrollVectorOp(ZExt.getNode());
7787   }
7788 
7789   // The sq block of gfx8.1 does not estimate register use correctly for d16
7790   // image store instructions. The data operand is computed as if it were not a
7791   // d16 image instruction.
7792   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7793     // Bitcast to i16
7794     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7795     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7796 
7797     // Decompose into scalars
7798     SmallVector<SDValue, 4> Elts;
7799     DAG.ExtractVectorElements(IntVData, Elts);
7800 
7801     // Group pairs of i16 into v2i16 and bitcast to i32
7802     SmallVector<SDValue, 4> PackedElts;
7803     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7804       SDValue Pair =
7805           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7806       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7807       PackedElts.push_back(IntPair);
7808     }
7809     if ((NumElements % 2) == 1) {
7810       // Handle v3i16
7811       unsigned I = Elts.size() / 2;
7812       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7813                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7814       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7815       PackedElts.push_back(IntPair);
7816     }
7817 
7818     // Pad using UNDEF
7819     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7820 
7821     // Build final vector
7822     EVT VecVT =
7823         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7824     return DAG.getBuildVector(VecVT, DL, PackedElts);
7825   }
7826 
7827   if (NumElements == 3) {
7828     EVT IntStoreVT =
7829         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7830     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7831 
7832     EVT WidenedStoreVT = EVT::getVectorVT(
7833         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7834     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7835                                          WidenedStoreVT.getStoreSizeInBits());
7836     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7837     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7838   }
7839 
7840   assert(isTypeLegal(StoreVT));
7841   return VData;
7842 }
7843 
7844 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7845                                               SelectionDAG &DAG) const {
7846   SDLoc DL(Op);
7847   SDValue Chain = Op.getOperand(0);
7848   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7849   MachineFunction &MF = DAG.getMachineFunction();
7850 
7851   switch (IntrinsicID) {
7852   case Intrinsic::amdgcn_exp_compr: {
7853     SDValue Src0 = Op.getOperand(4);
7854     SDValue Src1 = Op.getOperand(5);
7855     // Hack around illegal type on SI by directly selecting it.
7856     if (isTypeLegal(Src0.getValueType()))
7857       return SDValue();
7858 
7859     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7860     SDValue Undef = DAG.getUNDEF(MVT::f32);
7861     const SDValue Ops[] = {
7862       Op.getOperand(2), // tgt
7863       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7864       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7865       Undef, // src2
7866       Undef, // src3
7867       Op.getOperand(7), // vm
7868       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7869       Op.getOperand(3), // en
7870       Op.getOperand(0) // Chain
7871     };
7872 
7873     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7874     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7875   }
7876   case Intrinsic::amdgcn_s_barrier: {
7877     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7878       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7879       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7880       if (WGSize <= ST.getWavefrontSize())
7881         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7882                                           Op.getOperand(0)), 0);
7883     }
7884     return SDValue();
7885   };
7886   case Intrinsic::amdgcn_tbuffer_store: {
7887     SDValue VData = Op.getOperand(2);
7888     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7889     if (IsD16)
7890       VData = handleD16VData(VData, DAG);
7891     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7892     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7893     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7894     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7895     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7896     SDValue Ops[] = {
7897       Chain,
7898       VData,             // vdata
7899       Op.getOperand(3),  // rsrc
7900       Op.getOperand(4),  // vindex
7901       Op.getOperand(5),  // voffset
7902       Op.getOperand(6),  // soffset
7903       Op.getOperand(7),  // offset
7904       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7905       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7906       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7907     };
7908     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7909                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7910     MemSDNode *M = cast<MemSDNode>(Op);
7911     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7912                                    M->getMemoryVT(), M->getMemOperand());
7913   }
7914 
7915   case Intrinsic::amdgcn_struct_tbuffer_store: {
7916     SDValue VData = Op.getOperand(2);
7917     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7918     if (IsD16)
7919       VData = handleD16VData(VData, DAG);
7920     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7921     SDValue Ops[] = {
7922       Chain,
7923       VData,             // vdata
7924       Op.getOperand(3),  // rsrc
7925       Op.getOperand(4),  // vindex
7926       Offsets.first,     // voffset
7927       Op.getOperand(6),  // soffset
7928       Offsets.second,    // offset
7929       Op.getOperand(7),  // format
7930       Op.getOperand(8),  // cachepolicy, swizzled buffer
7931       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7932     };
7933     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7934                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7935     MemSDNode *M = cast<MemSDNode>(Op);
7936     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7937                                    M->getMemoryVT(), M->getMemOperand());
7938   }
7939 
7940   case Intrinsic::amdgcn_raw_tbuffer_store: {
7941     SDValue VData = Op.getOperand(2);
7942     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7943     if (IsD16)
7944       VData = handleD16VData(VData, DAG);
7945     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7946     SDValue Ops[] = {
7947       Chain,
7948       VData,             // vdata
7949       Op.getOperand(3),  // rsrc
7950       DAG.getConstant(0, DL, MVT::i32), // vindex
7951       Offsets.first,     // voffset
7952       Op.getOperand(5),  // soffset
7953       Offsets.second,    // offset
7954       Op.getOperand(6),  // format
7955       Op.getOperand(7),  // cachepolicy, swizzled buffer
7956       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7957     };
7958     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7959                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7960     MemSDNode *M = cast<MemSDNode>(Op);
7961     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7962                                    M->getMemoryVT(), M->getMemOperand());
7963   }
7964 
7965   case Intrinsic::amdgcn_buffer_store:
7966   case Intrinsic::amdgcn_buffer_store_format: {
7967     SDValue VData = Op.getOperand(2);
7968     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7969     if (IsD16)
7970       VData = handleD16VData(VData, DAG);
7971     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7972     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7973     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7974     SDValue Ops[] = {
7975       Chain,
7976       VData,
7977       Op.getOperand(3), // rsrc
7978       Op.getOperand(4), // vindex
7979       SDValue(), // voffset -- will be set by setBufferOffsets
7980       SDValue(), // soffset -- will be set by setBufferOffsets
7981       SDValue(), // offset -- will be set by setBufferOffsets
7982       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7983       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7984     };
7985     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7986 
7987     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7988                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7989     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7990     MemSDNode *M = cast<MemSDNode>(Op);
7991     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7992 
7993     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7994     EVT VDataType = VData.getValueType().getScalarType();
7995     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7996       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7997 
7998     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7999                                    M->getMemoryVT(), M->getMemOperand());
8000   }
8001 
8002   case Intrinsic::amdgcn_raw_buffer_store:
8003   case Intrinsic::amdgcn_raw_buffer_store_format: {
8004     const bool IsFormat =
8005         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8006 
8007     SDValue VData = Op.getOperand(2);
8008     EVT VDataVT = VData.getValueType();
8009     EVT EltType = VDataVT.getScalarType();
8010     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8011     if (IsD16) {
8012       VData = handleD16VData(VData, DAG);
8013       VDataVT = VData.getValueType();
8014     }
8015 
8016     if (!isTypeLegal(VDataVT)) {
8017       VData =
8018           DAG.getNode(ISD::BITCAST, DL,
8019                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8020     }
8021 
8022     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8023     SDValue Ops[] = {
8024       Chain,
8025       VData,
8026       Op.getOperand(3), // rsrc
8027       DAG.getConstant(0, DL, MVT::i32), // vindex
8028       Offsets.first,    // voffset
8029       Op.getOperand(5), // soffset
8030       Offsets.second,   // offset
8031       Op.getOperand(6), // cachepolicy, swizzled buffer
8032       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8033     };
8034     unsigned Opc =
8035         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8036     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8037     MemSDNode *M = cast<MemSDNode>(Op);
8038     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8039 
8040     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8041     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8042       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8043 
8044     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8045                                    M->getMemoryVT(), M->getMemOperand());
8046   }
8047 
8048   case Intrinsic::amdgcn_struct_buffer_store:
8049   case Intrinsic::amdgcn_struct_buffer_store_format: {
8050     const bool IsFormat =
8051         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8052 
8053     SDValue VData = Op.getOperand(2);
8054     EVT VDataVT = VData.getValueType();
8055     EVT EltType = VDataVT.getScalarType();
8056     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8057 
8058     if (IsD16) {
8059       VData = handleD16VData(VData, DAG);
8060       VDataVT = VData.getValueType();
8061     }
8062 
8063     if (!isTypeLegal(VDataVT)) {
8064       VData =
8065           DAG.getNode(ISD::BITCAST, DL,
8066                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8067     }
8068 
8069     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8070     SDValue Ops[] = {
8071       Chain,
8072       VData,
8073       Op.getOperand(3), // rsrc
8074       Op.getOperand(4), // vindex
8075       Offsets.first,    // voffset
8076       Op.getOperand(6), // soffset
8077       Offsets.second,   // offset
8078       Op.getOperand(7), // cachepolicy, swizzled buffer
8079       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8080     };
8081     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8082                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8083     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8084     MemSDNode *M = cast<MemSDNode>(Op);
8085     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8086 
8087     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8088     EVT VDataType = VData.getValueType().getScalarType();
8089     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8090       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8091 
8092     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8093                                    M->getMemoryVT(), M->getMemOperand());
8094   }
8095   case Intrinsic::amdgcn_raw_buffer_load_lds:
8096   case Intrinsic::amdgcn_struct_buffer_load_lds: {
8097     unsigned Opc;
8098     bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8099     unsigned OpOffset = HasVIndex ? 1 : 0;
8100     SDValue VOffset = Op.getOperand(5 + OpOffset);
8101     auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8102     bool HasVOffset = !CVOffset || !CVOffset->isZero();
8103     unsigned Size = Op->getConstantOperandVal(4);
8104 
8105     switch (Size) {
8106     default:
8107       return SDValue();
8108     case 1:
8109       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8110                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8111                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8112                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8113       break;
8114     case 2:
8115       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8116                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8117                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8118                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8119       break;
8120     case 4:
8121       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8122                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8123                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8124                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8125       break;
8126     }
8127 
8128     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8129 
8130     SmallVector<SDValue, 8> Ops;
8131 
8132     if (HasVIndex && HasVOffset)
8133       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8134                                        { Op.getOperand(5), // VIndex
8135                                          VOffset }));
8136     else if (HasVIndex)
8137       Ops.push_back(Op.getOperand(5));
8138     else if (HasVOffset)
8139       Ops.push_back(VOffset);
8140 
8141     Ops.push_back(Op.getOperand(2));           // rsrc
8142     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8143     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8144     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8145     Ops.push_back(
8146       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8147     Ops.push_back(
8148       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
8149     Ops.push_back(M0Val.getValue(0)); // Chain
8150     Ops.push_back(M0Val.getValue(1)); // Glue
8151 
8152     auto *M = cast<MemSDNode>(Op);
8153     MachineMemOperand *LoadMMO = M->getMemOperand();
8154     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8155     LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8156     MachinePointerInfo StorePtrI = LoadPtrI;
8157     StorePtrI.V = nullptr;
8158     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8159 
8160     auto F = LoadMMO->getFlags() &
8161              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8162     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8163                                       Size, LoadMMO->getBaseAlign());
8164 
8165     MachineMemOperand *StoreMMO =
8166         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8167                                 sizeof(int32_t), LoadMMO->getBaseAlign());
8168 
8169     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8170     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8171 
8172     return SDValue(Load, 0);
8173   }
8174   case Intrinsic::amdgcn_global_load_lds: {
8175     unsigned Opc;
8176     unsigned Size = Op->getConstantOperandVal(4);
8177     switch (Size) {
8178     default:
8179       return SDValue();
8180     case 1:
8181       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8182       break;
8183     case 2:
8184       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8185       break;
8186     case 4:
8187       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8188       break;
8189     }
8190 
8191     auto *M = cast<MemSDNode>(Op);
8192     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8193 
8194     SmallVector<SDValue, 6> Ops;
8195 
8196     SDValue Addr = Op.getOperand(2); // Global ptr
8197     SDValue VOffset;
8198     // Try to split SAddr and VOffset. Global and LDS pointers share the same
8199     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8200     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8201       SDValue LHS = Addr.getOperand(0);
8202       SDValue RHS = Addr.getOperand(1);
8203 
8204       if (LHS->isDivergent())
8205         std::swap(LHS, RHS);
8206 
8207       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8208           RHS.getOperand(0).getValueType() == MVT::i32) {
8209         // add (i64 sgpr), (zero_extend (i32 vgpr))
8210         Addr = LHS;
8211         VOffset = RHS.getOperand(0);
8212       }
8213     }
8214 
8215     Ops.push_back(Addr);
8216     if (!Addr->isDivergent()) {
8217       Opc = AMDGPU::getGlobalSaddrOp(Opc);
8218       if (!VOffset)
8219         VOffset = SDValue(
8220             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8221                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8222       Ops.push_back(VOffset);
8223     }
8224 
8225     Ops.push_back(Op.getOperand(5));  // Offset
8226     Ops.push_back(Op.getOperand(6));  // CPol
8227     Ops.push_back(M0Val.getValue(0)); // Chain
8228     Ops.push_back(M0Val.getValue(1)); // Glue
8229 
8230     MachineMemOperand *LoadMMO = M->getMemOperand();
8231     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8232     LoadPtrI.Offset = Op->getConstantOperandVal(5);
8233     MachinePointerInfo StorePtrI = LoadPtrI;
8234     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8235     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8236     auto F = LoadMMO->getFlags() &
8237              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8238     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8239                                       Size, LoadMMO->getBaseAlign());
8240     MachineMemOperand *StoreMMO =
8241         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8242                                 sizeof(int32_t), Align(4));
8243 
8244     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8245     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8246 
8247     return SDValue(Load, 0);
8248   }
8249   case Intrinsic::amdgcn_end_cf:
8250     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8251                                       Op->getOperand(2), Chain), 0);
8252 
8253   default: {
8254     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8255             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8256       return lowerImage(Op, ImageDimIntr, DAG, true);
8257 
8258     return Op;
8259   }
8260   }
8261 }
8262 
8263 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8264 // offset (the offset that is included in bounds checking and swizzling, to be
8265 // split between the instruction's voffset and immoffset fields) and soffset
8266 // (the offset that is excluded from bounds checking and swizzling, to go in
8267 // the instruction's soffset field).  This function takes the first kind of
8268 // offset and figures out how to split it between voffset and immoffset.
8269 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8270     SDValue Offset, SelectionDAG &DAG) const {
8271   SDLoc DL(Offset);
8272   const unsigned MaxImm = 4095;
8273   SDValue N0 = Offset;
8274   ConstantSDNode *C1 = nullptr;
8275 
8276   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8277     N0 = SDValue();
8278   else if (DAG.isBaseWithConstantOffset(N0)) {
8279     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8280     N0 = N0.getOperand(0);
8281   }
8282 
8283   if (C1) {
8284     unsigned ImmOffset = C1->getZExtValue();
8285     // If the immediate value is too big for the immoffset field, put the value
8286     // and -4096 into the immoffset field so that the value that is copied/added
8287     // for the voffset field is a multiple of 4096, and it stands more chance
8288     // of being CSEd with the copy/add for another similar load/store.
8289     // However, do not do that rounding down to a multiple of 4096 if that is a
8290     // negative number, as it appears to be illegal to have a negative offset
8291     // in the vgpr, even if adding the immediate offset makes it positive.
8292     unsigned Overflow = ImmOffset & ~MaxImm;
8293     ImmOffset -= Overflow;
8294     if ((int32_t)Overflow < 0) {
8295       Overflow += ImmOffset;
8296       ImmOffset = 0;
8297     }
8298     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8299     if (Overflow) {
8300       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8301       if (!N0)
8302         N0 = OverflowVal;
8303       else {
8304         SDValue Ops[] = { N0, OverflowVal };
8305         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8306       }
8307     }
8308   }
8309   if (!N0)
8310     N0 = DAG.getConstant(0, DL, MVT::i32);
8311   if (!C1)
8312     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8313   return {N0, SDValue(C1, 0)};
8314 }
8315 
8316 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8317 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8318 // pointed to by Offsets.
8319 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8320                                         SelectionDAG &DAG, SDValue *Offsets,
8321                                         Align Alignment) const {
8322   SDLoc DL(CombinedOffset);
8323   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8324     uint32_t Imm = C->getZExtValue();
8325     uint32_t SOffset, ImmOffset;
8326     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8327                                  Alignment)) {
8328       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8329       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8330       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8331       return;
8332     }
8333   }
8334   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8335     SDValue N0 = CombinedOffset.getOperand(0);
8336     SDValue N1 = CombinedOffset.getOperand(1);
8337     uint32_t SOffset, ImmOffset;
8338     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8339     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8340                                                 Subtarget, Alignment)) {
8341       Offsets[0] = N0;
8342       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8343       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8344       return;
8345     }
8346   }
8347   Offsets[0] = CombinedOffset;
8348   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8349   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8350 }
8351 
8352 // Handle 8 bit and 16 bit buffer loads
8353 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8354                                                      EVT LoadVT, SDLoc DL,
8355                                                      ArrayRef<SDValue> Ops,
8356                                                      MemSDNode *M) const {
8357   EVT IntVT = LoadVT.changeTypeToInteger();
8358   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8359          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8360 
8361   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8362   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8363                                                Ops, IntVT,
8364                                                M->getMemOperand());
8365   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8366   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8367 
8368   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8369 }
8370 
8371 // Handle 8 bit and 16 bit buffer stores
8372 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8373                                                       EVT VDataType, SDLoc DL,
8374                                                       SDValue Ops[],
8375                                                       MemSDNode *M) const {
8376   if (VDataType == MVT::f16)
8377     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8378 
8379   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8380   Ops[1] = BufferStoreExt;
8381   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8382                                  AMDGPUISD::BUFFER_STORE_SHORT;
8383   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8384   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8385                                      M->getMemOperand());
8386 }
8387 
8388 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8389                                  ISD::LoadExtType ExtType, SDValue Op,
8390                                  const SDLoc &SL, EVT VT) {
8391   if (VT.bitsLT(Op.getValueType()))
8392     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8393 
8394   switch (ExtType) {
8395   case ISD::SEXTLOAD:
8396     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8397   case ISD::ZEXTLOAD:
8398     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8399   case ISD::EXTLOAD:
8400     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8401   case ISD::NON_EXTLOAD:
8402     return Op;
8403   }
8404 
8405   llvm_unreachable("invalid ext type");
8406 }
8407 
8408 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8409   SelectionDAG &DAG = DCI.DAG;
8410   if (Ld->getAlign() < Align(4) || Ld->isDivergent())
8411     return SDValue();
8412 
8413   // FIXME: Constant loads should all be marked invariant.
8414   unsigned AS = Ld->getAddressSpace();
8415   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8416       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8417       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8418     return SDValue();
8419 
8420   // Don't do this early, since it may interfere with adjacent load merging for
8421   // illegal types. We can avoid losing alignment information for exotic types
8422   // pre-legalize.
8423   EVT MemVT = Ld->getMemoryVT();
8424   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8425       MemVT.getSizeInBits() >= 32)
8426     return SDValue();
8427 
8428   SDLoc SL(Ld);
8429 
8430   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8431          "unexpected vector extload");
8432 
8433   // TODO: Drop only high part of range.
8434   SDValue Ptr = Ld->getBasePtr();
8435   SDValue NewLoad = DAG.getLoad(
8436       ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
8437       Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
8438       Ld->getMemOperand()->getFlags(), Ld->getAAInfo(),
8439       nullptr); // Drop ranges
8440 
8441   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8442   if (MemVT.isFloatingPoint()) {
8443     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8444            "unexpected fp extload");
8445     TruncVT = MemVT.changeTypeToInteger();
8446   }
8447 
8448   SDValue Cvt = NewLoad;
8449   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8450     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8451                       DAG.getValueType(TruncVT));
8452   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8453              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8454     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8455   } else {
8456     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8457   }
8458 
8459   EVT VT = Ld->getValueType(0);
8460   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8461 
8462   DCI.AddToWorklist(Cvt.getNode());
8463 
8464   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8465   // the appropriate extension from the 32-bit load.
8466   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8467   DCI.AddToWorklist(Cvt.getNode());
8468 
8469   // Handle conversion back to floating point if necessary.
8470   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8471 
8472   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8473 }
8474 
8475 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8476   SDLoc DL(Op);
8477   LoadSDNode *Load = cast<LoadSDNode>(Op);
8478   ISD::LoadExtType ExtType = Load->getExtensionType();
8479   EVT MemVT = Load->getMemoryVT();
8480 
8481   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8482     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8483       return SDValue();
8484 
8485     // FIXME: Copied from PPC
8486     // First, load into 32 bits, then truncate to 1 bit.
8487 
8488     SDValue Chain = Load->getChain();
8489     SDValue BasePtr = Load->getBasePtr();
8490     MachineMemOperand *MMO = Load->getMemOperand();
8491 
8492     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8493 
8494     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8495                                    BasePtr, RealMemVT, MMO);
8496 
8497     if (!MemVT.isVector()) {
8498       SDValue Ops[] = {
8499         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8500         NewLD.getValue(1)
8501       };
8502 
8503       return DAG.getMergeValues(Ops, DL);
8504     }
8505 
8506     SmallVector<SDValue, 3> Elts;
8507     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8508       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8509                                 DAG.getConstant(I, DL, MVT::i32));
8510 
8511       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8512     }
8513 
8514     SDValue Ops[] = {
8515       DAG.getBuildVector(MemVT, DL, Elts),
8516       NewLD.getValue(1)
8517     };
8518 
8519     return DAG.getMergeValues(Ops, DL);
8520   }
8521 
8522   if (!MemVT.isVector())
8523     return SDValue();
8524 
8525   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8526          "Custom lowering for non-i32 vectors hasn't been implemented.");
8527 
8528   Align Alignment = Load->getAlign();
8529   unsigned AS = Load->getAddressSpace();
8530   if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS &&
8531       Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8532     return SplitVectorLoad(Op, DAG);
8533   }
8534 
8535   MachineFunction &MF = DAG.getMachineFunction();
8536   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8537   // If there is a possibility that flat instruction access scratch memory
8538   // then we need to use the same legalization rules we use for private.
8539   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8540       !Subtarget->hasMultiDwordFlatScratchAddressing())
8541     AS = MFI->hasFlatScratchInit() ?
8542          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8543 
8544   unsigned NumElements = MemVT.getVectorNumElements();
8545 
8546   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8547       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8548     if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) {
8549       if (MemVT.isPow2VectorType())
8550         return SDValue();
8551       return WidenOrSplitVectorLoad(Op, DAG);
8552     }
8553     // Non-uniform loads will be selected to MUBUF instructions, so they
8554     // have the same legalization requirements as global and private
8555     // loads.
8556     //
8557   }
8558 
8559   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8560       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8561       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8562     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8563         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8564         Alignment >= Align(4) && NumElements < 32) {
8565       if (MemVT.isPow2VectorType())
8566         return SDValue();
8567       return WidenOrSplitVectorLoad(Op, DAG);
8568     }
8569     // Non-uniform loads will be selected to MUBUF instructions, so they
8570     // have the same legalization requirements as global and private
8571     // loads.
8572     //
8573   }
8574   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8575       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8576       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8577       AS == AMDGPUAS::FLAT_ADDRESS) {
8578     if (NumElements > 4)
8579       return SplitVectorLoad(Op, DAG);
8580     // v3 loads not supported on SI.
8581     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8582       return WidenOrSplitVectorLoad(Op, DAG);
8583 
8584     // v3 and v4 loads are supported for private and global memory.
8585     return SDValue();
8586   }
8587   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8588     // Depending on the setting of the private_element_size field in the
8589     // resource descriptor, we can only make private accesses up to a certain
8590     // size.
8591     switch (Subtarget->getMaxPrivateElementSize()) {
8592     case 4: {
8593       SDValue Ops[2];
8594       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8595       return DAG.getMergeValues(Ops, DL);
8596     }
8597     case 8:
8598       if (NumElements > 2)
8599         return SplitVectorLoad(Op, DAG);
8600       return SDValue();
8601     case 16:
8602       // Same as global/flat
8603       if (NumElements > 4)
8604         return SplitVectorLoad(Op, DAG);
8605       // v3 loads not supported on SI.
8606       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8607         return WidenOrSplitVectorLoad(Op, DAG);
8608 
8609       return SDValue();
8610     default:
8611       llvm_unreachable("unsupported private_element_size");
8612     }
8613   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8614     bool Fast = false;
8615     auto Flags = Load->getMemOperand()->getFlags();
8616     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8617                                            Load->getAlign(), Flags, &Fast) &&
8618         Fast)
8619       return SDValue();
8620 
8621     if (MemVT.isVector())
8622       return SplitVectorLoad(Op, DAG);
8623   }
8624 
8625   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8626                                       MemVT, *Load->getMemOperand())) {
8627     SDValue Ops[2];
8628     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8629     return DAG.getMergeValues(Ops, DL);
8630   }
8631 
8632   return SDValue();
8633 }
8634 
8635 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8636   EVT VT = Op.getValueType();
8637   if (VT.getSizeInBits() == 128)
8638     return splitTernaryVectorOp(Op, DAG);
8639 
8640   assert(VT.getSizeInBits() == 64);
8641 
8642   SDLoc DL(Op);
8643   SDValue Cond = Op.getOperand(0);
8644 
8645   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8646   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8647 
8648   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8649   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8650 
8651   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8652   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8653 
8654   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8655 
8656   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8657   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8658 
8659   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8660 
8661   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8662   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8663 }
8664 
8665 // Catch division cases where we can use shortcuts with rcp and rsq
8666 // instructions.
8667 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8668                                               SelectionDAG &DAG) const {
8669   SDLoc SL(Op);
8670   SDValue LHS = Op.getOperand(0);
8671   SDValue RHS = Op.getOperand(1);
8672   EVT VT = Op.getValueType();
8673   const SDNodeFlags Flags = Op->getFlags();
8674 
8675   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8676 
8677   // Without !fpmath accuracy information, we can't do more because we don't
8678   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8679   if (!AllowInaccurateRcp)
8680     return SDValue();
8681 
8682   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8683     if (CLHS->isExactlyValue(1.0)) {
8684       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8685       // the CI documentation has a worst case error of 1 ulp.
8686       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8687       // use it as long as we aren't trying to use denormals.
8688       //
8689       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8690 
8691       // 1.0 / sqrt(x) -> rsq(x)
8692 
8693       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8694       // error seems really high at 2^29 ULP.
8695       if (RHS.getOpcode() == ISD::FSQRT)
8696         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8697 
8698       // 1.0 / x -> rcp(x)
8699       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8700     }
8701 
8702     // Same as for 1.0, but expand the sign out of the constant.
8703     if (CLHS->isExactlyValue(-1.0)) {
8704       // -1.0 / x -> rcp (fneg x)
8705       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8706       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8707     }
8708   }
8709 
8710   // Turn into multiply by the reciprocal.
8711   // x / y -> x * (1.0 / y)
8712   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8713   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8714 }
8715 
8716 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8717                                                 SelectionDAG &DAG) const {
8718   SDLoc SL(Op);
8719   SDValue X = Op.getOperand(0);
8720   SDValue Y = Op.getOperand(1);
8721   EVT VT = Op.getValueType();
8722   const SDNodeFlags Flags = Op->getFlags();
8723 
8724   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8725                             DAG.getTarget().Options.UnsafeFPMath;
8726   if (!AllowInaccurateDiv)
8727     return SDValue();
8728 
8729   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8730   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8731 
8732   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8733   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8734 
8735   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8736   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8737   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8738   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8739   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8740   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8741 }
8742 
8743 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8744                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8745                           SDNodeFlags Flags) {
8746   if (GlueChain->getNumValues() <= 1) {
8747     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8748   }
8749 
8750   assert(GlueChain->getNumValues() == 3);
8751 
8752   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8753   switch (Opcode) {
8754   default: llvm_unreachable("no chain equivalent for opcode");
8755   case ISD::FMUL:
8756     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8757     break;
8758   }
8759 
8760   return DAG.getNode(Opcode, SL, VTList,
8761                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8762                      Flags);
8763 }
8764 
8765 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8766                            EVT VT, SDValue A, SDValue B, SDValue C,
8767                            SDValue GlueChain, SDNodeFlags Flags) {
8768   if (GlueChain->getNumValues() <= 1) {
8769     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8770   }
8771 
8772   assert(GlueChain->getNumValues() == 3);
8773 
8774   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8775   switch (Opcode) {
8776   default: llvm_unreachable("no chain equivalent for opcode");
8777   case ISD::FMA:
8778     Opcode = AMDGPUISD::FMA_W_CHAIN;
8779     break;
8780   }
8781 
8782   return DAG.getNode(Opcode, SL, VTList,
8783                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8784                      Flags);
8785 }
8786 
8787 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8788   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8789     return FastLowered;
8790 
8791   SDLoc SL(Op);
8792   SDValue Src0 = Op.getOperand(0);
8793   SDValue Src1 = Op.getOperand(1);
8794 
8795   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8796   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8797 
8798   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8799   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8800 
8801   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8802   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8803 
8804   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8805 }
8806 
8807 // Faster 2.5 ULP division that does not support denormals.
8808 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8809   SDLoc SL(Op);
8810   SDValue LHS = Op.getOperand(1);
8811   SDValue RHS = Op.getOperand(2);
8812 
8813   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8814 
8815   const APFloat K0Val(BitsToFloat(0x6f800000));
8816   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8817 
8818   const APFloat K1Val(BitsToFloat(0x2f800000));
8819   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8820 
8821   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8822 
8823   EVT SetCCVT =
8824     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8825 
8826   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8827 
8828   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8829 
8830   // TODO: Should this propagate fast-math-flags?
8831   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8832 
8833   // rcp does not support denormals.
8834   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8835 
8836   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8837 
8838   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8839 }
8840 
8841 // Returns immediate value for setting the F32 denorm mode when using the
8842 // S_DENORM_MODE instruction.
8843 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8844                                     const SDLoc &SL, const GCNSubtarget *ST) {
8845   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8846   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8847                                 ? FP_DENORM_FLUSH_NONE
8848                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8849 
8850   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8851   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8852 }
8853 
8854 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8855   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8856     return FastLowered;
8857 
8858   // The selection matcher assumes anything with a chain selecting to a
8859   // mayRaiseFPException machine instruction. Since we're introducing a chain
8860   // here, we need to explicitly report nofpexcept for the regular fdiv
8861   // lowering.
8862   SDNodeFlags Flags = Op->getFlags();
8863   Flags.setNoFPExcept(true);
8864 
8865   SDLoc SL(Op);
8866   SDValue LHS = Op.getOperand(0);
8867   SDValue RHS = Op.getOperand(1);
8868 
8869   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8870 
8871   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8872 
8873   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8874                                           {RHS, RHS, LHS}, Flags);
8875   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8876                                         {LHS, RHS, LHS}, Flags);
8877 
8878   // Denominator is scaled to not be denormal, so using rcp is ok.
8879   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8880                                   DenominatorScaled, Flags);
8881   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8882                                      DenominatorScaled, Flags);
8883 
8884   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8885                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8886                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8887   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8888 
8889   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8890 
8891   if (!HasFP32Denormals) {
8892     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8893     // lowering. The chain dependence is insufficient, and we need glue. We do
8894     // not need the glue variants in a strictfp function.
8895 
8896     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8897 
8898     SDNode *EnableDenorm;
8899     if (Subtarget->hasDenormModeInst()) {
8900       const SDValue EnableDenormValue =
8901           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8902 
8903       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8904                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8905     } else {
8906       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8907                                                         SL, MVT::i32);
8908       EnableDenorm =
8909           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8910                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8911     }
8912 
8913     SDValue Ops[3] = {
8914       NegDivScale0,
8915       SDValue(EnableDenorm, 0),
8916       SDValue(EnableDenorm, 1)
8917     };
8918 
8919     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8920   }
8921 
8922   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8923                              ApproxRcp, One, NegDivScale0, Flags);
8924 
8925   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8926                              ApproxRcp, Fma0, Flags);
8927 
8928   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8929                            Fma1, Fma1, Flags);
8930 
8931   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8932                              NumeratorScaled, Mul, Flags);
8933 
8934   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8935                              Fma2, Fma1, Mul, Fma2, Flags);
8936 
8937   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8938                              NumeratorScaled, Fma3, Flags);
8939 
8940   if (!HasFP32Denormals) {
8941     SDNode *DisableDenorm;
8942     if (Subtarget->hasDenormModeInst()) {
8943       const SDValue DisableDenormValue =
8944           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8945 
8946       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8947                                   Fma4.getValue(1), DisableDenormValue,
8948                                   Fma4.getValue(2)).getNode();
8949     } else {
8950       const SDValue DisableDenormValue =
8951           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8952 
8953       DisableDenorm = DAG.getMachineNode(
8954           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8955           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8956     }
8957 
8958     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8959                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8960     DAG.setRoot(OutputChain);
8961   }
8962 
8963   SDValue Scale = NumeratorScaled.getValue(1);
8964   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8965                              {Fma4, Fma1, Fma3, Scale}, Flags);
8966 
8967   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8968 }
8969 
8970 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8971   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8972     return FastLowered;
8973 
8974   SDLoc SL(Op);
8975   SDValue X = Op.getOperand(0);
8976   SDValue Y = Op.getOperand(1);
8977 
8978   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8979 
8980   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8981 
8982   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8983 
8984   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8985 
8986   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8987 
8988   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8989 
8990   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8991 
8992   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8993 
8994   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8995 
8996   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8997   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8998 
8999   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
9000                              NegDivScale0, Mul, DivScale1);
9001 
9002   SDValue Scale;
9003 
9004   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
9005     // Workaround a hardware bug on SI where the condition output from div_scale
9006     // is not usable.
9007 
9008     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
9009 
9010     // Figure out if the scale to use for div_fmas.
9011     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
9012     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
9013     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
9014     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
9015 
9016     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
9017     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
9018 
9019     SDValue Scale0Hi
9020       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
9021     SDValue Scale1Hi
9022       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
9023 
9024     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
9025     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
9026     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9027   } else {
9028     Scale = DivScale1.getValue(1);
9029   }
9030 
9031   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9032                              Fma4, Fma3, Mul, Scale);
9033 
9034   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9035 }
9036 
9037 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9038   EVT VT = Op.getValueType();
9039 
9040   if (VT == MVT::f32)
9041     return LowerFDIV32(Op, DAG);
9042 
9043   if (VT == MVT::f64)
9044     return LowerFDIV64(Op, DAG);
9045 
9046   if (VT == MVT::f16)
9047     return LowerFDIV16(Op, DAG);
9048 
9049   llvm_unreachable("Unexpected type for fdiv");
9050 }
9051 
9052 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9053   SDLoc DL(Op);
9054   StoreSDNode *Store = cast<StoreSDNode>(Op);
9055   EVT VT = Store->getMemoryVT();
9056 
9057   if (VT == MVT::i1) {
9058     return DAG.getTruncStore(Store->getChain(), DL,
9059        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9060        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9061   }
9062 
9063   assert(VT.isVector() &&
9064          Store->getValue().getValueType().getScalarType() == MVT::i32);
9065 
9066   unsigned AS = Store->getAddressSpace();
9067   if (Subtarget->hasLDSMisalignedBug() &&
9068       AS == AMDGPUAS::FLAT_ADDRESS &&
9069       Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9070     return SplitVectorStore(Op, DAG);
9071   }
9072 
9073   MachineFunction &MF = DAG.getMachineFunction();
9074   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9075   // If there is a possibility that flat instruction access scratch memory
9076   // then we need to use the same legalization rules we use for private.
9077   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9078       !Subtarget->hasMultiDwordFlatScratchAddressing())
9079     AS = MFI->hasFlatScratchInit() ?
9080          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9081 
9082   unsigned NumElements = VT.getVectorNumElements();
9083   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9084       AS == AMDGPUAS::FLAT_ADDRESS) {
9085     if (NumElements > 4)
9086       return SplitVectorStore(Op, DAG);
9087     // v3 stores not supported on SI.
9088     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9089       return SplitVectorStore(Op, DAG);
9090 
9091     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9092                                         VT, *Store->getMemOperand()))
9093       return expandUnalignedStore(Store, DAG);
9094 
9095     return SDValue();
9096   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9097     switch (Subtarget->getMaxPrivateElementSize()) {
9098     case 4:
9099       return scalarizeVectorStore(Store, DAG);
9100     case 8:
9101       if (NumElements > 2)
9102         return SplitVectorStore(Op, DAG);
9103       return SDValue();
9104     case 16:
9105       if (NumElements > 4 ||
9106           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9107         return SplitVectorStore(Op, DAG);
9108       return SDValue();
9109     default:
9110       llvm_unreachable("unsupported private_element_size");
9111     }
9112   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9113     bool Fast = false;
9114     auto Flags = Store->getMemOperand()->getFlags();
9115     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9116                                            Store->getAlign(), Flags, &Fast) &&
9117         Fast)
9118       return SDValue();
9119 
9120     if (VT.isVector())
9121       return SplitVectorStore(Op, DAG);
9122 
9123     return expandUnalignedStore(Store, DAG);
9124   }
9125 
9126   // Probably an invalid store. If so we'll end up emitting a selection error.
9127   return SDValue();
9128 }
9129 
9130 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9131   SDLoc DL(Op);
9132   EVT VT = Op.getValueType();
9133   SDValue Arg = Op.getOperand(0);
9134   SDValue TrigVal;
9135 
9136   // Propagate fast-math flags so that the multiply we introduce can be folded
9137   // if Arg is already the result of a multiply by constant.
9138   auto Flags = Op->getFlags();
9139 
9140   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9141 
9142   if (Subtarget->hasTrigReducedRange()) {
9143     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9144     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9145   } else {
9146     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9147   }
9148 
9149   switch (Op.getOpcode()) {
9150   case ISD::FCOS:
9151     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9152   case ISD::FSIN:
9153     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9154   default:
9155     llvm_unreachable("Wrong trig opcode");
9156   }
9157 }
9158 
9159 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9160   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9161   assert(AtomicNode->isCompareAndSwap());
9162   unsigned AS = AtomicNode->getAddressSpace();
9163 
9164   // No custom lowering required for local address space
9165   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9166     return Op;
9167 
9168   // Non-local address space requires custom lowering for atomic compare
9169   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9170   SDLoc DL(Op);
9171   SDValue ChainIn = Op.getOperand(0);
9172   SDValue Addr = Op.getOperand(1);
9173   SDValue Old = Op.getOperand(2);
9174   SDValue New = Op.getOperand(3);
9175   EVT VT = Op.getValueType();
9176   MVT SimpleVT = VT.getSimpleVT();
9177   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9178 
9179   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9180   SDValue Ops[] = { ChainIn, Addr, NewOld };
9181 
9182   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9183                                  Ops, VT, AtomicNode->getMemOperand());
9184 }
9185 
9186 //===----------------------------------------------------------------------===//
9187 // Custom DAG optimizations
9188 //===----------------------------------------------------------------------===//
9189 
9190 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9191                                                      DAGCombinerInfo &DCI) const {
9192   EVT VT = N->getValueType(0);
9193   EVT ScalarVT = VT.getScalarType();
9194   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9195     return SDValue();
9196 
9197   SelectionDAG &DAG = DCI.DAG;
9198   SDLoc DL(N);
9199 
9200   SDValue Src = N->getOperand(0);
9201   EVT SrcVT = Src.getValueType();
9202 
9203   // TODO: We could try to match extracting the higher bytes, which would be
9204   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9205   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9206   // about in practice.
9207   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9208     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9209       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9210       DCI.AddToWorklist(Cvt.getNode());
9211 
9212       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9213       if (ScalarVT != MVT::f32) {
9214         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9215                           DAG.getTargetConstant(0, DL, MVT::i32));
9216       }
9217       return Cvt;
9218     }
9219   }
9220 
9221   return SDValue();
9222 }
9223 
9224 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9225 
9226 // This is a variant of
9227 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9228 //
9229 // The normal DAG combiner will do this, but only if the add has one use since
9230 // that would increase the number of instructions.
9231 //
9232 // This prevents us from seeing a constant offset that can be folded into a
9233 // memory instruction's addressing mode. If we know the resulting add offset of
9234 // a pointer can be folded into an addressing offset, we can replace the pointer
9235 // operand with the add of new constant offset. This eliminates one of the uses,
9236 // and may allow the remaining use to also be simplified.
9237 //
9238 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9239                                                unsigned AddrSpace,
9240                                                EVT MemVT,
9241                                                DAGCombinerInfo &DCI) const {
9242   SDValue N0 = N->getOperand(0);
9243   SDValue N1 = N->getOperand(1);
9244 
9245   // We only do this to handle cases where it's profitable when there are
9246   // multiple uses of the add, so defer to the standard combine.
9247   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9248       N0->hasOneUse())
9249     return SDValue();
9250 
9251   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9252   if (!CN1)
9253     return SDValue();
9254 
9255   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9256   if (!CAdd)
9257     return SDValue();
9258 
9259   // If the resulting offset is too large, we can't fold it into the addressing
9260   // mode offset.
9261   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9262   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9263 
9264   AddrMode AM;
9265   AM.HasBaseReg = true;
9266   AM.BaseOffs = Offset.getSExtValue();
9267   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9268     return SDValue();
9269 
9270   SelectionDAG &DAG = DCI.DAG;
9271   SDLoc SL(N);
9272   EVT VT = N->getValueType(0);
9273 
9274   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9275   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9276 
9277   SDNodeFlags Flags;
9278   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9279                           (N0.getOpcode() == ISD::OR ||
9280                            N0->getFlags().hasNoUnsignedWrap()));
9281 
9282   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9283 }
9284 
9285 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9286 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9287 /// specific intrinsic, but they all place the pointer operand first.
9288 static unsigned getBasePtrIndex(const MemSDNode *N) {
9289   switch (N->getOpcode()) {
9290   case ISD::STORE:
9291   case ISD::INTRINSIC_W_CHAIN:
9292   case ISD::INTRINSIC_VOID:
9293     return 2;
9294   default:
9295     return 1;
9296   }
9297 }
9298 
9299 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9300                                                   DAGCombinerInfo &DCI) const {
9301   SelectionDAG &DAG = DCI.DAG;
9302   SDLoc SL(N);
9303 
9304   unsigned PtrIdx = getBasePtrIndex(N);
9305   SDValue Ptr = N->getOperand(PtrIdx);
9306 
9307   // TODO: We could also do this for multiplies.
9308   if (Ptr.getOpcode() == ISD::SHL) {
9309     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9310                                           N->getMemoryVT(), DCI);
9311     if (NewPtr) {
9312       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9313 
9314       NewOps[PtrIdx] = NewPtr;
9315       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9316     }
9317   }
9318 
9319   return SDValue();
9320 }
9321 
9322 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9323   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9324          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9325          (Opc == ISD::XOR && Val == 0);
9326 }
9327 
9328 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9329 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9330 // integer combine opportunities since most 64-bit operations are decomposed
9331 // this way.  TODO: We won't want this for SALU especially if it is an inline
9332 // immediate.
9333 SDValue SITargetLowering::splitBinaryBitConstantOp(
9334   DAGCombinerInfo &DCI,
9335   const SDLoc &SL,
9336   unsigned Opc, SDValue LHS,
9337   const ConstantSDNode *CRHS) const {
9338   uint64_t Val = CRHS->getZExtValue();
9339   uint32_t ValLo = Lo_32(Val);
9340   uint32_t ValHi = Hi_32(Val);
9341   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9342 
9343     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9344          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9345         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9346     // If we need to materialize a 64-bit immediate, it will be split up later
9347     // anyway. Avoid creating the harder to understand 64-bit immediate
9348     // materialization.
9349     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9350   }
9351 
9352   return SDValue();
9353 }
9354 
9355 // Returns true if argument is a boolean value which is not serialized into
9356 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9357 static bool isBoolSGPR(SDValue V) {
9358   if (V.getValueType() != MVT::i1)
9359     return false;
9360   switch (V.getOpcode()) {
9361   default:
9362     break;
9363   case ISD::SETCC:
9364   case AMDGPUISD::FP_CLASS:
9365     return true;
9366   case ISD::AND:
9367   case ISD::OR:
9368   case ISD::XOR:
9369     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9370   }
9371   return false;
9372 }
9373 
9374 // If a constant has all zeroes or all ones within each byte return it.
9375 // Otherwise return 0.
9376 static uint32_t getConstantPermuteMask(uint32_t C) {
9377   // 0xff for any zero byte in the mask
9378   uint32_t ZeroByteMask = 0;
9379   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9380   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9381   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9382   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9383   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9384   if ((NonZeroByteMask & C) != NonZeroByteMask)
9385     return 0; // Partial bytes selected.
9386   return C;
9387 }
9388 
9389 // Check if a node selects whole bytes from its operand 0 starting at a byte
9390 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9391 // or -1 if not succeeded.
9392 // Note byte select encoding:
9393 // value 0-3 selects corresponding source byte;
9394 // value 0xc selects zero;
9395 // value 0xff selects 0xff.
9396 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9397   assert(V.getValueSizeInBits() == 32);
9398 
9399   if (V.getNumOperands() != 2)
9400     return ~0;
9401 
9402   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9403   if (!N1)
9404     return ~0;
9405 
9406   uint32_t C = N1->getZExtValue();
9407 
9408   switch (V.getOpcode()) {
9409   default:
9410     break;
9411   case ISD::AND:
9412     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9413       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9414     }
9415     break;
9416 
9417   case ISD::OR:
9418     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9419       return (0x03020100 & ~ConstMask) | ConstMask;
9420     }
9421     break;
9422 
9423   case ISD::SHL:
9424     if (C % 8)
9425       return ~0;
9426 
9427     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9428 
9429   case ISD::SRL:
9430     if (C % 8)
9431       return ~0;
9432 
9433     return uint32_t(0x0c0c0c0c03020100ull >> C);
9434   }
9435 
9436   return ~0;
9437 }
9438 
9439 SDValue SITargetLowering::performAndCombine(SDNode *N,
9440                                             DAGCombinerInfo &DCI) const {
9441   if (DCI.isBeforeLegalize())
9442     return SDValue();
9443 
9444   SelectionDAG &DAG = DCI.DAG;
9445   EVT VT = N->getValueType(0);
9446   SDValue LHS = N->getOperand(0);
9447   SDValue RHS = N->getOperand(1);
9448 
9449 
9450   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9451   if (VT == MVT::i64 && CRHS) {
9452     if (SDValue Split
9453         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9454       return Split;
9455   }
9456 
9457   if (CRHS && VT == MVT::i32) {
9458     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9459     // nb = number of trailing zeroes in mask
9460     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9461     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9462     uint64_t Mask = CRHS->getZExtValue();
9463     unsigned Bits = countPopulation(Mask);
9464     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9465         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9466       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9467         unsigned Shift = CShift->getZExtValue();
9468         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9469         unsigned Offset = NB + Shift;
9470         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9471           SDLoc SL(N);
9472           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9473                                     LHS->getOperand(0),
9474                                     DAG.getConstant(Offset, SL, MVT::i32),
9475                                     DAG.getConstant(Bits, SL, MVT::i32));
9476           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9477           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9478                                     DAG.getValueType(NarrowVT));
9479           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9480                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9481           return Shl;
9482         }
9483       }
9484     }
9485 
9486     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9487     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9488         isa<ConstantSDNode>(LHS.getOperand(2))) {
9489       uint32_t Sel = getConstantPermuteMask(Mask);
9490       if (!Sel)
9491         return SDValue();
9492 
9493       // Select 0xc for all zero bytes
9494       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9495       SDLoc DL(N);
9496       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9497                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9498     }
9499   }
9500 
9501   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9502   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9503   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9504     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9505     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9506 
9507     SDValue X = LHS.getOperand(0);
9508     SDValue Y = RHS.getOperand(0);
9509     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9510       return SDValue();
9511 
9512     if (LCC == ISD::SETO) {
9513       if (X != LHS.getOperand(1))
9514         return SDValue();
9515 
9516       if (RCC == ISD::SETUNE) {
9517         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9518         if (!C1 || !C1->isInfinity() || C1->isNegative())
9519           return SDValue();
9520 
9521         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9522                               SIInstrFlags::N_SUBNORMAL |
9523                               SIInstrFlags::N_ZERO |
9524                               SIInstrFlags::P_ZERO |
9525                               SIInstrFlags::P_SUBNORMAL |
9526                               SIInstrFlags::P_NORMAL;
9527 
9528         static_assert(((~(SIInstrFlags::S_NAN |
9529                           SIInstrFlags::Q_NAN |
9530                           SIInstrFlags::N_INFINITY |
9531                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9532                       "mask not equal");
9533 
9534         SDLoc DL(N);
9535         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9536                            X, DAG.getConstant(Mask, DL, MVT::i32));
9537       }
9538     }
9539   }
9540 
9541   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9542     std::swap(LHS, RHS);
9543 
9544   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9545       RHS.hasOneUse()) {
9546     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9547     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9548     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9549     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9550     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9551         (RHS.getOperand(0) == LHS.getOperand(0) &&
9552          LHS.getOperand(0) == LHS.getOperand(1))) {
9553       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9554       unsigned NewMask = LCC == ISD::SETO ?
9555         Mask->getZExtValue() & ~OrdMask :
9556         Mask->getZExtValue() & OrdMask;
9557 
9558       SDLoc DL(N);
9559       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9560                          DAG.getConstant(NewMask, DL, MVT::i32));
9561     }
9562   }
9563 
9564   if (VT == MVT::i32 &&
9565       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9566     // and x, (sext cc from i1) => select cc, x, 0
9567     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9568       std::swap(LHS, RHS);
9569     if (isBoolSGPR(RHS.getOperand(0)))
9570       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9571                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9572   }
9573 
9574   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9575   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9576   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9577       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9578     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9579     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9580     if (LHSMask != ~0u && RHSMask != ~0u) {
9581       // Canonicalize the expression in an attempt to have fewer unique masks
9582       // and therefore fewer registers used to hold the masks.
9583       if (LHSMask > RHSMask) {
9584         std::swap(LHSMask, RHSMask);
9585         std::swap(LHS, RHS);
9586       }
9587 
9588       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9589       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9590       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9591       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9592 
9593       // Check of we need to combine values from two sources within a byte.
9594       if (!(LHSUsedLanes & RHSUsedLanes) &&
9595           // If we select high and lower word keep it for SDWA.
9596           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9597           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9598         // Each byte in each mask is either selector mask 0-3, or has higher
9599         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9600         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9601         // mask which is not 0xff wins. By anding both masks we have a correct
9602         // result except that 0x0c shall be corrected to give 0x0c only.
9603         uint32_t Mask = LHSMask & RHSMask;
9604         for (unsigned I = 0; I < 32; I += 8) {
9605           uint32_t ByteSel = 0xff << I;
9606           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9607             Mask &= (0x0c << I) & 0xffffffff;
9608         }
9609 
9610         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9611         // or 0x0c.
9612         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9613         SDLoc DL(N);
9614 
9615         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9616                            LHS.getOperand(0), RHS.getOperand(0),
9617                            DAG.getConstant(Sel, DL, MVT::i32));
9618       }
9619     }
9620   }
9621 
9622   return SDValue();
9623 }
9624 
9625 SDValue SITargetLowering::performOrCombine(SDNode *N,
9626                                            DAGCombinerInfo &DCI) const {
9627   SelectionDAG &DAG = DCI.DAG;
9628   SDValue LHS = N->getOperand(0);
9629   SDValue RHS = N->getOperand(1);
9630 
9631   EVT VT = N->getValueType(0);
9632   if (VT == MVT::i1) {
9633     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9634     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9635         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9636       SDValue Src = LHS.getOperand(0);
9637       if (Src != RHS.getOperand(0))
9638         return SDValue();
9639 
9640       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9641       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9642       if (!CLHS || !CRHS)
9643         return SDValue();
9644 
9645       // Only 10 bits are used.
9646       static const uint32_t MaxMask = 0x3ff;
9647 
9648       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9649       SDLoc DL(N);
9650       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9651                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9652     }
9653 
9654     return SDValue();
9655   }
9656 
9657   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9658   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9659       LHS.getOpcode() == AMDGPUISD::PERM &&
9660       isa<ConstantSDNode>(LHS.getOperand(2))) {
9661     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9662     if (!Sel)
9663       return SDValue();
9664 
9665     Sel |= LHS.getConstantOperandVal(2);
9666     SDLoc DL(N);
9667     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9668                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9669   }
9670 
9671   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9672   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9673   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9674       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9675     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9676     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9677     if (LHSMask != ~0u && RHSMask != ~0u) {
9678       // Canonicalize the expression in an attempt to have fewer unique masks
9679       // and therefore fewer registers used to hold the masks.
9680       if (LHSMask > RHSMask) {
9681         std::swap(LHSMask, RHSMask);
9682         std::swap(LHS, RHS);
9683       }
9684 
9685       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9686       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9687       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9688       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9689 
9690       // Check of we need to combine values from two sources within a byte.
9691       if (!(LHSUsedLanes & RHSUsedLanes) &&
9692           // If we select high and lower word keep it for SDWA.
9693           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9694           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9695         // Kill zero bytes selected by other mask. Zero value is 0xc.
9696         LHSMask &= ~RHSUsedLanes;
9697         RHSMask &= ~LHSUsedLanes;
9698         // Add 4 to each active LHS lane
9699         LHSMask |= LHSUsedLanes & 0x04040404;
9700         // Combine masks
9701         uint32_t Sel = LHSMask | RHSMask;
9702         SDLoc DL(N);
9703 
9704         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9705                            LHS.getOperand(0), RHS.getOperand(0),
9706                            DAG.getConstant(Sel, DL, MVT::i32));
9707       }
9708     }
9709   }
9710 
9711   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9712     return SDValue();
9713 
9714   // TODO: This could be a generic combine with a predicate for extracting the
9715   // high half of an integer being free.
9716 
9717   // (or i64:x, (zero_extend i32:y)) ->
9718   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9719   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9720       RHS.getOpcode() != ISD::ZERO_EXTEND)
9721     std::swap(LHS, RHS);
9722 
9723   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9724     SDValue ExtSrc = RHS.getOperand(0);
9725     EVT SrcVT = ExtSrc.getValueType();
9726     if (SrcVT == MVT::i32) {
9727       SDLoc SL(N);
9728       SDValue LowLHS, HiBits;
9729       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9730       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9731 
9732       DCI.AddToWorklist(LowOr.getNode());
9733       DCI.AddToWorklist(HiBits.getNode());
9734 
9735       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9736                                 LowOr, HiBits);
9737       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9738     }
9739   }
9740 
9741   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9742   if (CRHS) {
9743     if (SDValue Split
9744           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9745                                      N->getOperand(0), CRHS))
9746       return Split;
9747   }
9748 
9749   return SDValue();
9750 }
9751 
9752 SDValue SITargetLowering::performXorCombine(SDNode *N,
9753                                             DAGCombinerInfo &DCI) const {
9754   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9755     return RV;
9756 
9757   EVT VT = N->getValueType(0);
9758   if (VT != MVT::i64)
9759     return SDValue();
9760 
9761   SDValue LHS = N->getOperand(0);
9762   SDValue RHS = N->getOperand(1);
9763 
9764   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9765   if (CRHS) {
9766     if (SDValue Split
9767           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9768       return Split;
9769   }
9770 
9771   return SDValue();
9772 }
9773 
9774 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9775                                                    DAGCombinerInfo &DCI) const {
9776   if (!Subtarget->has16BitInsts() ||
9777       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9778     return SDValue();
9779 
9780   EVT VT = N->getValueType(0);
9781   if (VT != MVT::i32)
9782     return SDValue();
9783 
9784   SDValue Src = N->getOperand(0);
9785   if (Src.getValueType() != MVT::i16)
9786     return SDValue();
9787 
9788   return SDValue();
9789 }
9790 
9791 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9792                                                         DAGCombinerInfo &DCI)
9793                                                         const {
9794   SDValue Src = N->getOperand(0);
9795   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9796 
9797   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9798       VTSign->getVT() == MVT::i8) ||
9799       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9800       VTSign->getVT() == MVT::i16)) &&
9801       Src.hasOneUse()) {
9802     auto *M = cast<MemSDNode>(Src);
9803     SDValue Ops[] = {
9804       Src.getOperand(0), // Chain
9805       Src.getOperand(1), // rsrc
9806       Src.getOperand(2), // vindex
9807       Src.getOperand(3), // voffset
9808       Src.getOperand(4), // soffset
9809       Src.getOperand(5), // offset
9810       Src.getOperand(6),
9811       Src.getOperand(7)
9812     };
9813     // replace with BUFFER_LOAD_BYTE/SHORT
9814     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9815                                          Src.getOperand(0).getValueType());
9816     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9817                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9818     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9819                                                           ResList,
9820                                                           Ops, M->getMemoryVT(),
9821                                                           M->getMemOperand());
9822     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9823                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9824   }
9825   return SDValue();
9826 }
9827 
9828 SDValue SITargetLowering::performClassCombine(SDNode *N,
9829                                               DAGCombinerInfo &DCI) const {
9830   SelectionDAG &DAG = DCI.DAG;
9831   SDValue Mask = N->getOperand(1);
9832 
9833   // fp_class x, 0 -> false
9834   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9835     if (CMask->isZero())
9836       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9837   }
9838 
9839   if (N->getOperand(0).isUndef())
9840     return DAG.getUNDEF(MVT::i1);
9841 
9842   return SDValue();
9843 }
9844 
9845 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9846                                             DAGCombinerInfo &DCI) const {
9847   EVT VT = N->getValueType(0);
9848   SDValue N0 = N->getOperand(0);
9849 
9850   if (N0.isUndef())
9851     return N0;
9852 
9853   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9854                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9855     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9856                            N->getFlags());
9857   }
9858 
9859   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9860     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9861                            N0.getOperand(0), N->getFlags());
9862   }
9863 
9864   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9865 }
9866 
9867 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9868                                        unsigned MaxDepth) const {
9869   unsigned Opcode = Op.getOpcode();
9870   if (Opcode == ISD::FCANONICALIZE)
9871     return true;
9872 
9873   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9874     auto F = CFP->getValueAPF();
9875     if (F.isNaN() && F.isSignaling())
9876       return false;
9877     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9878   }
9879 
9880   // If source is a result of another standard FP operation it is already in
9881   // canonical form.
9882   if (MaxDepth == 0)
9883     return false;
9884 
9885   switch (Opcode) {
9886   // These will flush denorms if required.
9887   case ISD::FADD:
9888   case ISD::FSUB:
9889   case ISD::FMUL:
9890   case ISD::FCEIL:
9891   case ISD::FFLOOR:
9892   case ISD::FMA:
9893   case ISD::FMAD:
9894   case ISD::FSQRT:
9895   case ISD::FDIV:
9896   case ISD::FREM:
9897   case ISD::FP_ROUND:
9898   case ISD::FP_EXTEND:
9899   case AMDGPUISD::FMUL_LEGACY:
9900   case AMDGPUISD::FMAD_FTZ:
9901   case AMDGPUISD::RCP:
9902   case AMDGPUISD::RSQ:
9903   case AMDGPUISD::RSQ_CLAMP:
9904   case AMDGPUISD::RCP_LEGACY:
9905   case AMDGPUISD::RCP_IFLAG:
9906   case AMDGPUISD::DIV_SCALE:
9907   case AMDGPUISD::DIV_FMAS:
9908   case AMDGPUISD::DIV_FIXUP:
9909   case AMDGPUISD::FRACT:
9910   case AMDGPUISD::LDEXP:
9911   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9912   case AMDGPUISD::CVT_F32_UBYTE0:
9913   case AMDGPUISD::CVT_F32_UBYTE1:
9914   case AMDGPUISD::CVT_F32_UBYTE2:
9915   case AMDGPUISD::CVT_F32_UBYTE3:
9916     return true;
9917 
9918   // It can/will be lowered or combined as a bit operation.
9919   // Need to check their input recursively to handle.
9920   case ISD::FNEG:
9921   case ISD::FABS:
9922   case ISD::FCOPYSIGN:
9923     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9924 
9925   case ISD::FSIN:
9926   case ISD::FCOS:
9927   case ISD::FSINCOS:
9928     return Op.getValueType().getScalarType() != MVT::f16;
9929 
9930   case ISD::FMINNUM:
9931   case ISD::FMAXNUM:
9932   case ISD::FMINNUM_IEEE:
9933   case ISD::FMAXNUM_IEEE:
9934   case AMDGPUISD::CLAMP:
9935   case AMDGPUISD::FMED3:
9936   case AMDGPUISD::FMAX3:
9937   case AMDGPUISD::FMIN3: {
9938     // FIXME: Shouldn't treat the generic operations different based these.
9939     // However, we aren't really required to flush the result from
9940     // minnum/maxnum..
9941 
9942     // snans will be quieted, so we only need to worry about denormals.
9943     if (Subtarget->supportsMinMaxDenormModes() ||
9944         denormalsEnabledForType(DAG, Op.getValueType()))
9945       return true;
9946 
9947     // Flushing may be required.
9948     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9949     // targets need to check their input recursively.
9950 
9951     // FIXME: Does this apply with clamp? It's implemented with max.
9952     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9953       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9954         return false;
9955     }
9956 
9957     return true;
9958   }
9959   case ISD::SELECT: {
9960     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9961            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9962   }
9963   case ISD::BUILD_VECTOR: {
9964     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9965       SDValue SrcOp = Op.getOperand(i);
9966       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9967         return false;
9968     }
9969 
9970     return true;
9971   }
9972   case ISD::EXTRACT_VECTOR_ELT:
9973   case ISD::EXTRACT_SUBVECTOR: {
9974     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9975   }
9976   case ISD::INSERT_VECTOR_ELT: {
9977     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9978            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9979   }
9980   case ISD::UNDEF:
9981     // Could be anything.
9982     return false;
9983 
9984   case ISD::BITCAST:
9985     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9986   case ISD::TRUNCATE: {
9987     // Hack round the mess we make when legalizing extract_vector_elt
9988     if (Op.getValueType() == MVT::i16) {
9989       SDValue TruncSrc = Op.getOperand(0);
9990       if (TruncSrc.getValueType() == MVT::i32 &&
9991           TruncSrc.getOpcode() == ISD::BITCAST &&
9992           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9993         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9994       }
9995     }
9996     return false;
9997   }
9998   case ISD::INTRINSIC_WO_CHAIN: {
9999     unsigned IntrinsicID
10000       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10001     // TODO: Handle more intrinsics
10002     switch (IntrinsicID) {
10003     case Intrinsic::amdgcn_cvt_pkrtz:
10004     case Intrinsic::amdgcn_cubeid:
10005     case Intrinsic::amdgcn_frexp_mant:
10006     case Intrinsic::amdgcn_fdot2:
10007     case Intrinsic::amdgcn_rcp:
10008     case Intrinsic::amdgcn_rsq:
10009     case Intrinsic::amdgcn_rsq_clamp:
10010     case Intrinsic::amdgcn_rcp_legacy:
10011     case Intrinsic::amdgcn_rsq_legacy:
10012     case Intrinsic::amdgcn_trig_preop:
10013       return true;
10014     default:
10015       break;
10016     }
10017 
10018     LLVM_FALLTHROUGH;
10019   }
10020   default:
10021     return denormalsEnabledForType(DAG, Op.getValueType()) &&
10022            DAG.isKnownNeverSNaN(Op);
10023   }
10024 
10025   llvm_unreachable("invalid operation");
10026 }
10027 
10028 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10029                                        unsigned MaxDepth) const {
10030   MachineRegisterInfo &MRI = MF.getRegInfo();
10031   MachineInstr *MI = MRI.getVRegDef(Reg);
10032   unsigned Opcode = MI->getOpcode();
10033 
10034   if (Opcode == AMDGPU::G_FCANONICALIZE)
10035     return true;
10036 
10037   Optional<FPValueAndVReg> FCR;
10038   // Constant splat (can be padded with undef) or scalar constant.
10039   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10040     if (FCR->Value.isSignaling())
10041       return false;
10042     return !FCR->Value.isDenormal() ||
10043            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10044   }
10045 
10046   if (MaxDepth == 0)
10047     return false;
10048 
10049   switch (Opcode) {
10050   case AMDGPU::G_FMINNUM_IEEE:
10051   case AMDGPU::G_FMAXNUM_IEEE: {
10052     if (Subtarget->supportsMinMaxDenormModes() ||
10053         denormalsEnabledForType(MRI.getType(Reg), MF))
10054       return true;
10055     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10056       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10057         return false;
10058     return true;
10059   }
10060   default:
10061     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10062            isKnownNeverSNaN(Reg, MRI);
10063   }
10064 
10065   llvm_unreachable("invalid operation");
10066 }
10067 
10068 // Constant fold canonicalize.
10069 SDValue SITargetLowering::getCanonicalConstantFP(
10070   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10071   // Flush denormals to 0 if not enabled.
10072   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10073     return DAG.getConstantFP(0.0, SL, VT);
10074 
10075   if (C.isNaN()) {
10076     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10077     if (C.isSignaling()) {
10078       // Quiet a signaling NaN.
10079       // FIXME: Is this supposed to preserve payload bits?
10080       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10081     }
10082 
10083     // Make sure it is the canonical NaN bitpattern.
10084     //
10085     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10086     // immediate?
10087     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10088       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10089   }
10090 
10091   // Already canonical.
10092   return DAG.getConstantFP(C, SL, VT);
10093 }
10094 
10095 static bool vectorEltWillFoldAway(SDValue Op) {
10096   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10097 }
10098 
10099 SDValue SITargetLowering::performFCanonicalizeCombine(
10100   SDNode *N,
10101   DAGCombinerInfo &DCI) const {
10102   SelectionDAG &DAG = DCI.DAG;
10103   SDValue N0 = N->getOperand(0);
10104   EVT VT = N->getValueType(0);
10105 
10106   // fcanonicalize undef -> qnan
10107   if (N0.isUndef()) {
10108     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10109     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10110   }
10111 
10112   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10113     EVT VT = N->getValueType(0);
10114     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10115   }
10116 
10117   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10118   //                                                   (fcanonicalize k)
10119   //
10120   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10121 
10122   // TODO: This could be better with wider vectors that will be split to v2f16,
10123   // and to consider uses since there aren't that many packed operations.
10124   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10125       isTypeLegal(MVT::v2f16)) {
10126     SDLoc SL(N);
10127     SDValue NewElts[2];
10128     SDValue Lo = N0.getOperand(0);
10129     SDValue Hi = N0.getOperand(1);
10130     EVT EltVT = Lo.getValueType();
10131 
10132     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10133       for (unsigned I = 0; I != 2; ++I) {
10134         SDValue Op = N0.getOperand(I);
10135         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10136           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10137                                               CFP->getValueAPF());
10138         } else if (Op.isUndef()) {
10139           // Handled below based on what the other operand is.
10140           NewElts[I] = Op;
10141         } else {
10142           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10143         }
10144       }
10145 
10146       // If one half is undef, and one is constant, prefer a splat vector rather
10147       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10148       // cheaper to use and may be free with a packed operation.
10149       if (NewElts[0].isUndef()) {
10150         if (isa<ConstantFPSDNode>(NewElts[1]))
10151           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10152             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10153       }
10154 
10155       if (NewElts[1].isUndef()) {
10156         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10157           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10158       }
10159 
10160       return DAG.getBuildVector(VT, SL, NewElts);
10161     }
10162   }
10163 
10164   unsigned SrcOpc = N0.getOpcode();
10165 
10166   // If it's free to do so, push canonicalizes further up the source, which may
10167   // find a canonical source.
10168   //
10169   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10170   // sNaNs.
10171   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10172     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10173     if (CRHS && N0.hasOneUse()) {
10174       SDLoc SL(N);
10175       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10176                                    N0.getOperand(0));
10177       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10178       DCI.AddToWorklist(Canon0.getNode());
10179 
10180       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10181     }
10182   }
10183 
10184   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10185 }
10186 
10187 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10188   switch (Opc) {
10189   case ISD::FMAXNUM:
10190   case ISD::FMAXNUM_IEEE:
10191     return AMDGPUISD::FMAX3;
10192   case ISD::SMAX:
10193     return AMDGPUISD::SMAX3;
10194   case ISD::UMAX:
10195     return AMDGPUISD::UMAX3;
10196   case ISD::FMINNUM:
10197   case ISD::FMINNUM_IEEE:
10198     return AMDGPUISD::FMIN3;
10199   case ISD::SMIN:
10200     return AMDGPUISD::SMIN3;
10201   case ISD::UMIN:
10202     return AMDGPUISD::UMIN3;
10203   default:
10204     llvm_unreachable("Not a min/max opcode");
10205   }
10206 }
10207 
10208 SDValue SITargetLowering::performIntMed3ImmCombine(
10209   SelectionDAG &DAG, const SDLoc &SL,
10210   SDValue Op0, SDValue Op1, bool Signed) const {
10211   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10212   if (!K1)
10213     return SDValue();
10214 
10215   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10216   if (!K0)
10217     return SDValue();
10218 
10219   if (Signed) {
10220     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10221       return SDValue();
10222   } else {
10223     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10224       return SDValue();
10225   }
10226 
10227   EVT VT = K0->getValueType(0);
10228   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10229   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10230     return DAG.getNode(Med3Opc, SL, VT,
10231                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10232   }
10233 
10234   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10235   if (VT == MVT::i16) {
10236     MVT NVT = MVT::i32;
10237     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10238 
10239     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10240     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10241     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10242 
10243     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10244     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10245   }
10246 
10247   return SDValue();
10248 }
10249 
10250 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10251   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10252     return C;
10253 
10254   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10255     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10256       return C;
10257   }
10258 
10259   return nullptr;
10260 }
10261 
10262 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10263                                                   const SDLoc &SL,
10264                                                   SDValue Op0,
10265                                                   SDValue Op1) const {
10266   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10267   if (!K1)
10268     return SDValue();
10269 
10270   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10271   if (!K0)
10272     return SDValue();
10273 
10274   // Ordered >= (although NaN inputs should have folded away by now).
10275   if (K0->getValueAPF() > K1->getValueAPF())
10276     return SDValue();
10277 
10278   const MachineFunction &MF = DAG.getMachineFunction();
10279   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10280 
10281   // TODO: Check IEEE bit enabled?
10282   EVT VT = Op0.getValueType();
10283   if (Info->getMode().DX10Clamp) {
10284     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10285     // hardware fmed3 behavior converting to a min.
10286     // FIXME: Should this be allowing -0.0?
10287     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10288       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10289   }
10290 
10291   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10292   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10293     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10294     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10295     // then give the other result, which is different from med3 with a NaN
10296     // input.
10297     SDValue Var = Op0.getOperand(0);
10298     if (!DAG.isKnownNeverSNaN(Var))
10299       return SDValue();
10300 
10301     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10302 
10303     if ((!K0->hasOneUse() ||
10304          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10305         (!K1->hasOneUse() ||
10306          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10307       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10308                          Var, SDValue(K0, 0), SDValue(K1, 0));
10309     }
10310   }
10311 
10312   return SDValue();
10313 }
10314 
10315 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10316                                                DAGCombinerInfo &DCI) const {
10317   SelectionDAG &DAG = DCI.DAG;
10318 
10319   EVT VT = N->getValueType(0);
10320   unsigned Opc = N->getOpcode();
10321   SDValue Op0 = N->getOperand(0);
10322   SDValue Op1 = N->getOperand(1);
10323 
10324   // Only do this if the inner op has one use since this will just increases
10325   // register pressure for no benefit.
10326 
10327   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10328       !VT.isVector() &&
10329       (VT == MVT::i32 || VT == MVT::f32 ||
10330        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10331     // max(max(a, b), c) -> max3(a, b, c)
10332     // min(min(a, b), c) -> min3(a, b, c)
10333     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10334       SDLoc DL(N);
10335       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10336                          DL,
10337                          N->getValueType(0),
10338                          Op0.getOperand(0),
10339                          Op0.getOperand(1),
10340                          Op1);
10341     }
10342 
10343     // Try commuted.
10344     // max(a, max(b, c)) -> max3(a, b, c)
10345     // min(a, min(b, c)) -> min3(a, b, c)
10346     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10347       SDLoc DL(N);
10348       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10349                          DL,
10350                          N->getValueType(0),
10351                          Op0,
10352                          Op1.getOperand(0),
10353                          Op1.getOperand(1));
10354     }
10355   }
10356 
10357   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10358   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10359     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10360       return Med3;
10361   }
10362 
10363   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10364     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10365       return Med3;
10366   }
10367 
10368   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10369   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10370        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10371        (Opc == AMDGPUISD::FMIN_LEGACY &&
10372         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10373       (VT == MVT::f32 || VT == MVT::f64 ||
10374        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10375        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10376       Op0.hasOneUse()) {
10377     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10378       return Res;
10379   }
10380 
10381   return SDValue();
10382 }
10383 
10384 static bool isClampZeroToOne(SDValue A, SDValue B) {
10385   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10386     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10387       // FIXME: Should this be allowing -0.0?
10388       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10389              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10390     }
10391   }
10392 
10393   return false;
10394 }
10395 
10396 // FIXME: Should only worry about snans for version with chain.
10397 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10398                                               DAGCombinerInfo &DCI) const {
10399   EVT VT = N->getValueType(0);
10400   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10401   // NaNs. With a NaN input, the order of the operands may change the result.
10402 
10403   SelectionDAG &DAG = DCI.DAG;
10404   SDLoc SL(N);
10405 
10406   SDValue Src0 = N->getOperand(0);
10407   SDValue Src1 = N->getOperand(1);
10408   SDValue Src2 = N->getOperand(2);
10409 
10410   if (isClampZeroToOne(Src0, Src1)) {
10411     // const_a, const_b, x -> clamp is safe in all cases including signaling
10412     // nans.
10413     // FIXME: Should this be allowing -0.0?
10414     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10415   }
10416 
10417   const MachineFunction &MF = DAG.getMachineFunction();
10418   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10419 
10420   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10421   // handling no dx10-clamp?
10422   if (Info->getMode().DX10Clamp) {
10423     // If NaNs is clamped to 0, we are free to reorder the inputs.
10424 
10425     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10426       std::swap(Src0, Src1);
10427 
10428     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10429       std::swap(Src1, Src2);
10430 
10431     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10432       std::swap(Src0, Src1);
10433 
10434     if (isClampZeroToOne(Src1, Src2))
10435       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10436   }
10437 
10438   return SDValue();
10439 }
10440 
10441 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10442                                                  DAGCombinerInfo &DCI) const {
10443   SDValue Src0 = N->getOperand(0);
10444   SDValue Src1 = N->getOperand(1);
10445   if (Src0.isUndef() && Src1.isUndef())
10446     return DCI.DAG.getUNDEF(N->getValueType(0));
10447   return SDValue();
10448 }
10449 
10450 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10451 // expanded into a set of cmp/select instructions.
10452 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10453                                                 unsigned NumElem,
10454                                                 bool IsDivergentIdx,
10455                                                 const GCNSubtarget *Subtarget) {
10456   if (UseDivergentRegisterIndexing)
10457     return false;
10458 
10459   unsigned VecSize = EltSize * NumElem;
10460 
10461   // Sub-dword vectors of size 2 dword or less have better implementation.
10462   if (VecSize <= 64 && EltSize < 32)
10463     return false;
10464 
10465   // Always expand the rest of sub-dword instructions, otherwise it will be
10466   // lowered via memory.
10467   if (EltSize < 32)
10468     return true;
10469 
10470   // Always do this if var-idx is divergent, otherwise it will become a loop.
10471   if (IsDivergentIdx)
10472     return true;
10473 
10474   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10475   unsigned NumInsts = NumElem /* Number of compares */ +
10476                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10477 
10478   // On some architectures (GFX9) movrel is not available and it's better
10479   // to expand.
10480   if (!Subtarget->hasMovrel())
10481     return NumInsts <= 16;
10482 
10483   // If movrel is available, use it instead of expanding for vector of 8
10484   // elements.
10485   return NumInsts <= 15;
10486 }
10487 
10488 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
10489   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10490   if (isa<ConstantSDNode>(Idx))
10491     return false;
10492 
10493   SDValue Vec = N->getOperand(0);
10494   EVT VecVT = Vec.getValueType();
10495   EVT EltVT = VecVT.getVectorElementType();
10496   unsigned EltSize = EltVT.getSizeInBits();
10497   unsigned NumElem = VecVT.getVectorNumElements();
10498 
10499   return SITargetLowering::shouldExpandVectorDynExt(
10500       EltSize, NumElem, Idx->isDivergent(), getSubtarget());
10501 }
10502 
10503 SDValue SITargetLowering::performExtractVectorEltCombine(
10504   SDNode *N, DAGCombinerInfo &DCI) const {
10505   SDValue Vec = N->getOperand(0);
10506   SelectionDAG &DAG = DCI.DAG;
10507 
10508   EVT VecVT = Vec.getValueType();
10509   EVT EltVT = VecVT.getVectorElementType();
10510 
10511   if ((Vec.getOpcode() == ISD::FNEG ||
10512        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10513     SDLoc SL(N);
10514     EVT EltVT = N->getValueType(0);
10515     SDValue Idx = N->getOperand(1);
10516     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10517                               Vec.getOperand(0), Idx);
10518     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10519   }
10520 
10521   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10522   //    =>
10523   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10524   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10525   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10526   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10527     SDLoc SL(N);
10528     EVT EltVT = N->getValueType(0);
10529     SDValue Idx = N->getOperand(1);
10530     unsigned Opc = Vec.getOpcode();
10531 
10532     switch(Opc) {
10533     default:
10534       break;
10535       // TODO: Support other binary operations.
10536     case ISD::FADD:
10537     case ISD::FSUB:
10538     case ISD::FMUL:
10539     case ISD::ADD:
10540     case ISD::UMIN:
10541     case ISD::UMAX:
10542     case ISD::SMIN:
10543     case ISD::SMAX:
10544     case ISD::FMAXNUM:
10545     case ISD::FMINNUM:
10546     case ISD::FMAXNUM_IEEE:
10547     case ISD::FMINNUM_IEEE: {
10548       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10549                                  Vec.getOperand(0), Idx);
10550       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10551                                  Vec.getOperand(1), Idx);
10552 
10553       DCI.AddToWorklist(Elt0.getNode());
10554       DCI.AddToWorklist(Elt1.getNode());
10555       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10556     }
10557     }
10558   }
10559 
10560   unsigned VecSize = VecVT.getSizeInBits();
10561   unsigned EltSize = EltVT.getSizeInBits();
10562 
10563   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10564   if (shouldExpandVectorDynExt(N)) {
10565     SDLoc SL(N);
10566     SDValue Idx = N->getOperand(1);
10567     SDValue V;
10568     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10569       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10570       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10571       if (I == 0)
10572         V = Elt;
10573       else
10574         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10575     }
10576     return V;
10577   }
10578 
10579   if (!DCI.isBeforeLegalize())
10580     return SDValue();
10581 
10582   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10583   // elements. This exposes more load reduction opportunities by replacing
10584   // multiple small extract_vector_elements with a single 32-bit extract.
10585   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10586   if (isa<MemSDNode>(Vec) &&
10587       EltSize <= 16 &&
10588       EltVT.isByteSized() &&
10589       VecSize > 32 &&
10590       VecSize % 32 == 0 &&
10591       Idx) {
10592     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10593 
10594     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10595     unsigned EltIdx = BitIndex / 32;
10596     unsigned LeftoverBitIdx = BitIndex % 32;
10597     SDLoc SL(N);
10598 
10599     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10600     DCI.AddToWorklist(Cast.getNode());
10601 
10602     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10603                               DAG.getConstant(EltIdx, SL, MVT::i32));
10604     DCI.AddToWorklist(Elt.getNode());
10605     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10606                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10607     DCI.AddToWorklist(Srl.getNode());
10608 
10609     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10610     DCI.AddToWorklist(Trunc.getNode());
10611     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10612   }
10613 
10614   return SDValue();
10615 }
10616 
10617 SDValue
10618 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10619                                                 DAGCombinerInfo &DCI) const {
10620   SDValue Vec = N->getOperand(0);
10621   SDValue Idx = N->getOperand(2);
10622   EVT VecVT = Vec.getValueType();
10623   EVT EltVT = VecVT.getVectorElementType();
10624 
10625   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10626   // => BUILD_VECTOR n x select (e, const-idx)
10627   if (!shouldExpandVectorDynExt(N))
10628     return SDValue();
10629 
10630   SelectionDAG &DAG = DCI.DAG;
10631   SDLoc SL(N);
10632   SDValue Ins = N->getOperand(1);
10633   EVT IdxVT = Idx.getValueType();
10634 
10635   SmallVector<SDValue, 16> Ops;
10636   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10637     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10638     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10639     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10640     Ops.push_back(V);
10641   }
10642 
10643   return DAG.getBuildVector(VecVT, SL, Ops);
10644 }
10645 
10646 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10647                                           const SDNode *N0,
10648                                           const SDNode *N1) const {
10649   EVT VT = N0->getValueType(0);
10650 
10651   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10652   // support denormals ever.
10653   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10654        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10655         getSubtarget()->hasMadF16())) &&
10656        isOperationLegal(ISD::FMAD, VT))
10657     return ISD::FMAD;
10658 
10659   const TargetOptions &Options = DAG.getTarget().Options;
10660   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10661        (N0->getFlags().hasAllowContract() &&
10662         N1->getFlags().hasAllowContract())) &&
10663       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10664     return ISD::FMA;
10665   }
10666 
10667   return 0;
10668 }
10669 
10670 // For a reassociatable opcode perform:
10671 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10672 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10673                                                SelectionDAG &DAG) const {
10674   EVT VT = N->getValueType(0);
10675   if (VT != MVT::i32 && VT != MVT::i64)
10676     return SDValue();
10677 
10678   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10679     return SDValue();
10680 
10681   unsigned Opc = N->getOpcode();
10682   SDValue Op0 = N->getOperand(0);
10683   SDValue Op1 = N->getOperand(1);
10684 
10685   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10686     return SDValue();
10687 
10688   if (Op0->isDivergent())
10689     std::swap(Op0, Op1);
10690 
10691   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10692     return SDValue();
10693 
10694   SDValue Op2 = Op1.getOperand(1);
10695   Op1 = Op1.getOperand(0);
10696   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10697     return SDValue();
10698 
10699   if (Op1->isDivergent())
10700     std::swap(Op1, Op2);
10701 
10702   SDLoc SL(N);
10703   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10704   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10705 }
10706 
10707 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10708                            EVT VT,
10709                            SDValue N0, SDValue N1, SDValue N2,
10710                            bool Signed) {
10711   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10712   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10713   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10714   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10715 }
10716 
10717 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
10718 // multiplies, if any.
10719 //
10720 // Full 64-bit multiplies that feed into an addition are lowered here instead
10721 // of using the generic expansion. The generic expansion ends up with
10722 // a tree of ADD nodes that prevents us from using the "add" part of the
10723 // MAD instruction. The expansion produced here results in a chain of ADDs
10724 // instead of a tree.
10725 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10726                                             DAGCombinerInfo &DCI) const {
10727   assert(N->getOpcode() == ISD::ADD);
10728 
10729   SelectionDAG &DAG = DCI.DAG;
10730   EVT VT = N->getValueType(0);
10731   SDLoc SL(N);
10732   SDValue LHS = N->getOperand(0);
10733   SDValue RHS = N->getOperand(1);
10734 
10735   if (VT.isVector())
10736     return SDValue();
10737 
10738   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
10739   // result in scalar registers for uniform values.
10740   if (!N->isDivergent() && Subtarget->hasSMulHi())
10741     return SDValue();
10742 
10743   unsigned NumBits = VT.getScalarSizeInBits();
10744   if (NumBits <= 32 || NumBits > 64)
10745     return SDValue();
10746 
10747   if (LHS.getOpcode() != ISD::MUL) {
10748     assert(RHS.getOpcode() == ISD::MUL);
10749     std::swap(LHS, RHS);
10750   }
10751 
10752   // Avoid the fold if it would unduly increase the number of multiplies due to
10753   // multiple uses, except on hardware with full-rate multiply-add (which is
10754   // part of full-rate 64-bit ops).
10755   if (!Subtarget->hasFullRate64Ops()) {
10756     unsigned NumUsers = 0;
10757     for (SDNode *Use : LHS->uses()) {
10758       // There is a use that does not feed into addition, so the multiply can't
10759       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
10760       if (Use->getOpcode() != ISD::ADD)
10761         return SDValue();
10762 
10763       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
10764       // MUL + 3xADD + 3xADDC over 3xMAD.
10765       ++NumUsers;
10766       if (NumUsers >= 3)
10767         return SDValue();
10768     }
10769   }
10770 
10771   SDValue MulLHS = LHS.getOperand(0);
10772   SDValue MulRHS = LHS.getOperand(1);
10773   SDValue AddRHS = RHS;
10774 
10775   // Always check whether operands are small unsigned values, since that
10776   // knowledge is useful in more cases. Check for small signed values only if
10777   // doing so can unlock a shorter code sequence.
10778   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
10779   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
10780 
10781   bool MulSignedLo = false;
10782   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
10783     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
10784                   numBitsSigned(MulRHS, DAG) <= 32;
10785   }
10786 
10787   // The operands and final result all have the same number of bits. If
10788   // operands need to be extended, they can be extended with garbage. The
10789   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
10790   // truncated away in the end.
10791   if (VT != MVT::i64) {
10792     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
10793     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
10794     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
10795   }
10796 
10797   // The basic code generated is conceptually straightforward. Pseudo code:
10798   //
10799   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
10800   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
10801   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
10802   //
10803   // The second and third lines are optional, depending on whether the factors
10804   // are {sign,zero}-extended or not.
10805   //
10806   // The actual DAG is noisier than the pseudo code, but only due to
10807   // instructions that disassemble values into low and high parts, and
10808   // assemble the final result.
10809   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
10810   SDValue One = DAG.getConstant(1, SL, MVT::i32);
10811 
10812   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
10813   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
10814   SDValue Accum =
10815       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
10816 
10817   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
10818     auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero);
10819     auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One);
10820 
10821     if (!MulLHSUnsigned32) {
10822       auto MulLHSHi =
10823           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
10824       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
10825       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10826     }
10827 
10828     if (!MulRHSUnsigned32) {
10829       auto MulRHSHi =
10830           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
10831       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
10832       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10833     }
10834 
10835     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
10836     Accum = DAG.getBitcast(MVT::i64, Accum);
10837   }
10838 
10839   if (VT != MVT::i64)
10840     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
10841   return Accum;
10842 }
10843 
10844 SDValue SITargetLowering::performAddCombine(SDNode *N,
10845                                             DAGCombinerInfo &DCI) const {
10846   SelectionDAG &DAG = DCI.DAG;
10847   EVT VT = N->getValueType(0);
10848   SDLoc SL(N);
10849   SDValue LHS = N->getOperand(0);
10850   SDValue RHS = N->getOperand(1);
10851 
10852   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10853     if (Subtarget->hasMad64_32()) {
10854       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10855         return Folded;
10856     }
10857 
10858     return SDValue();
10859   }
10860 
10861   if (SDValue V = reassociateScalarOps(N, DAG)) {
10862     return V;
10863   }
10864 
10865   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10866     return SDValue();
10867 
10868   // add x, zext (setcc) => addcarry x, 0, setcc
10869   // add x, sext (setcc) => subcarry x, 0, setcc
10870   unsigned Opc = LHS.getOpcode();
10871   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10872       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10873     std::swap(RHS, LHS);
10874 
10875   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::SUBCARRY : ISD::ADDCARRY;
10889     return DAG.getNode(Opc, SL, VTList, Args);
10890   }
10891   case ISD::ADDCARRY: {
10892     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10893     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10894     if (!C || C->getZExtValue() != 0) break;
10895     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10896     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10897   }
10898   }
10899   return SDValue();
10900 }
10901 
10902 SDValue SITargetLowering::performSubCombine(SDNode *N,
10903                                             DAGCombinerInfo &DCI) const {
10904   SelectionDAG &DAG = DCI.DAG;
10905   EVT VT = N->getValueType(0);
10906 
10907   if (VT != MVT::i32)
10908     return SDValue();
10909 
10910   SDLoc SL(N);
10911   SDValue LHS = N->getOperand(0);
10912   SDValue RHS = N->getOperand(1);
10913 
10914   // sub x, zext (setcc) => subcarry x, 0, setcc
10915   // sub x, sext (setcc) => addcarry x, 0, setcc
10916   unsigned Opc = RHS.getOpcode();
10917   switch (Opc) {
10918   default: break;
10919   case ISD::ZERO_EXTEND:
10920   case ISD::SIGN_EXTEND:
10921   case ISD::ANY_EXTEND: {
10922     auto Cond = RHS.getOperand(0);
10923     // If this won't be a real VOPC output, we would still need to insert an
10924     // extra instruction anyway.
10925     if (!isBoolSGPR(Cond))
10926       break;
10927     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10928     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10929     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10930     return DAG.getNode(Opc, SL, VTList, Args);
10931   }
10932   }
10933 
10934   if (LHS.getOpcode() == ISD::SUBCARRY) {
10935     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10936     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10937     if (!C || !C->isZero())
10938       return SDValue();
10939     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10940     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10941   }
10942   return SDValue();
10943 }
10944 
10945 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10946   DAGCombinerInfo &DCI) const {
10947 
10948   if (N->getValueType(0) != MVT::i32)
10949     return SDValue();
10950 
10951   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10952   if (!C || C->getZExtValue() != 0)
10953     return SDValue();
10954 
10955   SelectionDAG &DAG = DCI.DAG;
10956   SDValue LHS = N->getOperand(0);
10957 
10958   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10959   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10960   unsigned LHSOpc = LHS.getOpcode();
10961   unsigned Opc = N->getOpcode();
10962   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10963       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10964     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10965     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10966   }
10967   return SDValue();
10968 }
10969 
10970 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10971                                              DAGCombinerInfo &DCI) const {
10972   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10973     return SDValue();
10974 
10975   SelectionDAG &DAG = DCI.DAG;
10976   EVT VT = N->getValueType(0);
10977 
10978   SDLoc SL(N);
10979   SDValue LHS = N->getOperand(0);
10980   SDValue RHS = N->getOperand(1);
10981 
10982   // These should really be instruction patterns, but writing patterns with
10983   // source modifiers is a pain.
10984 
10985   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10986   if (LHS.getOpcode() == ISD::FADD) {
10987     SDValue A = LHS.getOperand(0);
10988     if (A == LHS.getOperand(1)) {
10989       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10990       if (FusedOp != 0) {
10991         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10992         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10993       }
10994     }
10995   }
10996 
10997   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10998   if (RHS.getOpcode() == ISD::FADD) {
10999     SDValue A = RHS.getOperand(0);
11000     if (A == RHS.getOperand(1)) {
11001       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11002       if (FusedOp != 0) {
11003         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11004         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
11005       }
11006     }
11007   }
11008 
11009   return SDValue();
11010 }
11011 
11012 SDValue SITargetLowering::performFSubCombine(SDNode *N,
11013                                              DAGCombinerInfo &DCI) const {
11014   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11015     return SDValue();
11016 
11017   SelectionDAG &DAG = DCI.DAG;
11018   SDLoc SL(N);
11019   EVT VT = N->getValueType(0);
11020   assert(!VT.isVector());
11021 
11022   // Try to get the fneg to fold into the source modifier. This undoes generic
11023   // DAG combines and folds them into the mad.
11024   //
11025   // Only do this if we are not trying to support denormals. v_mad_f32 does
11026   // not support denormals ever.
11027   SDValue LHS = N->getOperand(0);
11028   SDValue RHS = N->getOperand(1);
11029   if (LHS.getOpcode() == ISD::FADD) {
11030     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
11031     SDValue A = LHS.getOperand(0);
11032     if (A == LHS.getOperand(1)) {
11033       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11034       if (FusedOp != 0){
11035         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11036         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
11037 
11038         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
11039       }
11040     }
11041   }
11042 
11043   if (RHS.getOpcode() == ISD::FADD) {
11044     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11045 
11046     SDValue A = RHS.getOperand(0);
11047     if (A == RHS.getOperand(1)) {
11048       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11049       if (FusedOp != 0){
11050         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11051         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11052       }
11053     }
11054   }
11055 
11056   return SDValue();
11057 }
11058 
11059 SDValue SITargetLowering::performFMACombine(SDNode *N,
11060                                             DAGCombinerInfo &DCI) const {
11061   SelectionDAG &DAG = DCI.DAG;
11062   EVT VT = N->getValueType(0);
11063   SDLoc SL(N);
11064 
11065   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11066     return SDValue();
11067 
11068   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11069   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11070   SDValue Op1 = N->getOperand(0);
11071   SDValue Op2 = N->getOperand(1);
11072   SDValue FMA = N->getOperand(2);
11073 
11074   if (FMA.getOpcode() != ISD::FMA ||
11075       Op1.getOpcode() != ISD::FP_EXTEND ||
11076       Op2.getOpcode() != ISD::FP_EXTEND)
11077     return SDValue();
11078 
11079   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11080   // regardless of the denorm mode setting. Therefore,
11081   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11082   const TargetOptions &Options = DAG.getTarget().Options;
11083   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11084       (N->getFlags().hasAllowContract() &&
11085        FMA->getFlags().hasAllowContract())) {
11086     Op1 = Op1.getOperand(0);
11087     Op2 = Op2.getOperand(0);
11088     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11089         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11090       return SDValue();
11091 
11092     SDValue Vec1 = Op1.getOperand(0);
11093     SDValue Idx1 = Op1.getOperand(1);
11094     SDValue Vec2 = Op2.getOperand(0);
11095 
11096     SDValue FMAOp1 = FMA.getOperand(0);
11097     SDValue FMAOp2 = FMA.getOperand(1);
11098     SDValue FMAAcc = FMA.getOperand(2);
11099 
11100     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11101         FMAOp2.getOpcode() != ISD::FP_EXTEND)
11102       return SDValue();
11103 
11104     FMAOp1 = FMAOp1.getOperand(0);
11105     FMAOp2 = FMAOp2.getOperand(0);
11106     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11107         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11108       return SDValue();
11109 
11110     SDValue Vec3 = FMAOp1.getOperand(0);
11111     SDValue Vec4 = FMAOp2.getOperand(0);
11112     SDValue Idx2 = FMAOp1.getOperand(1);
11113 
11114     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11115         // Idx1 and Idx2 cannot be the same.
11116         Idx1 == Idx2)
11117       return SDValue();
11118 
11119     if (Vec1 == Vec2 || Vec3 == Vec4)
11120       return SDValue();
11121 
11122     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11123       return SDValue();
11124 
11125     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11126         (Vec1 == Vec4 && Vec2 == Vec3)) {
11127       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11128                          DAG.getTargetConstant(0, SL, MVT::i1));
11129     }
11130   }
11131   return SDValue();
11132 }
11133 
11134 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11135                                               DAGCombinerInfo &DCI) const {
11136   SelectionDAG &DAG = DCI.DAG;
11137   SDLoc SL(N);
11138 
11139   SDValue LHS = N->getOperand(0);
11140   SDValue RHS = N->getOperand(1);
11141   EVT VT = LHS.getValueType();
11142   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11143 
11144   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11145   if (!CRHS) {
11146     CRHS = dyn_cast<ConstantSDNode>(LHS);
11147     if (CRHS) {
11148       std::swap(LHS, RHS);
11149       CC = getSetCCSwappedOperands(CC);
11150     }
11151   }
11152 
11153   if (CRHS) {
11154     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11155         isBoolSGPR(LHS.getOperand(0))) {
11156       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11157       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11158       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11159       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11160       if ((CRHS->isAllOnes() &&
11161            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11162           (CRHS->isZero() &&
11163            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11164         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11165                            DAG.getConstant(-1, SL, MVT::i1));
11166       if ((CRHS->isAllOnes() &&
11167            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11168           (CRHS->isZero() &&
11169            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11170         return LHS.getOperand(0);
11171     }
11172 
11173     const APInt &CRHSVal = CRHS->getAPIntValue();
11174     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11175         LHS.getOpcode() == ISD::SELECT &&
11176         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11177         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11178         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11179         isBoolSGPR(LHS.getOperand(0))) {
11180       // Given CT != FT:
11181       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11182       // setcc (select cc, CT, CF), CF, ne => cc
11183       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11184       // setcc (select cc, CT, CF), CT, eq => cc
11185       const APInt &CT = LHS.getConstantOperandAPInt(1);
11186       const APInt &CF = LHS.getConstantOperandAPInt(2);
11187 
11188       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11189           (CT == CRHSVal && CC == ISD::SETNE))
11190         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11191                            DAG.getConstant(-1, SL, MVT::i1));
11192       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11193           (CT == CRHSVal && CC == ISD::SETEQ))
11194         return LHS.getOperand(0);
11195     }
11196   }
11197 
11198   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11199                                            VT != MVT::f16))
11200     return SDValue();
11201 
11202   // Match isinf/isfinite pattern
11203   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11204   // (fcmp one (fabs x), inf) -> (fp_class x,
11205   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11206   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11207     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11208     if (!CRHS)
11209       return SDValue();
11210 
11211     const APFloat &APF = CRHS->getValueAPF();
11212     if (APF.isInfinity() && !APF.isNegative()) {
11213       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11214                                  SIInstrFlags::N_INFINITY;
11215       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11216                                     SIInstrFlags::P_ZERO |
11217                                     SIInstrFlags::N_NORMAL |
11218                                     SIInstrFlags::P_NORMAL |
11219                                     SIInstrFlags::N_SUBNORMAL |
11220                                     SIInstrFlags::P_SUBNORMAL;
11221       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11222       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11223                          DAG.getConstant(Mask, SL, MVT::i32));
11224     }
11225   }
11226 
11227   return SDValue();
11228 }
11229 
11230 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11231                                                      DAGCombinerInfo &DCI) const {
11232   SelectionDAG &DAG = DCI.DAG;
11233   SDLoc SL(N);
11234   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11235 
11236   SDValue Src = N->getOperand(0);
11237   SDValue Shift = N->getOperand(0);
11238 
11239   // TODO: Extend type shouldn't matter (assuming legal types).
11240   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11241     Shift = Shift.getOperand(0);
11242 
11243   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11244     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11245     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11246     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11247     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11248     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11249     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11250       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11251                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11252 
11253       unsigned ShiftOffset = 8 * Offset;
11254       if (Shift.getOpcode() == ISD::SHL)
11255         ShiftOffset -= C->getZExtValue();
11256       else
11257         ShiftOffset += C->getZExtValue();
11258 
11259       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11260         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11261                            MVT::f32, Shifted);
11262       }
11263     }
11264   }
11265 
11266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11267   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11268   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11269     // We simplified Src. If this node is not dead, visit it again so it is
11270     // folded properly.
11271     if (N->getOpcode() != ISD::DELETED_NODE)
11272       DCI.AddToWorklist(N);
11273     return SDValue(N, 0);
11274   }
11275 
11276   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11277   if (SDValue DemandedSrc =
11278           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11279     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11280 
11281   return SDValue();
11282 }
11283 
11284 SDValue SITargetLowering::performClampCombine(SDNode *N,
11285                                               DAGCombinerInfo &DCI) const {
11286   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11287   if (!CSrc)
11288     return SDValue();
11289 
11290   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11291   const APFloat &F = CSrc->getValueAPF();
11292   APFloat Zero = APFloat::getZero(F.getSemantics());
11293   if (F < Zero ||
11294       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11295     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11296   }
11297 
11298   APFloat One(F.getSemantics(), "1.0");
11299   if (F > One)
11300     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11301 
11302   return SDValue(CSrc, 0);
11303 }
11304 
11305 
11306 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11307                                             DAGCombinerInfo &DCI) const {
11308   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11309     return SDValue();
11310   switch (N->getOpcode()) {
11311   case ISD::ADD:
11312     return performAddCombine(N, DCI);
11313   case ISD::SUB:
11314     return performSubCombine(N, DCI);
11315   case ISD::ADDCARRY:
11316   case ISD::SUBCARRY:
11317     return performAddCarrySubCarryCombine(N, DCI);
11318   case ISD::FADD:
11319     return performFAddCombine(N, DCI);
11320   case ISD::FSUB:
11321     return performFSubCombine(N, DCI);
11322   case ISD::SETCC:
11323     return performSetCCCombine(N, DCI);
11324   case ISD::FMAXNUM:
11325   case ISD::FMINNUM:
11326   case ISD::FMAXNUM_IEEE:
11327   case ISD::FMINNUM_IEEE:
11328   case ISD::SMAX:
11329   case ISD::SMIN:
11330   case ISD::UMAX:
11331   case ISD::UMIN:
11332   case AMDGPUISD::FMIN_LEGACY:
11333   case AMDGPUISD::FMAX_LEGACY:
11334     return performMinMaxCombine(N, DCI);
11335   case ISD::FMA:
11336     return performFMACombine(N, DCI);
11337   case ISD::AND:
11338     return performAndCombine(N, DCI);
11339   case ISD::OR:
11340     return performOrCombine(N, DCI);
11341   case ISD::XOR:
11342     return performXorCombine(N, DCI);
11343   case ISD::ZERO_EXTEND:
11344     return performZeroExtendCombine(N, DCI);
11345   case ISD::SIGN_EXTEND_INREG:
11346     return performSignExtendInRegCombine(N , DCI);
11347   case AMDGPUISD::FP_CLASS:
11348     return performClassCombine(N, DCI);
11349   case ISD::FCANONICALIZE:
11350     return performFCanonicalizeCombine(N, DCI);
11351   case AMDGPUISD::RCP:
11352     return performRcpCombine(N, DCI);
11353   case AMDGPUISD::FRACT:
11354   case AMDGPUISD::RSQ:
11355   case AMDGPUISD::RCP_LEGACY:
11356   case AMDGPUISD::RCP_IFLAG:
11357   case AMDGPUISD::RSQ_CLAMP:
11358   case AMDGPUISD::LDEXP: {
11359     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11360     SDValue Src = N->getOperand(0);
11361     if (Src.isUndef())
11362       return Src;
11363     break;
11364   }
11365   case ISD::SINT_TO_FP:
11366   case ISD::UINT_TO_FP:
11367     return performUCharToFloatCombine(N, DCI);
11368   case AMDGPUISD::CVT_F32_UBYTE0:
11369   case AMDGPUISD::CVT_F32_UBYTE1:
11370   case AMDGPUISD::CVT_F32_UBYTE2:
11371   case AMDGPUISD::CVT_F32_UBYTE3:
11372     return performCvtF32UByteNCombine(N, DCI);
11373   case AMDGPUISD::FMED3:
11374     return performFMed3Combine(N, DCI);
11375   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11376     return performCvtPkRTZCombine(N, DCI);
11377   case AMDGPUISD::CLAMP:
11378     return performClampCombine(N, DCI);
11379   case ISD::SCALAR_TO_VECTOR: {
11380     SelectionDAG &DAG = DCI.DAG;
11381     EVT VT = N->getValueType(0);
11382 
11383     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11384     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11385       SDLoc SL(N);
11386       SDValue Src = N->getOperand(0);
11387       EVT EltVT = Src.getValueType();
11388       if (EltVT == MVT::f16)
11389         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11390 
11391       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11392       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11393     }
11394 
11395     break;
11396   }
11397   case ISD::EXTRACT_VECTOR_ELT:
11398     return performExtractVectorEltCombine(N, DCI);
11399   case ISD::INSERT_VECTOR_ELT:
11400     return performInsertVectorEltCombine(N, DCI);
11401   case ISD::LOAD: {
11402     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11403       return Widended;
11404     LLVM_FALLTHROUGH;
11405   }
11406   default: {
11407     if (!DCI.isBeforeLegalize()) {
11408       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11409         return performMemSDNodeCombine(MemNode, DCI);
11410     }
11411 
11412     break;
11413   }
11414   }
11415 
11416   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11417 }
11418 
11419 /// Helper function for adjustWritemask
11420 static unsigned SubIdx2Lane(unsigned Idx) {
11421   switch (Idx) {
11422   default: return ~0u;
11423   case AMDGPU::sub0: return 0;
11424   case AMDGPU::sub1: return 1;
11425   case AMDGPU::sub2: return 2;
11426   case AMDGPU::sub3: return 3;
11427   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11428   }
11429 }
11430 
11431 /// Adjust the writemask of MIMG instructions
11432 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11433                                           SelectionDAG &DAG) const {
11434   unsigned Opcode = Node->getMachineOpcode();
11435 
11436   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11437   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11438   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11439     return Node; // not implemented for D16
11440 
11441   SDNode *Users[5] = { nullptr };
11442   unsigned Lane = 0;
11443   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11444   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11445   unsigned NewDmask = 0;
11446   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11447   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11448   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11449                   Node->getConstantOperandVal(LWEIdx))
11450                      ? true
11451                      : false;
11452   unsigned TFCLane = 0;
11453   bool HasChain = Node->getNumValues() > 1;
11454 
11455   if (OldDmask == 0) {
11456     // These are folded out, but on the chance it happens don't assert.
11457     return Node;
11458   }
11459 
11460   unsigned OldBitsSet = countPopulation(OldDmask);
11461   // Work out which is the TFE/LWE lane if that is enabled.
11462   if (UsesTFC) {
11463     TFCLane = OldBitsSet;
11464   }
11465 
11466   // Try to figure out the used register components
11467   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11468        I != E; ++I) {
11469 
11470     // Don't look at users of the chain.
11471     if (I.getUse().getResNo() != 0)
11472       continue;
11473 
11474     // Abort if we can't understand the usage
11475     if (!I->isMachineOpcode() ||
11476         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11477       return Node;
11478 
11479     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11480     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11481     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11482     // set, etc.
11483     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11484     if (Lane == ~0u)
11485       return Node;
11486 
11487     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11488     if (UsesTFC && Lane == TFCLane) {
11489       Users[Lane] = *I;
11490     } else {
11491       // Set which texture component corresponds to the lane.
11492       unsigned Comp;
11493       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11494         Comp = countTrailingZeros(Dmask);
11495         Dmask &= ~(1 << Comp);
11496       }
11497 
11498       // Abort if we have more than one user per component.
11499       if (Users[Lane])
11500         return Node;
11501 
11502       Users[Lane] = *I;
11503       NewDmask |= 1 << Comp;
11504     }
11505   }
11506 
11507   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11508   bool NoChannels = !NewDmask;
11509   if (NoChannels) {
11510     if (!UsesTFC) {
11511       // No uses of the result and not using TFC. Then do nothing.
11512       return Node;
11513     }
11514     // If the original dmask has one channel - then nothing to do
11515     if (OldBitsSet == 1)
11516       return Node;
11517     // Use an arbitrary dmask - required for the instruction to work
11518     NewDmask = 1;
11519   }
11520   // Abort if there's no change
11521   if (NewDmask == OldDmask)
11522     return Node;
11523 
11524   unsigned BitsSet = countPopulation(NewDmask);
11525 
11526   // Check for TFE or LWE - increase the number of channels by one to account
11527   // for the extra return value
11528   // This will need adjustment for D16 if this is also included in
11529   // adjustWriteMask (this function) but at present D16 are excluded.
11530   unsigned NewChannels = BitsSet + UsesTFC;
11531 
11532   int NewOpcode =
11533       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11534   assert(NewOpcode != -1 &&
11535          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11536          "failed to find equivalent MIMG op");
11537 
11538   // Adjust the writemask in the node
11539   SmallVector<SDValue, 12> Ops;
11540   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11541   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11542   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11543 
11544   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11545 
11546   MVT ResultVT = NewChannels == 1 ?
11547     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11548                            NewChannels == 5 ? 8 : NewChannels);
11549   SDVTList NewVTList = HasChain ?
11550     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11551 
11552 
11553   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11554                                               NewVTList, Ops);
11555 
11556   if (HasChain) {
11557     // Update chain.
11558     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11559     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11560   }
11561 
11562   if (NewChannels == 1) {
11563     assert(Node->hasNUsesOfValue(1, 0));
11564     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11565                                       SDLoc(Node), Users[Lane]->getValueType(0),
11566                                       SDValue(NewNode, 0));
11567     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11568     return nullptr;
11569   }
11570 
11571   // Update the users of the node with the new indices
11572   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11573     SDNode *User = Users[i];
11574     if (!User) {
11575       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11576       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11577       if (i || !NoChannels)
11578         continue;
11579     } else {
11580       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11581       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11582     }
11583 
11584     switch (Idx) {
11585     default: break;
11586     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11587     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11588     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11589     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11590     }
11591   }
11592 
11593   DAG.RemoveDeadNode(Node);
11594   return nullptr;
11595 }
11596 
11597 static bool isFrameIndexOp(SDValue Op) {
11598   if (Op.getOpcode() == ISD::AssertZext)
11599     Op = Op.getOperand(0);
11600 
11601   return isa<FrameIndexSDNode>(Op);
11602 }
11603 
11604 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11605 /// with frame index operands.
11606 /// LLVM assumes that inputs are to these instructions are registers.
11607 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11608                                                         SelectionDAG &DAG) const {
11609   if (Node->getOpcode() == ISD::CopyToReg) {
11610     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11611     SDValue SrcVal = Node->getOperand(2);
11612 
11613     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11614     // to try understanding copies to physical registers.
11615     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11616       SDLoc SL(Node);
11617       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11618       SDValue VReg = DAG.getRegister(
11619         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11620 
11621       SDNode *Glued = Node->getGluedNode();
11622       SDValue ToVReg
11623         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11624                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11625       SDValue ToResultReg
11626         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11627                            VReg, ToVReg.getValue(1));
11628       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11629       DAG.RemoveDeadNode(Node);
11630       return ToResultReg.getNode();
11631     }
11632   }
11633 
11634   SmallVector<SDValue, 8> Ops;
11635   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11636     if (!isFrameIndexOp(Node->getOperand(i))) {
11637       Ops.push_back(Node->getOperand(i));
11638       continue;
11639     }
11640 
11641     SDLoc DL(Node);
11642     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11643                                      Node->getOperand(i).getValueType(),
11644                                      Node->getOperand(i)), 0));
11645   }
11646 
11647   return DAG.UpdateNodeOperands(Node, Ops);
11648 }
11649 
11650 /// Fold the instructions after selecting them.
11651 /// Returns null if users were already updated.
11652 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11653                                           SelectionDAG &DAG) const {
11654   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11655   unsigned Opcode = Node->getMachineOpcode();
11656 
11657   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11658       !TII->isGather4(Opcode) &&
11659       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11660     return adjustWritemask(Node, DAG);
11661   }
11662 
11663   if (Opcode == AMDGPU::INSERT_SUBREG ||
11664       Opcode == AMDGPU::REG_SEQUENCE) {
11665     legalizeTargetIndependentNode(Node, DAG);
11666     return Node;
11667   }
11668 
11669   switch (Opcode) {
11670   case AMDGPU::V_DIV_SCALE_F32_e64:
11671   case AMDGPU::V_DIV_SCALE_F64_e64: {
11672     // Satisfy the operand register constraint when one of the inputs is
11673     // undefined. Ordinarily each undef value will have its own implicit_def of
11674     // a vreg, so force these to use a single register.
11675     SDValue Src0 = Node->getOperand(1);
11676     SDValue Src1 = Node->getOperand(3);
11677     SDValue Src2 = Node->getOperand(5);
11678 
11679     if ((Src0.isMachineOpcode() &&
11680          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11681         (Src0 == Src1 || Src0 == Src2))
11682       break;
11683 
11684     MVT VT = Src0.getValueType().getSimpleVT();
11685     const TargetRegisterClass *RC =
11686         getRegClassFor(VT, Src0.getNode()->isDivergent());
11687 
11688     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11689     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11690 
11691     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11692                                       UndefReg, Src0, SDValue());
11693 
11694     // src0 must be the same register as src1 or src2, even if the value is
11695     // undefined, so make sure we don't violate this constraint.
11696     if (Src0.isMachineOpcode() &&
11697         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11698       if (Src1.isMachineOpcode() &&
11699           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11700         Src0 = Src1;
11701       else if (Src2.isMachineOpcode() &&
11702                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11703         Src0 = Src2;
11704       else {
11705         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11706         Src0 = UndefReg;
11707         Src1 = UndefReg;
11708       }
11709     } else
11710       break;
11711 
11712     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11713     Ops[1] = Src0;
11714     Ops[3] = Src1;
11715     Ops[5] = Src2;
11716     Ops.push_back(ImpDef.getValue(1));
11717     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11718   }
11719   default:
11720     break;
11721   }
11722 
11723   return Node;
11724 }
11725 
11726 // Any MIMG instructions that use tfe or lwe require an initialization of the
11727 // result register that will be written in the case of a memory access failure.
11728 // The required code is also added to tie this init code to the result of the
11729 // img instruction.
11730 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11731   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11732   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11733   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11734   MachineBasicBlock &MBB = *MI.getParent();
11735 
11736   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11737   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11738   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11739 
11740   if (!TFE && !LWE) // intersect_ray
11741     return;
11742 
11743   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11744   unsigned LWEVal = LWE->getImm();
11745   unsigned D16Val = D16 ? D16->getImm() : 0;
11746 
11747   if (!TFEVal && !LWEVal)
11748     return;
11749 
11750   // At least one of TFE or LWE are non-zero
11751   // We have to insert a suitable initialization of the result value and
11752   // tie this to the dest of the image instruction.
11753 
11754   const DebugLoc &DL = MI.getDebugLoc();
11755 
11756   int DstIdx =
11757       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11758 
11759   // Calculate which dword we have to initialize to 0.
11760   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11761 
11762   // check that dmask operand is found.
11763   assert(MO_Dmask && "Expected dmask operand in instruction");
11764 
11765   unsigned dmask = MO_Dmask->getImm();
11766   // Determine the number of active lanes taking into account the
11767   // Gather4 special case
11768   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11769 
11770   bool Packed = !Subtarget->hasUnpackedD16VMem();
11771 
11772   unsigned InitIdx =
11773       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11774 
11775   // Abandon attempt if the dst size isn't large enough
11776   // - this is in fact an error but this is picked up elsewhere and
11777   // reported correctly.
11778   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11779   if (DstSize < InitIdx)
11780     return;
11781 
11782   // Create a register for the initialization value.
11783   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11784   unsigned NewDst = 0; // Final initialized value will be in here
11785 
11786   // If PRTStrictNull feature is enabled (the default) then initialize
11787   // all the result registers to 0, otherwise just the error indication
11788   // register (VGPRn+1)
11789   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11790   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11791 
11792   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11793   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11794     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11795     // Initialize dword
11796     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11797     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11798       .addImm(0);
11799     // Insert into the super-reg
11800     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11801       .addReg(PrevDst)
11802       .addReg(SubReg)
11803       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11804 
11805     PrevDst = NewDst;
11806   }
11807 
11808   // Add as an implicit operand
11809   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11810 
11811   // Tie the just added implicit operand to the dst
11812   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11813 }
11814 
11815 /// Assign the register class depending on the number of
11816 /// bits set in the writemask
11817 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11818                                                      SDNode *Node) const {
11819   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11820 
11821   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11822 
11823   if (TII->isVOP3(MI.getOpcode())) {
11824     // Make sure constant bus requirements are respected.
11825     TII->legalizeOperandsVOP3(MRI, MI);
11826 
11827     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11828     // This saves a chain-copy of registers and better balance register
11829     // use between vgpr and agpr as agpr tuples tend to be big.
11830     if (MI.getDesc().OpInfo) {
11831       unsigned Opc = MI.getOpcode();
11832       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11833       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11834                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11835         if (I == -1)
11836           break;
11837         MachineOperand &Op = MI.getOperand(I);
11838         if (!Op.isReg() || !Op.getReg().isVirtual())
11839           continue;
11840         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11841         if (!TRI->hasAGPRs(RC))
11842           continue;
11843         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11844         if (!Src || !Src->isCopy() ||
11845             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11846           continue;
11847         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11848         // All uses of agpr64 and agpr32 can also accept vgpr except for
11849         // v_accvgpr_read, but we do not produce agpr reads during selection,
11850         // so no use checks are needed.
11851         MRI.setRegClass(Op.getReg(), NewRC);
11852       }
11853 
11854       // Resolve the rest of AV operands to AGPRs.
11855       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11856         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11857           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11858           if (TRI->isVectorSuperClass(RC)) {
11859             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11860             MRI.setRegClass(Src2->getReg(), NewRC);
11861             if (Src2->isTied())
11862               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11863           }
11864         }
11865       }
11866     }
11867 
11868     return;
11869   }
11870 
11871   if (TII->isMIMG(MI)) {
11872     if (!MI.mayStore())
11873       AddIMGInit(MI);
11874     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
11875   }
11876 }
11877 
11878 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11879                               uint64_t Val) {
11880   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11881   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11882 }
11883 
11884 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11885                                                 const SDLoc &DL,
11886                                                 SDValue Ptr) const {
11887   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11888 
11889   // Build the half of the subregister with the constants before building the
11890   // full 128-bit register. If we are building multiple resource descriptors,
11891   // this will allow CSEing of the 2-component register.
11892   const SDValue Ops0[] = {
11893     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11894     buildSMovImm32(DAG, DL, 0),
11895     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11896     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11897     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11898   };
11899 
11900   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11901                                                 MVT::v2i32, Ops0), 0);
11902 
11903   // Combine the constants and the pointer.
11904   const SDValue Ops1[] = {
11905     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11906     Ptr,
11907     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11908     SubRegHi,
11909     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11910   };
11911 
11912   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11913 }
11914 
11915 /// Return a resource descriptor with the 'Add TID' bit enabled
11916 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11917 ///        of the resource descriptor) to create an offset, which is added to
11918 ///        the resource pointer.
11919 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11920                                            SDValue Ptr, uint32_t RsrcDword1,
11921                                            uint64_t RsrcDword2And3) const {
11922   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11923   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11924   if (RsrcDword1) {
11925     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11926                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11927                     0);
11928   }
11929 
11930   SDValue DataLo = buildSMovImm32(DAG, DL,
11931                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11932   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11933 
11934   const SDValue Ops[] = {
11935     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11936     PtrLo,
11937     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11938     PtrHi,
11939     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11940     DataLo,
11941     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11942     DataHi,
11943     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11944   };
11945 
11946   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11947 }
11948 
11949 //===----------------------------------------------------------------------===//
11950 //                         SI Inline Assembly Support
11951 //===----------------------------------------------------------------------===//
11952 
11953 std::pair<unsigned, const TargetRegisterClass *>
11954 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11955                                                StringRef Constraint,
11956                                                MVT VT) const {
11957   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11958 
11959   const TargetRegisterClass *RC = nullptr;
11960   if (Constraint.size() == 1) {
11961     const unsigned BitWidth = VT.getSizeInBits();
11962     switch (Constraint[0]) {
11963     default:
11964       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11965     case 's':
11966     case 'r':
11967       switch (BitWidth) {
11968       case 16:
11969         RC = &AMDGPU::SReg_32RegClass;
11970         break;
11971       case 64:
11972         RC = &AMDGPU::SGPR_64RegClass;
11973         break;
11974       default:
11975         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11976         if (!RC)
11977           return std::make_pair(0U, nullptr);
11978         break;
11979       }
11980       break;
11981     case 'v':
11982       switch (BitWidth) {
11983       case 16:
11984         RC = &AMDGPU::VGPR_32RegClass;
11985         break;
11986       default:
11987         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11988         if (!RC)
11989           return std::make_pair(0U, nullptr);
11990         break;
11991       }
11992       break;
11993     case 'a':
11994       if (!Subtarget->hasMAIInsts())
11995         break;
11996       switch (BitWidth) {
11997       case 16:
11998         RC = &AMDGPU::AGPR_32RegClass;
11999         break;
12000       default:
12001         RC = TRI->getAGPRClassForBitWidth(BitWidth);
12002         if (!RC)
12003           return std::make_pair(0U, nullptr);
12004         break;
12005       }
12006       break;
12007     }
12008     // We actually support i128, i16 and f16 as inline parameters
12009     // even if they are not reported as legal
12010     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
12011                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
12012       return std::make_pair(0U, RC);
12013   }
12014 
12015   if (Constraint.startswith("{") && Constraint.endswith("}")) {
12016     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
12017     if (RegName.consume_front("v")) {
12018       RC = &AMDGPU::VGPR_32RegClass;
12019     } else if (RegName.consume_front("s")) {
12020       RC = &AMDGPU::SGPR_32RegClass;
12021     } else if (RegName.consume_front("a")) {
12022       RC = &AMDGPU::AGPR_32RegClass;
12023     }
12024 
12025     if (RC) {
12026       uint32_t Idx;
12027       if (RegName.consume_front("[")) {
12028         uint32_t End;
12029         bool Failed = RegName.consumeInteger(10, Idx);
12030         Failed |= !RegName.consume_front(":");
12031         Failed |= RegName.consumeInteger(10, End);
12032         Failed |= !RegName.consume_back("]");
12033         if (!Failed) {
12034           uint32_t Width = (End - Idx + 1) * 32;
12035           MCRegister Reg = RC->getRegister(Idx);
12036           if (SIRegisterInfo::isVGPRClass(RC))
12037             RC = TRI->getVGPRClassForBitWidth(Width);
12038           else if (SIRegisterInfo::isSGPRClass(RC))
12039             RC = TRI->getSGPRClassForBitWidth(Width);
12040           else if (SIRegisterInfo::isAGPRClass(RC))
12041             RC = TRI->getAGPRClassForBitWidth(Width);
12042           if (RC) {
12043             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12044             return std::make_pair(Reg, RC);
12045           }
12046         }
12047       } else {
12048         bool Failed = RegName.getAsInteger(10, Idx);
12049         if (!Failed && Idx < RC->getNumRegs())
12050           return std::make_pair(RC->getRegister(Idx), RC);
12051       }
12052     }
12053   }
12054 
12055   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12056   if (Ret.first)
12057     Ret.second = TRI->getPhysRegClass(Ret.first);
12058 
12059   return Ret;
12060 }
12061 
12062 static bool isImmConstraint(StringRef Constraint) {
12063   if (Constraint.size() == 1) {
12064     switch (Constraint[0]) {
12065     default: break;
12066     case 'I':
12067     case 'J':
12068     case 'A':
12069     case 'B':
12070     case 'C':
12071       return true;
12072     }
12073   } else if (Constraint == "DA" ||
12074              Constraint == "DB") {
12075     return true;
12076   }
12077   return false;
12078 }
12079 
12080 SITargetLowering::ConstraintType
12081 SITargetLowering::getConstraintType(StringRef Constraint) const {
12082   if (Constraint.size() == 1) {
12083     switch (Constraint[0]) {
12084     default: break;
12085     case 's':
12086     case 'v':
12087     case 'a':
12088       return C_RegisterClass;
12089     }
12090   }
12091   if (isImmConstraint(Constraint)) {
12092     return C_Other;
12093   }
12094   return TargetLowering::getConstraintType(Constraint);
12095 }
12096 
12097 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12098   if (!AMDGPU::isInlinableIntLiteral(Val)) {
12099     Val = Val & maskTrailingOnes<uint64_t>(Size);
12100   }
12101   return Val;
12102 }
12103 
12104 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12105                                                     std::string &Constraint,
12106                                                     std::vector<SDValue> &Ops,
12107                                                     SelectionDAG &DAG) const {
12108   if (isImmConstraint(Constraint)) {
12109     uint64_t Val;
12110     if (getAsmOperandConstVal(Op, Val) &&
12111         checkAsmConstraintVal(Op, Constraint, Val)) {
12112       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12113       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12114     }
12115   } else {
12116     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12117   }
12118 }
12119 
12120 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12121   unsigned Size = Op.getScalarValueSizeInBits();
12122   if (Size > 64)
12123     return false;
12124 
12125   if (Size == 16 && !Subtarget->has16BitInsts())
12126     return false;
12127 
12128   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12129     Val = C->getSExtValue();
12130     return true;
12131   }
12132   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12133     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12134     return true;
12135   }
12136   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12137     if (Size != 16 || Op.getNumOperands() != 2)
12138       return false;
12139     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12140       return false;
12141     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12142       Val = C->getSExtValue();
12143       return true;
12144     }
12145     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12146       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12147       return true;
12148     }
12149   }
12150 
12151   return false;
12152 }
12153 
12154 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12155                                              const std::string &Constraint,
12156                                              uint64_t Val) const {
12157   if (Constraint.size() == 1) {
12158     switch (Constraint[0]) {
12159     case 'I':
12160       return AMDGPU::isInlinableIntLiteral(Val);
12161     case 'J':
12162       return isInt<16>(Val);
12163     case 'A':
12164       return checkAsmConstraintValA(Op, Val);
12165     case 'B':
12166       return isInt<32>(Val);
12167     case 'C':
12168       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12169              AMDGPU::isInlinableIntLiteral(Val);
12170     default:
12171       break;
12172     }
12173   } else if (Constraint.size() == 2) {
12174     if (Constraint == "DA") {
12175       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12176       int64_t LoBits = static_cast<int32_t>(Val);
12177       return checkAsmConstraintValA(Op, HiBits, 32) &&
12178              checkAsmConstraintValA(Op, LoBits, 32);
12179     }
12180     if (Constraint == "DB") {
12181       return true;
12182     }
12183   }
12184   llvm_unreachable("Invalid asm constraint");
12185 }
12186 
12187 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12188                                               uint64_t Val,
12189                                               unsigned MaxSize) const {
12190   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12191   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12192   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12193       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12194       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12195     return true;
12196   }
12197   return false;
12198 }
12199 
12200 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12201   switch (UnalignedClassID) {
12202   case AMDGPU::VReg_64RegClassID:
12203     return AMDGPU::VReg_64_Align2RegClassID;
12204   case AMDGPU::VReg_96RegClassID:
12205     return AMDGPU::VReg_96_Align2RegClassID;
12206   case AMDGPU::VReg_128RegClassID:
12207     return AMDGPU::VReg_128_Align2RegClassID;
12208   case AMDGPU::VReg_160RegClassID:
12209     return AMDGPU::VReg_160_Align2RegClassID;
12210   case AMDGPU::VReg_192RegClassID:
12211     return AMDGPU::VReg_192_Align2RegClassID;
12212   case AMDGPU::VReg_224RegClassID:
12213     return AMDGPU::VReg_224_Align2RegClassID;
12214   case AMDGPU::VReg_256RegClassID:
12215     return AMDGPU::VReg_256_Align2RegClassID;
12216   case AMDGPU::VReg_512RegClassID:
12217     return AMDGPU::VReg_512_Align2RegClassID;
12218   case AMDGPU::VReg_1024RegClassID:
12219     return AMDGPU::VReg_1024_Align2RegClassID;
12220   case AMDGPU::AReg_64RegClassID:
12221     return AMDGPU::AReg_64_Align2RegClassID;
12222   case AMDGPU::AReg_96RegClassID:
12223     return AMDGPU::AReg_96_Align2RegClassID;
12224   case AMDGPU::AReg_128RegClassID:
12225     return AMDGPU::AReg_128_Align2RegClassID;
12226   case AMDGPU::AReg_160RegClassID:
12227     return AMDGPU::AReg_160_Align2RegClassID;
12228   case AMDGPU::AReg_192RegClassID:
12229     return AMDGPU::AReg_192_Align2RegClassID;
12230   case AMDGPU::AReg_256RegClassID:
12231     return AMDGPU::AReg_256_Align2RegClassID;
12232   case AMDGPU::AReg_512RegClassID:
12233     return AMDGPU::AReg_512_Align2RegClassID;
12234   case AMDGPU::AReg_1024RegClassID:
12235     return AMDGPU::AReg_1024_Align2RegClassID;
12236   default:
12237     return -1;
12238   }
12239 }
12240 
12241 // Figure out which registers should be reserved for stack access. Only after
12242 // the function is legalized do we know all of the non-spill stack objects or if
12243 // calls are present.
12244 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12245   MachineRegisterInfo &MRI = MF.getRegInfo();
12246   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12247   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12248   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12249   const SIInstrInfo *TII = ST.getInstrInfo();
12250 
12251   if (Info->isEntryFunction()) {
12252     // Callable functions have fixed registers used for stack access.
12253     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12254   }
12255 
12256   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12257                              Info->getStackPtrOffsetReg()));
12258   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12259     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12260 
12261   // We need to worry about replacing the default register with itself in case
12262   // of MIR testcases missing the MFI.
12263   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12264     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12265 
12266   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12267     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12268 
12269   Info->limitOccupancy(MF);
12270 
12271   if (ST.isWave32() && !MF.empty()) {
12272     for (auto &MBB : MF) {
12273       for (auto &MI : MBB) {
12274         TII->fixImplicitOperands(MI);
12275       }
12276     }
12277   }
12278 
12279   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12280   // classes if required. Ideally the register class constraints would differ
12281   // per-subtarget, but there's no easy way to achieve that right now. This is
12282   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12283   // from using them as the register class for legal types.
12284   if (ST.needsAlignedVGPRs()) {
12285     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12286       const Register Reg = Register::index2VirtReg(I);
12287       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12288       if (!RC)
12289         continue;
12290       int NewClassID = getAlignedAGPRClassID(RC->getID());
12291       if (NewClassID != -1)
12292         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12293     }
12294   }
12295 
12296   TargetLoweringBase::finalizeLowering(MF);
12297 }
12298 
12299 void SITargetLowering::computeKnownBitsForFrameIndex(
12300   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12301   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12302 
12303   // Set the high bits to zero based on the maximum allowed scratch size per
12304   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12305   // calculation won't overflow, so assume the sign bit is never set.
12306   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12307 }
12308 
12309 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12310                                    KnownBits &Known, unsigned Dim) {
12311   unsigned MaxValue =
12312       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12313   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12314 }
12315 
12316 void SITargetLowering::computeKnownBitsForTargetInstr(
12317     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12318     const MachineRegisterInfo &MRI, unsigned Depth) const {
12319   const MachineInstr *MI = MRI.getVRegDef(R);
12320   switch (MI->getOpcode()) {
12321   case AMDGPU::G_INTRINSIC: {
12322     switch (MI->getIntrinsicID()) {
12323     case Intrinsic::amdgcn_workitem_id_x:
12324       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12325       break;
12326     case Intrinsic::amdgcn_workitem_id_y:
12327       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12328       break;
12329     case Intrinsic::amdgcn_workitem_id_z:
12330       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12331       break;
12332     case Intrinsic::amdgcn_mbcnt_lo:
12333     case Intrinsic::amdgcn_mbcnt_hi: {
12334       // These return at most the wavefront size - 1.
12335       unsigned Size = MRI.getType(R).getSizeInBits();
12336       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12337       break;
12338     }
12339     case Intrinsic::amdgcn_groupstaticsize: {
12340       // We can report everything over the maximum size as 0. We can't report
12341       // based on the actual size because we don't know if it's accurate or not
12342       // at any given point.
12343       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12344       break;
12345     }
12346     }
12347     break;
12348   }
12349   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12350     Known.Zero.setHighBits(24);
12351     break;
12352   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12353     Known.Zero.setHighBits(16);
12354     break;
12355   }
12356 }
12357 
12358 Align SITargetLowering::computeKnownAlignForTargetInstr(
12359   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12360   unsigned Depth) const {
12361   const MachineInstr *MI = MRI.getVRegDef(R);
12362   switch (MI->getOpcode()) {
12363   case AMDGPU::G_INTRINSIC:
12364   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12365     // FIXME: Can this move to generic code? What about the case where the call
12366     // site specifies a lower alignment?
12367     Intrinsic::ID IID = MI->getIntrinsicID();
12368     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12369     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12370     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12371       return *RetAlign;
12372     return Align(1);
12373   }
12374   default:
12375     return Align(1);
12376   }
12377 }
12378 
12379 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12380   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12381   const Align CacheLineAlign = Align(64);
12382 
12383   // Pre-GFX10 target did not benefit from loop alignment
12384   if (!ML || DisableLoopAlignment ||
12385       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12386       getSubtarget()->hasInstFwdPrefetchBug())
12387     return PrefAlign;
12388 
12389   // On GFX10 I$ is 4 x 64 bytes cache lines.
12390   // By default prefetcher keeps one cache line behind and reads two ahead.
12391   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12392   // behind and one ahead.
12393   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12394   // If loop fits 64 bytes it always spans no more than two cache lines and
12395   // does not need an alignment.
12396   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12397   // Else if loop is less or equal 192 bytes we need two lines behind.
12398 
12399   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12400   const MachineBasicBlock *Header = ML->getHeader();
12401   if (Header->getAlignment() != PrefAlign)
12402     return Header->getAlignment(); // Already processed.
12403 
12404   unsigned LoopSize = 0;
12405   for (const MachineBasicBlock *MBB : ML->blocks()) {
12406     // If inner loop block is aligned assume in average half of the alignment
12407     // size to be added as nops.
12408     if (MBB != Header)
12409       LoopSize += MBB->getAlignment().value() / 2;
12410 
12411     for (const MachineInstr &MI : *MBB) {
12412       LoopSize += TII->getInstSizeInBytes(MI);
12413       if (LoopSize > 192)
12414         return PrefAlign;
12415     }
12416   }
12417 
12418   if (LoopSize <= 64)
12419     return PrefAlign;
12420 
12421   if (LoopSize <= 128)
12422     return CacheLineAlign;
12423 
12424   // If any of parent loops is surrounded by prefetch instructions do not
12425   // insert new for inner loop, which would reset parent's settings.
12426   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12427     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12428       auto I = Exit->getFirstNonDebugInstr();
12429       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12430         return CacheLineAlign;
12431     }
12432   }
12433 
12434   MachineBasicBlock *Pre = ML->getLoopPreheader();
12435   MachineBasicBlock *Exit = ML->getExitBlock();
12436 
12437   if (Pre && Exit) {
12438     auto PreTerm = Pre->getFirstTerminator();
12439     if (PreTerm == Pre->begin() ||
12440         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12441       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12442           .addImm(1); // prefetch 2 lines behind PC
12443 
12444     auto ExitHead = Exit->getFirstNonDebugInstr();
12445     if (ExitHead == Exit->end() ||
12446         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12447       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12448           .addImm(2); // prefetch 1 line behind PC
12449   }
12450 
12451   return CacheLineAlign;
12452 }
12453 
12454 LLVM_ATTRIBUTE_UNUSED
12455 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12456   assert(N->getOpcode() == ISD::CopyFromReg);
12457   do {
12458     // Follow the chain until we find an INLINEASM node.
12459     N = N->getOperand(0).getNode();
12460     if (N->getOpcode() == ISD::INLINEASM ||
12461         N->getOpcode() == ISD::INLINEASM_BR)
12462       return true;
12463   } while (N->getOpcode() == ISD::CopyFromReg);
12464   return false;
12465 }
12466 
12467 bool SITargetLowering::isSDNodeSourceOfDivergence(
12468     const SDNode *N, FunctionLoweringInfo *FLI,
12469     LegacyDivergenceAnalysis *KDA) const {
12470   switch (N->getOpcode()) {
12471   case ISD::CopyFromReg: {
12472     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12473     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12474     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12475     Register Reg = R->getReg();
12476 
12477     // FIXME: Why does this need to consider isLiveIn?
12478     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12479       return !TRI->isSGPRReg(MRI, Reg);
12480 
12481     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12482       return KDA->isDivergent(V);
12483 
12484     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12485     return !TRI->isSGPRReg(MRI, Reg);
12486   }
12487   case ISD::LOAD: {
12488     const LoadSDNode *L = cast<LoadSDNode>(N);
12489     unsigned AS = L->getAddressSpace();
12490     // A flat load may access private memory.
12491     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12492   }
12493   case ISD::CALLSEQ_END:
12494     return true;
12495   case ISD::INTRINSIC_WO_CHAIN:
12496     return AMDGPU::isIntrinsicSourceOfDivergence(
12497         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12498   case ISD::INTRINSIC_W_CHAIN:
12499     return AMDGPU::isIntrinsicSourceOfDivergence(
12500         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12501   case AMDGPUISD::ATOMIC_CMP_SWAP:
12502   case AMDGPUISD::ATOMIC_INC:
12503   case AMDGPUISD::ATOMIC_DEC:
12504   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12505   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12506   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12507   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12508   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12509   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12510   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12511   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12512   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12513   case AMDGPUISD::BUFFER_ATOMIC_AND:
12514   case AMDGPUISD::BUFFER_ATOMIC_OR:
12515   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12516   case AMDGPUISD::BUFFER_ATOMIC_INC:
12517   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12518   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12519   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12520   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12521   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12522   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12523     // Target-specific read-modify-write atomics are sources of divergence.
12524     return true;
12525   default:
12526     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12527       // Generic read-modify-write atomics are sources of divergence.
12528       return A->readMem() && A->writeMem();
12529     }
12530     return false;
12531   }
12532 }
12533 
12534 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12535                                                EVT VT) const {
12536   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12537   case MVT::f32:
12538     return hasFP32Denormals(DAG.getMachineFunction());
12539   case MVT::f64:
12540   case MVT::f16:
12541     return hasFP64FP16Denormals(DAG.getMachineFunction());
12542   default:
12543     return false;
12544   }
12545 }
12546 
12547 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12548                                                MachineFunction &MF) const {
12549   switch (Ty.getScalarSizeInBits()) {
12550   case 32:
12551     return hasFP32Denormals(MF);
12552   case 64:
12553   case 16:
12554     return hasFP64FP16Denormals(MF);
12555   default:
12556     return false;
12557   }
12558 }
12559 
12560 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12561                                                     const SelectionDAG &DAG,
12562                                                     bool SNaN,
12563                                                     unsigned Depth) const {
12564   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12565     const MachineFunction &MF = DAG.getMachineFunction();
12566     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12567 
12568     if (Info->getMode().DX10Clamp)
12569       return true; // Clamped to 0.
12570     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12571   }
12572 
12573   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12574                                                             SNaN, Depth);
12575 }
12576 
12577 // Global FP atomic instructions have a hardcoded FP mode and do not support
12578 // FP32 denormals, and only support v2f16 denormals.
12579 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12580   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12581   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12582   if (&Flt == &APFloat::IEEEsingle())
12583     return DenormMode == DenormalMode::getPreserveSign();
12584   return DenormMode == DenormalMode::getIEEE();
12585 }
12586 
12587 TargetLowering::AtomicExpansionKind
12588 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12589   unsigned AS = RMW->getPointerAddressSpace();
12590   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12591     return AtomicExpansionKind::NotAtomic;
12592 
12593   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12594     OptimizationRemarkEmitter ORE(RMW->getFunction());
12595     LLVMContext &Ctx = RMW->getFunction()->getContext();
12596     SmallVector<StringRef> SSNs;
12597     Ctx.getSyncScopeNames(SSNs);
12598     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12599                         ? "system"
12600                         : SSNs[RMW->getSyncScopeID()];
12601     ORE.emit([&]() {
12602       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12603              << "Hardware instruction generated for atomic "
12604              << RMW->getOperationName(RMW->getOperation())
12605              << " operation at memory scope " << MemScope
12606              << " due to an unsafe request.";
12607     });
12608     return Kind;
12609   };
12610 
12611   switch (RMW->getOperation()) {
12612   case AtomicRMWInst::FAdd: {
12613     Type *Ty = RMW->getType();
12614 
12615     // We don't have a way to support 16-bit atomics now, so just leave them
12616     // as-is.
12617     if (Ty->isHalfTy())
12618       return AtomicExpansionKind::None;
12619 
12620     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12621       return AtomicExpansionKind::CmpXChg;
12622 
12623     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12624          Subtarget->hasAtomicFaddInsts()) {
12625       if (Subtarget->hasGFX940Insts())
12626         return AtomicExpansionKind::None;
12627 
12628       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12629       // floating point atomic instructions. May generate more efficient code,
12630       // but may not respect rounding and denormal modes, and may give incorrect
12631       // results for certain memory destinations.
12632       if (RMW->getFunction()
12633               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12634               .getValueAsString() != "true")
12635         return AtomicExpansionKind::CmpXChg;
12636 
12637       if (Subtarget->hasGFX90AInsts()) {
12638         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12639           return AtomicExpansionKind::CmpXChg;
12640 
12641         auto SSID = RMW->getSyncScopeID();
12642         if (SSID == SyncScope::System ||
12643             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12644           return AtomicExpansionKind::CmpXChg;
12645 
12646         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12647       }
12648 
12649       if (AS == AMDGPUAS::FLAT_ADDRESS)
12650         return AtomicExpansionKind::CmpXChg;
12651 
12652       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12653                               : AtomicExpansionKind::CmpXChg;
12654     }
12655 
12656     // DS FP atomics do respect the denormal mode, but the rounding mode is
12657     // fixed to round-to-nearest-even.
12658     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12659     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12660       if (!Ty->isDoubleTy())
12661         return AtomicExpansionKind::None;
12662 
12663       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12664         return AtomicExpansionKind::None;
12665 
12666       return RMW->getFunction()
12667                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12668                          .getValueAsString() == "true"
12669                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12670                  : AtomicExpansionKind::CmpXChg;
12671     }
12672 
12673     return AtomicExpansionKind::CmpXChg;
12674   }
12675   default:
12676     break;
12677   }
12678 
12679   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12680 }
12681 
12682 TargetLowering::AtomicExpansionKind
12683 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12684   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12685              ? AtomicExpansionKind::NotAtomic
12686              : AtomicExpansionKind::None;
12687 }
12688 
12689 TargetLowering::AtomicExpansionKind
12690 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12691   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12692              ? AtomicExpansionKind::NotAtomic
12693              : AtomicExpansionKind::None;
12694 }
12695 
12696 TargetLowering::AtomicExpansionKind
12697 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12698   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12699              ? AtomicExpansionKind::NotAtomic
12700              : AtomicExpansionKind::None;
12701 }
12702 
12703 const TargetRegisterClass *
12704 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12705   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12706   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12707   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12708     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12709                                                : &AMDGPU::SReg_32RegClass;
12710   if (!TRI->isSGPRClass(RC) && !isDivergent)
12711     return TRI->getEquivalentSGPRClass(RC);
12712   else if (TRI->isSGPRClass(RC) && isDivergent)
12713     return TRI->getEquivalentVGPRClass(RC);
12714 
12715   return RC;
12716 }
12717 
12718 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12719 // uniform values (as produced by the mask results of control flow intrinsics)
12720 // used outside of divergent blocks. The phi users need to also be treated as
12721 // always uniform.
12722 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12723                       unsigned WaveSize) {
12724   // FIXME: We assume we never cast the mask results of a control flow
12725   // intrinsic.
12726   // Early exit if the type won't be consistent as a compile time hack.
12727   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12728   if (!IT || IT->getBitWidth() != WaveSize)
12729     return false;
12730 
12731   if (!isa<Instruction>(V))
12732     return false;
12733   if (!Visited.insert(V).second)
12734     return false;
12735   bool Result = false;
12736   for (auto U : V->users()) {
12737     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12738       if (V == U->getOperand(1)) {
12739         switch (Intrinsic->getIntrinsicID()) {
12740         default:
12741           Result = false;
12742           break;
12743         case Intrinsic::amdgcn_if_break:
12744         case Intrinsic::amdgcn_if:
12745         case Intrinsic::amdgcn_else:
12746           Result = true;
12747           break;
12748         }
12749       }
12750       if (V == U->getOperand(0)) {
12751         switch (Intrinsic->getIntrinsicID()) {
12752         default:
12753           Result = false;
12754           break;
12755         case Intrinsic::amdgcn_end_cf:
12756         case Intrinsic::amdgcn_loop:
12757           Result = true;
12758           break;
12759         }
12760       }
12761     } else {
12762       Result = hasCFUser(U, Visited, WaveSize);
12763     }
12764     if (Result)
12765       break;
12766   }
12767   return Result;
12768 }
12769 
12770 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12771                                                const Value *V) const {
12772   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12773     if (CI->isInlineAsm()) {
12774       // FIXME: This cannot give a correct answer. This should only trigger in
12775       // the case where inline asm returns mixed SGPR and VGPR results, used
12776       // outside the defining block. We don't have a specific result to
12777       // consider, so this assumes if any value is SGPR, the overall register
12778       // also needs to be SGPR.
12779       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12780       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12781           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12782       for (auto &TC : TargetConstraints) {
12783         if (TC.Type == InlineAsm::isOutput) {
12784           ComputeConstraintToUse(TC, SDValue());
12785           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12786               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12787           if (RC && SIRI->isSGPRClass(RC))
12788             return true;
12789         }
12790       }
12791     }
12792   }
12793   SmallPtrSet<const Value *, 16> Visited;
12794   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12795 }
12796 
12797 std::pair<InstructionCost, MVT>
12798 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12799                                           Type *Ty) const {
12800   std::pair<InstructionCost, MVT> Cost =
12801       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12802   auto Size = DL.getTypeSizeInBits(Ty);
12803   // Maximum load or store can handle 8 dwords for scalar and 4 for
12804   // vector ALU. Let's assume anything above 8 dwords is expensive
12805   // even if legal.
12806   if (Size <= 256)
12807     return Cost;
12808 
12809   Cost.first += (Size + 255) / 256;
12810   return Cost;
12811 }
12812 
12813 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12814   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12815   for (; I != E; ++I) {
12816     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12817       if (getBasePtrIndex(M) == I.getOperandNo())
12818         return true;
12819     }
12820   }
12821   return false;
12822 }
12823 
12824 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12825                                            SDValue N1) const {
12826   if (!N0.hasOneUse())
12827     return false;
12828   // Take care of the opportunity to keep N0 uniform
12829   if (N0->isDivergent() || !N1->isDivergent())
12830     return true;
12831   // Check if we have a good chance to form the memory access pattern with the
12832   // base and offset
12833   return (DAG.isBaseWithConstantOffset(N0) &&
12834           hasMemSDNodeUser(*N0->use_begin()));
12835 }
12836 
12837 MachineMemOperand::Flags
12838 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12839   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12840   if (I.getMetadata("amdgpu.noclobber"))
12841     return MONoClobber;
12842   return MachineMemOperand::MONone;
12843 }
12844