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 "AMDGPUSubtarget.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/IntrinsicsAMDGPU.h"
29 #include "llvm/IR/IntrinsicsR600.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/KnownBits.h"
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "si-lower"
36 
37 STATISTIC(NumTailCalls, "Number of tail calls");
38 
39 static cl::opt<bool> DisableLoopAlignment(
40   "amdgpu-disable-loop-alignment",
41   cl::desc("Do not align and prefetch loops"),
42   cl::init(false));
43 
44 static cl::opt<bool> VGPRReserveforSGPRSpill(
45     "amdgpu-reserve-vgpr-for-sgpr-spill",
46     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
47 
48 static cl::opt<bool> UseDivergentRegisterIndexing(
49   "amdgpu-use-divergent-register-indexing",
50   cl::Hidden,
51   cl::desc("Use indirect register addressing for divergent indexes"),
52   cl::init(false));
53 
54 static bool hasFP32Denormals(const MachineFunction &MF) {
55   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56   return Info->getMode().allFP32Denormals();
57 }
58 
59 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61   return Info->getMode().allFP64FP16Denormals();
62 }
63 
64 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68       return AMDGPU::SGPR0 + Reg;
69     }
70   }
71   llvm_unreachable("Cannot allocate sgpr");
72 }
73 
74 SITargetLowering::SITargetLowering(const TargetMachine &TM,
75                                    const GCNSubtarget &STI)
76     : AMDGPUTargetLowering(TM, STI),
77       Subtarget(&STI) {
78   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80 
81   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83 
84   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
85   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
86   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
87 
88   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
89   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
90 
91   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
92   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
93 
94   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
95   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
96 
97   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
98   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
99 
100   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
101   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
102 
103   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
104   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
105 
106   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
107   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
108 
109   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
110   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
111 
112   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
113   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
114 
115   if (Subtarget->has16BitInsts()) {
116     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
117     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
118 
119     // Unless there are also VOP3P operations, not operations are really legal.
120     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
121     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
122     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
123     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
124   }
125 
126   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
127   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
128 
129   computeRegisterProperties(Subtarget->getRegisterInfo());
130 
131   // The boolean content concept here is too inflexible. Compares only ever
132   // really produce a 1-bit result. Any copy/extend from these will turn into a
133   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
134   // it's what most targets use.
135   setBooleanContents(ZeroOrOneBooleanContent);
136   setBooleanVectorContents(ZeroOrOneBooleanContent);
137 
138   // We need to custom lower vector stores from local memory
139   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
140   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
141   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
142   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
143   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
144   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
145   setOperationAction(ISD::LOAD, MVT::i1, Custom);
146   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
147 
148   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
149   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
150   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
151   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
152   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
153   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
154   setOperationAction(ISD::STORE, MVT::i1, Custom);
155   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
156 
157   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
158   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
159   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
160   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
161   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
162   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
163   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
164   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
165   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
166   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
167   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
168   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
169   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
170   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
171   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
172   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
173 
174   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
175   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
176   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
177   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
178   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
179 
180   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
181   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
182 
183   setOperationAction(ISD::SELECT, MVT::i1, Promote);
184   setOperationAction(ISD::SELECT, MVT::i64, Custom);
185   setOperationAction(ISD::SELECT, MVT::f64, Promote);
186   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
187 
188   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
189   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
190   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
191   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
192   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
193 
194   setOperationAction(ISD::SETCC, MVT::i1, Promote);
195   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
196   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
197   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
198 
199   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
200   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
201   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
202   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
203   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
204   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
205   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
206   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
207 
208   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
209   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
210   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
216 
217   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
218   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
219   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
220   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
221   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
222   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
223 
224   setOperationAction(ISD::UADDO, MVT::i32, Legal);
225   setOperationAction(ISD::USUBO, MVT::i32, Legal);
226 
227   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
228   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
229 
230   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
231   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
232   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
233 
234 #if 0
235   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
236   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
237 #endif
238 
239   // We only support LOAD/STORE and vector manipulation ops for vectors
240   // with > 4 elements.
241   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
242                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
243                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
244                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
245     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
246       switch (Op) {
247       case ISD::LOAD:
248       case ISD::STORE:
249       case ISD::BUILD_VECTOR:
250       case ISD::BITCAST:
251       case ISD::EXTRACT_VECTOR_ELT:
252       case ISD::INSERT_VECTOR_ELT:
253       case ISD::INSERT_SUBVECTOR:
254       case ISD::EXTRACT_SUBVECTOR:
255       case ISD::SCALAR_TO_VECTOR:
256         break;
257       case ISD::CONCAT_VECTORS:
258         setOperationAction(Op, VT, Custom);
259         break;
260       default:
261         setOperationAction(Op, VT, Expand);
262         break;
263       }
264     }
265   }
266 
267   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
268 
269   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
270   // is expanded to avoid having two separate loops in case the index is a VGPR.
271 
272   // Most operations are naturally 32-bit vector operations. We only support
273   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
274   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
275     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
276     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
277 
278     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
279     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
280 
281     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
282     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
283 
284     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
285     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
286   }
287 
288   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
289     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
290     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
291 
292     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
293     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
294 
295     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
296     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
297 
298     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
299     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
300   }
301 
302   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
303     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
305 
306     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
307     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
308 
309     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
311 
312     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
313     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
314   }
315 
316   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
317     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
319 
320     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
321     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
322 
323     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
325 
326     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
328   }
329 
330   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
331   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
332   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
333   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
334 
335   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
336   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
337 
338   // Avoid stack access for these.
339   // TODO: Generalize to more vector types.
340   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
341   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
342   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
343   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
344 
345   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
346   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
347   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
348   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
349   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
350 
351   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
352   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
353   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
354 
355   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
356   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
357   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
358   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
359 
360   // Deal with vec3 vector operations when widened to vec4.
361   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
362   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
363   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
364   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
365 
366   // Deal with vec5 vector operations when widened to vec8.
367   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
368   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
369   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
370   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
371 
372   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
373   // and output demarshalling
374   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
375   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
376 
377   // We can't return success/failure, only the old value,
378   // let LLVM add the comparison
379   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
380   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
381 
382   if (Subtarget->hasFlatAddressSpace()) {
383     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
384     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
385   }
386 
387   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
388 
389   // FIXME: This should be narrowed to i32, but that only happens if i64 is
390   // illegal.
391   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
392   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
393   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
394 
395   // On SI this is s_memtime and s_memrealtime on VI.
396   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
397   setOperationAction(ISD::TRAP, MVT::Other, Custom);
398   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
399 
400   if (Subtarget->has16BitInsts()) {
401     setOperationAction(ISD::FPOW, MVT::f16, Promote);
402     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
403     setOperationAction(ISD::FLOG, MVT::f16, Custom);
404     setOperationAction(ISD::FEXP, MVT::f16, Custom);
405     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
406   }
407 
408   if (Subtarget->hasMadMacF32Insts())
409     setOperationAction(ISD::FMAD, MVT::f32, Legal);
410 
411   if (!Subtarget->hasBFI()) {
412     // fcopysign can be done in a single instruction with BFI.
413     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
414     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
415   }
416 
417   if (!Subtarget->hasBCNT(32))
418     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
419 
420   if (!Subtarget->hasBCNT(64))
421     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
422 
423   if (Subtarget->hasFFBH())
424     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
425 
426   if (Subtarget->hasFFBL())
427     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
428 
429   // We only really have 32-bit BFE instructions (and 16-bit on VI).
430   //
431   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
432   // effort to match them now. We want this to be false for i64 cases when the
433   // extraction isn't restricted to the upper or lower half. Ideally we would
434   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
435   // span the midpoint are probably relatively rare, so don't worry about them
436   // for now.
437   if (Subtarget->hasBFE())
438     setHasExtractBitsInsn(true);
439 
440   // Clamp modifier on add/sub
441   if (Subtarget->hasIntClamp()) {
442     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
443     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
444   }
445 
446   if (Subtarget->hasAddNoCarry()) {
447     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
448     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
449     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
450     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
451   }
452 
453   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
454   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
455   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
456   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
457 
458 
459   // These are really only legal for ieee_mode functions. We should be avoiding
460   // them for functions that don't have ieee_mode enabled, so just say they are
461   // legal.
462   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
463   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
464   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
465   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
466 
467 
468   if (Subtarget->haveRoundOpsF64()) {
469     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
470     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
471     setOperationAction(ISD::FRINT, MVT::f64, Legal);
472   } else {
473     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
474     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
475     setOperationAction(ISD::FRINT, MVT::f64, Custom);
476     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
477   }
478 
479   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
480 
481   setOperationAction(ISD::FSIN, MVT::f32, Custom);
482   setOperationAction(ISD::FCOS, MVT::f32, Custom);
483   setOperationAction(ISD::FDIV, MVT::f32, Custom);
484   setOperationAction(ISD::FDIV, MVT::f64, Custom);
485 
486   if (Subtarget->has16BitInsts()) {
487     setOperationAction(ISD::Constant, MVT::i16, Legal);
488 
489     setOperationAction(ISD::SMIN, MVT::i16, Legal);
490     setOperationAction(ISD::SMAX, MVT::i16, Legal);
491 
492     setOperationAction(ISD::UMIN, MVT::i16, Legal);
493     setOperationAction(ISD::UMAX, MVT::i16, Legal);
494 
495     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
496     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
497 
498     setOperationAction(ISD::ROTR, MVT::i16, Expand);
499     setOperationAction(ISD::ROTL, MVT::i16, Expand);
500 
501     setOperationAction(ISD::SDIV, MVT::i16, Promote);
502     setOperationAction(ISD::UDIV, MVT::i16, Promote);
503     setOperationAction(ISD::SREM, MVT::i16, Promote);
504     setOperationAction(ISD::UREM, MVT::i16, Promote);
505     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
506     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
507 
508     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
509 
510     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
511     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
512     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
513     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
514     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
515 
516     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
517 
518     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
519 
520     setOperationAction(ISD::LOAD, MVT::i16, Custom);
521 
522     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
523 
524     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
525     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
526     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
527     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
528 
529     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
530     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
531 
532     // F16 - Constant Actions.
533     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
534 
535     // F16 - Load/Store Actions.
536     setOperationAction(ISD::LOAD, MVT::f16, Promote);
537     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
538     setOperationAction(ISD::STORE, MVT::f16, Promote);
539     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
540 
541     // F16 - VOP1 Actions.
542     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
543     setOperationAction(ISD::FCOS, MVT::f16, Custom);
544     setOperationAction(ISD::FSIN, MVT::f16, Custom);
545 
546     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
547     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
548 
549     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
550     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
551     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
552     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
553     setOperationAction(ISD::FROUND, MVT::f16, Custom);
554 
555     // F16 - VOP2 Actions.
556     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
557     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
558 
559     setOperationAction(ISD::FDIV, MVT::f16, Custom);
560 
561     // F16 - VOP3 Actions.
562     setOperationAction(ISD::FMA, MVT::f16, Legal);
563     if (STI.hasMadF16())
564       setOperationAction(ISD::FMAD, MVT::f16, Legal);
565 
566     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
567       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
568         switch (Op) {
569         case ISD::LOAD:
570         case ISD::STORE:
571         case ISD::BUILD_VECTOR:
572         case ISD::BITCAST:
573         case ISD::EXTRACT_VECTOR_ELT:
574         case ISD::INSERT_VECTOR_ELT:
575         case ISD::INSERT_SUBVECTOR:
576         case ISD::EXTRACT_SUBVECTOR:
577         case ISD::SCALAR_TO_VECTOR:
578           break;
579         case ISD::CONCAT_VECTORS:
580           setOperationAction(Op, VT, Custom);
581           break;
582         default:
583           setOperationAction(Op, VT, Expand);
584           break;
585         }
586       }
587     }
588 
589     // v_perm_b32 can handle either of these.
590     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
591     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
592     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
593 
594     // XXX - Do these do anything? Vector constants turn into build_vector.
595     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
596     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
597 
598     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
599     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
600 
601     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
602     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
603     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
604     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
605 
606     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
607     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
608     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
609     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
610 
611     setOperationAction(ISD::AND, MVT::v2i16, Promote);
612     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
613     setOperationAction(ISD::OR, MVT::v2i16, Promote);
614     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
615     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
616     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
617 
618     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
619     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
620     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
621     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
622 
623     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
624     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
625     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
626     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
627 
628     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
629     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
630     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
631     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
632 
633     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
634     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
635     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
636 
637     if (!Subtarget->hasVOP3PInsts()) {
638       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
639       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
640     }
641 
642     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
643     // This isn't really legal, but this avoids the legalizer unrolling it (and
644     // allows matching fneg (fabs x) patterns)
645     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
646 
647     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
648     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
649     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
650     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
651 
652     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
653     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
654 
655     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
656     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
657   }
658 
659   if (Subtarget->hasVOP3PInsts()) {
660     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
661     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
662     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
663     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
664     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
665     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
666     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
667     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
668     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
669     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
670 
671     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
672     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
673     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
674     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
675 
676     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
677     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
678     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
679 
680     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
681     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
682 
683     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
684 
685     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
686     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
687 
688     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
689     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
690 
691     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
692     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
693     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
694     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
695     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
696     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
697 
698     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
699     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
700     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
701     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
702 
703     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
704     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
705     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
706     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
707 
708     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
709     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
710     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
711 
712     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
713     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
714 
715     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
716     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
717     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
718 
719     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
720     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
721     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
722   }
723 
724   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
725   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
726 
727   if (Subtarget->has16BitInsts()) {
728     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
729     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
730     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
731     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
732   } else {
733     // Legalization hack.
734     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
735     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
736 
737     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
738     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
739   }
740 
741   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
742     setOperationAction(ISD::SELECT, VT, Custom);
743   }
744 
745   setOperationAction(ISD::SMULO, MVT::i64, Custom);
746   setOperationAction(ISD::UMULO, MVT::i64, Custom);
747 
748   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
749   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
750   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
751   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
752   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
753   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
754   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
755 
756   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
757   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
758   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
759   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
760   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
761   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
762   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
763   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
764   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
765   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
766   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
767 
768   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
769   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
770   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
771   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
772   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
773   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
774   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
775   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
776   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
777   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
778 
779   setTargetDAGCombine(ISD::ADD);
780   setTargetDAGCombine(ISD::ADDCARRY);
781   setTargetDAGCombine(ISD::SUB);
782   setTargetDAGCombine(ISD::SUBCARRY);
783   setTargetDAGCombine(ISD::FADD);
784   setTargetDAGCombine(ISD::FSUB);
785   setTargetDAGCombine(ISD::FMINNUM);
786   setTargetDAGCombine(ISD::FMAXNUM);
787   setTargetDAGCombine(ISD::FMINNUM_IEEE);
788   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
789   setTargetDAGCombine(ISD::FMA);
790   setTargetDAGCombine(ISD::SMIN);
791   setTargetDAGCombine(ISD::SMAX);
792   setTargetDAGCombine(ISD::UMIN);
793   setTargetDAGCombine(ISD::UMAX);
794   setTargetDAGCombine(ISD::SETCC);
795   setTargetDAGCombine(ISD::AND);
796   setTargetDAGCombine(ISD::OR);
797   setTargetDAGCombine(ISD::XOR);
798   setTargetDAGCombine(ISD::SINT_TO_FP);
799   setTargetDAGCombine(ISD::UINT_TO_FP);
800   setTargetDAGCombine(ISD::FCANONICALIZE);
801   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
802   setTargetDAGCombine(ISD::ZERO_EXTEND);
803   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
804   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
805   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
806 
807   // All memory operations. Some folding on the pointer operand is done to help
808   // matching the constant offsets in the addressing modes.
809   setTargetDAGCombine(ISD::LOAD);
810   setTargetDAGCombine(ISD::STORE);
811   setTargetDAGCombine(ISD::ATOMIC_LOAD);
812   setTargetDAGCombine(ISD::ATOMIC_STORE);
813   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
814   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
815   setTargetDAGCombine(ISD::ATOMIC_SWAP);
816   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
817   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
818   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
819   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
820   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
821   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
822   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
823   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
824   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
825   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
826   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
827   setTargetDAGCombine(ISD::INTRINSIC_VOID);
828   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
829 
830   // FIXME: In other contexts we pretend this is a per-function property.
831   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
832 
833   setSchedulingPreference(Sched::RegPressure);
834 }
835 
836 const GCNSubtarget *SITargetLowering::getSubtarget() const {
837   return Subtarget;
838 }
839 
840 //===----------------------------------------------------------------------===//
841 // TargetLowering queries
842 //===----------------------------------------------------------------------===//
843 
844 // v_mad_mix* support a conversion from f16 to f32.
845 //
846 // There is only one special case when denormals are enabled we don't currently,
847 // where this is OK to use.
848 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
849                                        EVT DestVT, EVT SrcVT) const {
850   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
851           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
852     DestVT.getScalarType() == MVT::f32 &&
853     SrcVT.getScalarType() == MVT::f16 &&
854     // TODO: This probably only requires no input flushing?
855     !hasFP32Denormals(DAG.getMachineFunction());
856 }
857 
858 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
859   // SI has some legal vector types, but no legal vector operations. Say no
860   // shuffles are legal in order to prefer scalarizing some vector operations.
861   return false;
862 }
863 
864 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
865                                                     CallingConv::ID CC,
866                                                     EVT VT) const {
867   if (CC == CallingConv::AMDGPU_KERNEL)
868     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
869 
870   if (VT.isVector()) {
871     EVT ScalarVT = VT.getScalarType();
872     unsigned Size = ScalarVT.getSizeInBits();
873     if (Size == 16) {
874       if (Subtarget->has16BitInsts())
875         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
876       return VT.isInteger() ? MVT::i32 : MVT::f32;
877     }
878 
879     if (Size < 16)
880       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
881     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
882   }
883 
884   if (VT.getSizeInBits() > 32)
885     return MVT::i32;
886 
887   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
888 }
889 
890 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
891                                                          CallingConv::ID CC,
892                                                          EVT VT) const {
893   if (CC == CallingConv::AMDGPU_KERNEL)
894     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
895 
896   if (VT.isVector()) {
897     unsigned NumElts = VT.getVectorNumElements();
898     EVT ScalarVT = VT.getScalarType();
899     unsigned Size = ScalarVT.getSizeInBits();
900 
901     // FIXME: Should probably promote 8-bit vectors to i16.
902     if (Size == 16 && Subtarget->has16BitInsts())
903       return (NumElts + 1) / 2;
904 
905     if (Size <= 32)
906       return NumElts;
907 
908     if (Size > 32)
909       return NumElts * ((Size + 31) / 32);
910   } else if (VT.getSizeInBits() > 32)
911     return (VT.getSizeInBits() + 31) / 32;
912 
913   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
914 }
915 
916 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
917   LLVMContext &Context, CallingConv::ID CC,
918   EVT VT, EVT &IntermediateVT,
919   unsigned &NumIntermediates, MVT &RegisterVT) const {
920   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
921     unsigned NumElts = VT.getVectorNumElements();
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     // FIXME: We should fix the ABI to be the same on targets without 16-bit
925     // support, but unless we can properly handle 3-vectors, it will be still be
926     // inconsistent.
927     if (Size == 16 && Subtarget->has16BitInsts()) {
928       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
929       IntermediateVT = RegisterVT;
930       NumIntermediates = (NumElts + 1) / 2;
931       return NumIntermediates;
932     }
933 
934     if (Size == 32) {
935       RegisterVT = ScalarVT.getSimpleVT();
936       IntermediateVT = RegisterVT;
937       NumIntermediates = NumElts;
938       return NumIntermediates;
939     }
940 
941     if (Size < 16 && Subtarget->has16BitInsts()) {
942       // FIXME: Should probably form v2i16 pieces
943       RegisterVT = MVT::i16;
944       IntermediateVT = ScalarVT;
945       NumIntermediates = NumElts;
946       return NumIntermediates;
947     }
948 
949 
950     if (Size != 16 && Size <= 32) {
951       RegisterVT = MVT::i32;
952       IntermediateVT = ScalarVT;
953       NumIntermediates = NumElts;
954       return NumIntermediates;
955     }
956 
957     if (Size > 32) {
958       RegisterVT = MVT::i32;
959       IntermediateVT = RegisterVT;
960       NumIntermediates = NumElts * ((Size + 31) / 32);
961       return NumIntermediates;
962     }
963   }
964 
965   return TargetLowering::getVectorTypeBreakdownForCallingConv(
966     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
967 }
968 
969 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
970   assert(DMaskLanes != 0);
971 
972   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
973     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
974     return EVT::getVectorVT(Ty->getContext(),
975                             EVT::getEVT(VT->getElementType()),
976                             NumElts);
977   }
978 
979   return EVT::getEVT(Ty);
980 }
981 
982 // Peek through TFE struct returns to only use the data size.
983 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
984   auto *ST = dyn_cast<StructType>(Ty);
985   if (!ST)
986     return memVTFromImageData(Ty, DMaskLanes);
987 
988   // Some intrinsics return an aggregate type - special case to work out the
989   // correct memVT.
990   //
991   // Only limited forms of aggregate type currently expected.
992   if (ST->getNumContainedTypes() != 2 ||
993       !ST->getContainedType(1)->isIntegerTy(32))
994     return EVT();
995   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
996 }
997 
998 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
999                                           const CallInst &CI,
1000                                           MachineFunction &MF,
1001                                           unsigned IntrID) const {
1002   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1003           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1004     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1005                                                   (Intrinsic::ID)IntrID);
1006     if (Attr.hasFnAttribute(Attribute::ReadNone))
1007       return false;
1008 
1009     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1010 
1011     if (RsrcIntr->IsImage) {
1012       Info.ptrVal = MFI->getImagePSV(
1013         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1014         CI.getArgOperand(RsrcIntr->RsrcArg));
1015       Info.align.reset();
1016     } else {
1017       Info.ptrVal = MFI->getBufferPSV(
1018         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1019         CI.getArgOperand(RsrcIntr->RsrcArg));
1020     }
1021 
1022     Info.flags = MachineMemOperand::MODereferenceable;
1023     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1024       unsigned DMaskLanes = 4;
1025 
1026       if (RsrcIntr->IsImage) {
1027         const AMDGPU::ImageDimIntrinsicInfo *Intr
1028           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1029         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1030           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1031 
1032         if (!BaseOpcode->Gather4) {
1033           // If this isn't a gather, we may have excess loaded elements in the
1034           // IR type. Check the dmask for the real number of elements loaded.
1035           unsigned DMask
1036             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1037           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1038         }
1039 
1040         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1041       } else
1042         Info.memVT = EVT::getEVT(CI.getType());
1043 
1044       // FIXME: What does alignment mean for an image?
1045       Info.opc = ISD::INTRINSIC_W_CHAIN;
1046       Info.flags |= MachineMemOperand::MOLoad;
1047     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1048       Info.opc = ISD::INTRINSIC_VOID;
1049 
1050       Type *DataTy = CI.getArgOperand(0)->getType();
1051       if (RsrcIntr->IsImage) {
1052         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1053         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1054         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1055       } else
1056         Info.memVT = EVT::getEVT(DataTy);
1057 
1058       Info.flags |= MachineMemOperand::MOStore;
1059     } else {
1060       // Atomic
1061       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1062                                             ISD::INTRINSIC_W_CHAIN;
1063       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1064       Info.flags = MachineMemOperand::MOLoad |
1065                    MachineMemOperand::MOStore |
1066                    MachineMemOperand::MODereferenceable;
1067 
1068       // XXX - Should this be volatile without known ordering?
1069       Info.flags |= MachineMemOperand::MOVolatile;
1070     }
1071     return true;
1072   }
1073 
1074   switch (IntrID) {
1075   case Intrinsic::amdgcn_atomic_inc:
1076   case Intrinsic::amdgcn_atomic_dec:
1077   case Intrinsic::amdgcn_ds_ordered_add:
1078   case Intrinsic::amdgcn_ds_ordered_swap:
1079   case Intrinsic::amdgcn_ds_fadd:
1080   case Intrinsic::amdgcn_ds_fmin:
1081   case Intrinsic::amdgcn_ds_fmax: {
1082     Info.opc = ISD::INTRINSIC_W_CHAIN;
1083     Info.memVT = MVT::getVT(CI.getType());
1084     Info.ptrVal = CI.getOperand(0);
1085     Info.align.reset();
1086     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1087 
1088     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1089     if (!Vol->isZero())
1090       Info.flags |= MachineMemOperand::MOVolatile;
1091 
1092     return true;
1093   }
1094   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1095     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1096 
1097     Info.opc = ISD::INTRINSIC_W_CHAIN;
1098     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1099     Info.ptrVal = MFI->getBufferPSV(
1100       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1101       CI.getArgOperand(1));
1102     Info.align.reset();
1103     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1104 
1105     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1106     if (!Vol || !Vol->isZero())
1107       Info.flags |= MachineMemOperand::MOVolatile;
1108 
1109     return true;
1110   }
1111   case Intrinsic::amdgcn_ds_append:
1112   case Intrinsic::amdgcn_ds_consume: {
1113     Info.opc = ISD::INTRINSIC_W_CHAIN;
1114     Info.memVT = MVT::getVT(CI.getType());
1115     Info.ptrVal = CI.getOperand(0);
1116     Info.align.reset();
1117     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1118 
1119     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1120     if (!Vol->isZero())
1121       Info.flags |= MachineMemOperand::MOVolatile;
1122 
1123     return true;
1124   }
1125   case Intrinsic::amdgcn_global_atomic_csub: {
1126     Info.opc = ISD::INTRINSIC_W_CHAIN;
1127     Info.memVT = MVT::getVT(CI.getType());
1128     Info.ptrVal = CI.getOperand(0);
1129     Info.align.reset();
1130     Info.flags = MachineMemOperand::MOLoad |
1131                  MachineMemOperand::MOStore |
1132                  MachineMemOperand::MOVolatile;
1133     return true;
1134   }
1135   case Intrinsic::amdgcn_global_atomic_fadd: {
1136     Info.opc = ISD::INTRINSIC_W_CHAIN;
1137     Info.memVT = MVT::getVT(CI.getType());
1138     Info.ptrVal = CI.getOperand(0);
1139     Info.align.reset();
1140     Info.flags = MachineMemOperand::MOLoad |
1141                  MachineMemOperand::MOStore |
1142                  MachineMemOperand::MODereferenceable |
1143                  MachineMemOperand::MOVolatile;
1144     return true;
1145   }
1146   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1147     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1150     Info.ptrVal = MFI->getImagePSV(
1151         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1152     Info.align.reset();
1153     Info.flags = MachineMemOperand::MOLoad |
1154                  MachineMemOperand::MODereferenceable;
1155     return true;
1156   }
1157   case Intrinsic::amdgcn_ds_gws_init:
1158   case Intrinsic::amdgcn_ds_gws_barrier:
1159   case Intrinsic::amdgcn_ds_gws_sema_v:
1160   case Intrinsic::amdgcn_ds_gws_sema_br:
1161   case Intrinsic::amdgcn_ds_gws_sema_p:
1162   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1163     Info.opc = ISD::INTRINSIC_VOID;
1164 
1165     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1166     Info.ptrVal =
1167         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1168 
1169     // This is an abstract access, but we need to specify a type and size.
1170     Info.memVT = MVT::i32;
1171     Info.size = 4;
1172     Info.align = Align(4);
1173 
1174     Info.flags = MachineMemOperand::MOStore;
1175     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1176       Info.flags = MachineMemOperand::MOLoad;
1177     return true;
1178   }
1179   default:
1180     return false;
1181   }
1182 }
1183 
1184 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1185                                             SmallVectorImpl<Value*> &Ops,
1186                                             Type *&AccessTy) const {
1187   switch (II->getIntrinsicID()) {
1188   case Intrinsic::amdgcn_atomic_inc:
1189   case Intrinsic::amdgcn_atomic_dec:
1190   case Intrinsic::amdgcn_ds_ordered_add:
1191   case Intrinsic::amdgcn_ds_ordered_swap:
1192   case Intrinsic::amdgcn_ds_append:
1193   case Intrinsic::amdgcn_ds_consume:
1194   case Intrinsic::amdgcn_ds_fadd:
1195   case Intrinsic::amdgcn_ds_fmin:
1196   case Intrinsic::amdgcn_ds_fmax:
1197   case Intrinsic::amdgcn_global_atomic_fadd:
1198   case Intrinsic::amdgcn_global_atomic_csub: {
1199     Value *Ptr = II->getArgOperand(0);
1200     AccessTy = II->getType();
1201     Ops.push_back(Ptr);
1202     return true;
1203   }
1204   default:
1205     return false;
1206   }
1207 }
1208 
1209 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1210   if (!Subtarget->hasFlatInstOffsets()) {
1211     // Flat instructions do not have offsets, and only have the register
1212     // address.
1213     return AM.BaseOffs == 0 && AM.Scale == 0;
1214   }
1215 
1216   return AM.Scale == 0 &&
1217          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1218                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1219                                   /*Signed=*/false));
1220 }
1221 
1222 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1223   if (Subtarget->hasFlatGlobalInsts())
1224     return AM.Scale == 0 &&
1225            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1226                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1227                                     /*Signed=*/true));
1228 
1229   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1230       // Assume the we will use FLAT for all global memory accesses
1231       // on VI.
1232       // FIXME: This assumption is currently wrong.  On VI we still use
1233       // MUBUF instructions for the r + i addressing mode.  As currently
1234       // implemented, the MUBUF instructions only work on buffer < 4GB.
1235       // It may be possible to support > 4GB buffers with MUBUF instructions,
1236       // by setting the stride value in the resource descriptor which would
1237       // increase the size limit to (stride * 4GB).  However, this is risky,
1238       // because it has never been validated.
1239     return isLegalFlatAddressingMode(AM);
1240   }
1241 
1242   return isLegalMUBUFAddressingMode(AM);
1243 }
1244 
1245 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1246   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1247   // additionally can do r + r + i with addr64. 32-bit has more addressing
1248   // mode options. Depending on the resource constant, it can also do
1249   // (i64 r0) + (i32 r1) * (i14 i).
1250   //
1251   // Private arrays end up using a scratch buffer most of the time, so also
1252   // assume those use MUBUF instructions. Scratch loads / stores are currently
1253   // implemented as mubuf instructions with offen bit set, so slightly
1254   // different than the normal addr64.
1255   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1256     return false;
1257 
1258   // FIXME: Since we can split immediate into soffset and immediate offset,
1259   // would it make sense to allow any immediate?
1260 
1261   switch (AM.Scale) {
1262   case 0: // r + i or just i, depending on HasBaseReg.
1263     return true;
1264   case 1:
1265     return true; // We have r + r or r + i.
1266   case 2:
1267     if (AM.HasBaseReg) {
1268       // Reject 2 * r + r.
1269       return false;
1270     }
1271 
1272     // Allow 2 * r as r + r
1273     // Or  2 * r + i is allowed as r + r + i.
1274     return true;
1275   default: // Don't allow n * r
1276     return false;
1277   }
1278 }
1279 
1280 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1281                                              const AddrMode &AM, Type *Ty,
1282                                              unsigned AS, Instruction *I) const {
1283   // No global is ever allowed as a base.
1284   if (AM.BaseGV)
1285     return false;
1286 
1287   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1288     return isLegalGlobalAddressingMode(AM);
1289 
1290   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1291       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1292       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1293     // If the offset isn't a multiple of 4, it probably isn't going to be
1294     // correctly aligned.
1295     // FIXME: Can we get the real alignment here?
1296     if (AM.BaseOffs % 4 != 0)
1297       return isLegalMUBUFAddressingMode(AM);
1298 
1299     // There are no SMRD extloads, so if we have to do a small type access we
1300     // will use a MUBUF load.
1301     // FIXME?: We also need to do this if unaligned, but we don't know the
1302     // alignment here.
1303     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1304       return isLegalGlobalAddressingMode(AM);
1305 
1306     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1307       // SMRD instructions have an 8-bit, dword offset on SI.
1308       if (!isUInt<8>(AM.BaseOffs / 4))
1309         return false;
1310     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1311       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1312       // in 8-bits, it can use a smaller encoding.
1313       if (!isUInt<32>(AM.BaseOffs / 4))
1314         return false;
1315     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1316       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1317       if (!isUInt<20>(AM.BaseOffs))
1318         return false;
1319     } else
1320       llvm_unreachable("unhandled generation");
1321 
1322     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1323       return true;
1324 
1325     if (AM.Scale == 1 && AM.HasBaseReg)
1326       return true;
1327 
1328     return false;
1329 
1330   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1331     return isLegalMUBUFAddressingMode(AM);
1332   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1333              AS == AMDGPUAS::REGION_ADDRESS) {
1334     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1335     // field.
1336     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1337     // an 8-bit dword offset but we don't know the alignment here.
1338     if (!isUInt<16>(AM.BaseOffs))
1339       return false;
1340 
1341     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1342       return true;
1343 
1344     if (AM.Scale == 1 && AM.HasBaseReg)
1345       return true;
1346 
1347     return false;
1348   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1349              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1350     // For an unknown address space, this usually means that this is for some
1351     // reason being used for pure arithmetic, and not based on some addressing
1352     // computation. We don't have instructions that compute pointers with any
1353     // addressing modes, so treat them as having no offset like flat
1354     // instructions.
1355     return isLegalFlatAddressingMode(AM);
1356   }
1357 
1358   // Assume a user alias of global for unknown address spaces.
1359   return isLegalGlobalAddressingMode(AM);
1360 }
1361 
1362 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1363                                         const SelectionDAG &DAG) const {
1364   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1365     return (MemVT.getSizeInBits() <= 4 * 32);
1366   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1367     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1368     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1369   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1370     return (MemVT.getSizeInBits() <= 2 * 32);
1371   }
1372   return true;
1373 }
1374 
1375 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1376     unsigned Size, unsigned AddrSpace, Align Alignment,
1377     MachineMemOperand::Flags Flags, bool *IsFast) const {
1378   if (IsFast)
1379     *IsFast = false;
1380 
1381   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1382       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1383     // Check if alignment requirements for ds_read/write instructions are
1384     // disabled.
1385     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1386         !Subtarget->hasLDSMisalignedBug()) {
1387       if (IsFast)
1388         *IsFast = Alignment != Align(2);
1389       return true;
1390     }
1391 
1392     if (Size == 64) {
1393       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1394       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1395       // with adjacent offsets.
1396       bool AlignedBy4 = Alignment >= Align(4);
1397       if (IsFast)
1398         *IsFast = AlignedBy4;
1399 
1400       return AlignedBy4;
1401     }
1402     if (Size == 96) {
1403       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1404       bool Aligned = Alignment >= Align(16);
1405       if (IsFast)
1406         *IsFast = Aligned;
1407 
1408       return Aligned;
1409     }
1410     if (Size == 128) {
1411       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1412       // can do a 8 byte aligned, 16 byte access in a single operation using
1413       // ds_read2/write2_b64.
1414       bool Aligned = Alignment >= Align(8);
1415       if (IsFast)
1416         *IsFast = Aligned;
1417 
1418       return Aligned;
1419     }
1420   }
1421 
1422   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1423     bool AlignedBy4 = Alignment >= Align(4);
1424     if (IsFast)
1425       *IsFast = AlignedBy4;
1426 
1427     return AlignedBy4 ||
1428            Subtarget->enableFlatScratch() ||
1429            Subtarget->hasUnalignedScratchAccess();
1430   }
1431 
1432   // FIXME: We have to be conservative here and assume that flat operations
1433   // will access scratch.  If we had access to the IR function, then we
1434   // could determine if any private memory was used in the function.
1435   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1436       !Subtarget->hasUnalignedScratchAccess()) {
1437     bool AlignedBy4 = Alignment >= Align(4);
1438     if (IsFast)
1439       *IsFast = AlignedBy4;
1440 
1441     return AlignedBy4;
1442   }
1443 
1444   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1445       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1446         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1447     // If we have an uniform constant load, it still requires using a slow
1448     // buffer instruction if unaligned.
1449     if (IsFast) {
1450       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1451       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1452       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1453                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1454         Alignment >= Align(4) : Alignment != Align(2);
1455     }
1456 
1457     return true;
1458   }
1459 
1460   // Smaller than dword value must be aligned.
1461   if (Size < 32)
1462     return false;
1463 
1464   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1465   // byte-address are ignored, thus forcing Dword alignment.
1466   // This applies to private, global, and constant memory.
1467   if (IsFast)
1468     *IsFast = true;
1469 
1470   return Size >= 32 && Alignment >= Align(4);
1471 }
1472 
1473 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1474     EVT VT, unsigned AddrSpace, unsigned Alignment,
1475     MachineMemOperand::Flags Flags, bool *IsFast) const {
1476   if (IsFast)
1477     *IsFast = false;
1478 
1479   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1480   // which isn't a simple VT.
1481   // Until MVT is extended to handle this, simply check for the size and
1482   // rely on the condition below: allow accesses if the size is a multiple of 4.
1483   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1484                            VT.getStoreSize() > 16)) {
1485     return false;
1486   }
1487 
1488   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1489                                             Align(Alignment), Flags, IsFast);
1490 }
1491 
1492 EVT SITargetLowering::getOptimalMemOpType(
1493     const MemOp &Op, const AttributeList &FuncAttributes) const {
1494   // FIXME: Should account for address space here.
1495 
1496   // The default fallback uses the private pointer size as a guess for a type to
1497   // use. Make sure we switch these to 64-bit accesses.
1498 
1499   if (Op.size() >= 16 &&
1500       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1501     return MVT::v4i32;
1502 
1503   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1504     return MVT::v2i32;
1505 
1506   // Use the default.
1507   return MVT::Other;
1508 }
1509 
1510 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1511   const MemSDNode *MemNode = cast<MemSDNode>(N);
1512   const Value *Ptr = MemNode->getMemOperand()->getValue();
1513   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1514   return I && I->getMetadata("amdgpu.noclobber");
1515 }
1516 
1517 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1518   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1519          AS == AMDGPUAS::PRIVATE_ADDRESS;
1520 }
1521 
1522 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1523                                            unsigned DestAS) const {
1524   // Flat -> private/local is a simple truncate.
1525   // Flat -> global is no-op
1526   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1527     return true;
1528 
1529   const GCNTargetMachine &TM =
1530       static_cast<const GCNTargetMachine &>(getTargetMachine());
1531   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1532 }
1533 
1534 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1535   const MemSDNode *MemNode = cast<MemSDNode>(N);
1536 
1537   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1538 }
1539 
1540 TargetLoweringBase::LegalizeTypeAction
1541 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1542   int NumElts = VT.getVectorNumElements();
1543   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1544     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1545   return TargetLoweringBase::getPreferredVectorAction(VT);
1546 }
1547 
1548 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1549                                                          Type *Ty) const {
1550   // FIXME: Could be smarter if called for vector constants.
1551   return true;
1552 }
1553 
1554 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1555   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1556     switch (Op) {
1557     case ISD::LOAD:
1558     case ISD::STORE:
1559 
1560     // These operations are done with 32-bit instructions anyway.
1561     case ISD::AND:
1562     case ISD::OR:
1563     case ISD::XOR:
1564     case ISD::SELECT:
1565       // TODO: Extensions?
1566       return true;
1567     default:
1568       return false;
1569     }
1570   }
1571 
1572   // SimplifySetCC uses this function to determine whether or not it should
1573   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1574   if (VT == MVT::i1 && Op == ISD::SETCC)
1575     return false;
1576 
1577   return TargetLowering::isTypeDesirableForOp(Op, VT);
1578 }
1579 
1580 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1581                                                    const SDLoc &SL,
1582                                                    SDValue Chain,
1583                                                    uint64_t Offset) const {
1584   const DataLayout &DL = DAG.getDataLayout();
1585   MachineFunction &MF = DAG.getMachineFunction();
1586   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1587 
1588   const ArgDescriptor *InputPtrReg;
1589   const TargetRegisterClass *RC;
1590   LLT ArgTy;
1591 
1592   std::tie(InputPtrReg, RC, ArgTy) =
1593       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1594 
1595   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1596   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1597   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1598     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1599 
1600   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1601 }
1602 
1603 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1604                                             const SDLoc &SL) const {
1605   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1606                                                FIRST_IMPLICIT);
1607   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1608 }
1609 
1610 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1611                                          const SDLoc &SL, SDValue Val,
1612                                          bool Signed,
1613                                          const ISD::InputArg *Arg) const {
1614   // First, if it is a widened vector, narrow it.
1615   if (VT.isVector() &&
1616       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1617     EVT NarrowedVT =
1618         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1619                          VT.getVectorNumElements());
1620     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1621                       DAG.getConstant(0, SL, MVT::i32));
1622   }
1623 
1624   // Then convert the vector elements or scalar value.
1625   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1626       VT.bitsLT(MemVT)) {
1627     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1628     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1629   }
1630 
1631   if (MemVT.isFloatingPoint())
1632     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1633   else if (Signed)
1634     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1635   else
1636     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1637 
1638   return Val;
1639 }
1640 
1641 SDValue SITargetLowering::lowerKernargMemParameter(
1642     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1643     uint64_t Offset, Align Alignment, bool Signed,
1644     const ISD::InputArg *Arg) const {
1645   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1646 
1647   // Try to avoid using an extload by loading earlier than the argument address,
1648   // and extracting the relevant bits. The load should hopefully be merged with
1649   // the previous argument.
1650   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1651     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1652     int64_t AlignDownOffset = alignDown(Offset, 4);
1653     int64_t OffsetDiff = Offset - AlignDownOffset;
1654 
1655     EVT IntVT = MemVT.changeTypeToInteger();
1656 
1657     // TODO: If we passed in the base kernel offset we could have a better
1658     // alignment than 4, but we don't really need it.
1659     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1660     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1661                                MachineMemOperand::MODereferenceable |
1662                                    MachineMemOperand::MOInvariant);
1663 
1664     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1665     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1666 
1667     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1668     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1669     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1670 
1671 
1672     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1673   }
1674 
1675   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1676   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1677                              MachineMemOperand::MODereferenceable |
1678                                  MachineMemOperand::MOInvariant);
1679 
1680   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1681   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1682 }
1683 
1684 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1685                                               const SDLoc &SL, SDValue Chain,
1686                                               const ISD::InputArg &Arg) const {
1687   MachineFunction &MF = DAG.getMachineFunction();
1688   MachineFrameInfo &MFI = MF.getFrameInfo();
1689 
1690   if (Arg.Flags.isByVal()) {
1691     unsigned Size = Arg.Flags.getByValSize();
1692     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1693     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1694   }
1695 
1696   unsigned ArgOffset = VA.getLocMemOffset();
1697   unsigned ArgSize = VA.getValVT().getStoreSize();
1698 
1699   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1700 
1701   // Create load nodes to retrieve arguments from the stack.
1702   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1703   SDValue ArgValue;
1704 
1705   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1706   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1707   MVT MemVT = VA.getValVT();
1708 
1709   switch (VA.getLocInfo()) {
1710   default:
1711     break;
1712   case CCValAssign::BCvt:
1713     MemVT = VA.getLocVT();
1714     break;
1715   case CCValAssign::SExt:
1716     ExtType = ISD::SEXTLOAD;
1717     break;
1718   case CCValAssign::ZExt:
1719     ExtType = ISD::ZEXTLOAD;
1720     break;
1721   case CCValAssign::AExt:
1722     ExtType = ISD::EXTLOAD;
1723     break;
1724   }
1725 
1726   ArgValue = DAG.getExtLoad(
1727     ExtType, SL, VA.getLocVT(), Chain, FIN,
1728     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1729     MemVT);
1730   return ArgValue;
1731 }
1732 
1733 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1734   const SIMachineFunctionInfo &MFI,
1735   EVT VT,
1736   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1737   const ArgDescriptor *Reg;
1738   const TargetRegisterClass *RC;
1739   LLT Ty;
1740 
1741   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1742   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1743 }
1744 
1745 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1746                                CallingConv::ID CallConv,
1747                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1748                                FunctionType *FType,
1749                                SIMachineFunctionInfo *Info) {
1750   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1751     const ISD::InputArg *Arg = &Ins[I];
1752 
1753     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1754            "vector type argument should have been split");
1755 
1756     // First check if it's a PS input addr.
1757     if (CallConv == CallingConv::AMDGPU_PS &&
1758         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1759       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1760 
1761       // Inconveniently only the first part of the split is marked as isSplit,
1762       // so skip to the end. We only want to increment PSInputNum once for the
1763       // entire split argument.
1764       if (Arg->Flags.isSplit()) {
1765         while (!Arg->Flags.isSplitEnd()) {
1766           assert((!Arg->VT.isVector() ||
1767                   Arg->VT.getScalarSizeInBits() == 16) &&
1768                  "unexpected vector split in ps argument type");
1769           if (!SkipArg)
1770             Splits.push_back(*Arg);
1771           Arg = &Ins[++I];
1772         }
1773       }
1774 
1775       if (SkipArg) {
1776         // We can safely skip PS inputs.
1777         Skipped.set(Arg->getOrigArgIndex());
1778         ++PSInputNum;
1779         continue;
1780       }
1781 
1782       Info->markPSInputAllocated(PSInputNum);
1783       if (Arg->Used)
1784         Info->markPSInputEnabled(PSInputNum);
1785 
1786       ++PSInputNum;
1787     }
1788 
1789     Splits.push_back(*Arg);
1790   }
1791 }
1792 
1793 // Allocate special inputs passed in VGPRs.
1794 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1795                                                       MachineFunction &MF,
1796                                                       const SIRegisterInfo &TRI,
1797                                                       SIMachineFunctionInfo &Info) const {
1798   const LLT S32 = LLT::scalar(32);
1799   MachineRegisterInfo &MRI = MF.getRegInfo();
1800 
1801   if (Info.hasWorkItemIDX()) {
1802     Register Reg = AMDGPU::VGPR0;
1803     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1804 
1805     CCInfo.AllocateReg(Reg);
1806     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1807   }
1808 
1809   if (Info.hasWorkItemIDY()) {
1810     Register Reg = AMDGPU::VGPR1;
1811     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1812 
1813     CCInfo.AllocateReg(Reg);
1814     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1815   }
1816 
1817   if (Info.hasWorkItemIDZ()) {
1818     Register Reg = AMDGPU::VGPR2;
1819     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1820 
1821     CCInfo.AllocateReg(Reg);
1822     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1823   }
1824 }
1825 
1826 // Try to allocate a VGPR at the end of the argument list, or if no argument
1827 // VGPRs are left allocating a stack slot.
1828 // If \p Mask is is given it indicates bitfield position in the register.
1829 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1830 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1831                                          ArgDescriptor Arg = ArgDescriptor()) {
1832   if (Arg.isSet())
1833     return ArgDescriptor::createArg(Arg, Mask);
1834 
1835   ArrayRef<MCPhysReg> ArgVGPRs
1836     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1837   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1838   if (RegIdx == ArgVGPRs.size()) {
1839     // Spill to stack required.
1840     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1841 
1842     return ArgDescriptor::createStack(Offset, Mask);
1843   }
1844 
1845   unsigned Reg = ArgVGPRs[RegIdx];
1846   Reg = CCInfo.AllocateReg(Reg);
1847   assert(Reg != AMDGPU::NoRegister);
1848 
1849   MachineFunction &MF = CCInfo.getMachineFunction();
1850   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1851   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1852   return ArgDescriptor::createRegister(Reg, Mask);
1853 }
1854 
1855 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1856                                              const TargetRegisterClass *RC,
1857                                              unsigned NumArgRegs) {
1858   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1859   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1860   if (RegIdx == ArgSGPRs.size())
1861     report_fatal_error("ran out of SGPRs for arguments");
1862 
1863   unsigned Reg = ArgSGPRs[RegIdx];
1864   Reg = CCInfo.AllocateReg(Reg);
1865   assert(Reg != AMDGPU::NoRegister);
1866 
1867   MachineFunction &MF = CCInfo.getMachineFunction();
1868   MF.addLiveIn(Reg, RC);
1869   return ArgDescriptor::createRegister(Reg);
1870 }
1871 
1872 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1873   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1874 }
1875 
1876 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1877   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1878 }
1879 
1880 /// Allocate implicit function VGPR arguments at the end of allocated user
1881 /// arguments.
1882 void SITargetLowering::allocateSpecialInputVGPRs(
1883   CCState &CCInfo, MachineFunction &MF,
1884   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1885   const unsigned Mask = 0x3ff;
1886   ArgDescriptor Arg;
1887 
1888   if (Info.hasWorkItemIDX()) {
1889     Arg = allocateVGPR32Input(CCInfo, Mask);
1890     Info.setWorkItemIDX(Arg);
1891   }
1892 
1893   if (Info.hasWorkItemIDY()) {
1894     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1895     Info.setWorkItemIDY(Arg);
1896   }
1897 
1898   if (Info.hasWorkItemIDZ())
1899     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1900 }
1901 
1902 /// Allocate implicit function VGPR arguments in fixed registers.
1903 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1904   CCState &CCInfo, MachineFunction &MF,
1905   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1906   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1907   if (!Reg)
1908     report_fatal_error("failed to allocated VGPR for implicit arguments");
1909 
1910   const unsigned Mask = 0x3ff;
1911   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1912   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1913   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1914 }
1915 
1916 void SITargetLowering::allocateSpecialInputSGPRs(
1917   CCState &CCInfo,
1918   MachineFunction &MF,
1919   const SIRegisterInfo &TRI,
1920   SIMachineFunctionInfo &Info) const {
1921   auto &ArgInfo = Info.getArgInfo();
1922 
1923   // TODO: Unify handling with private memory pointers.
1924 
1925   if (Info.hasDispatchPtr())
1926     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1927 
1928   if (Info.hasQueuePtr())
1929     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1930 
1931   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1932   // constant offset from the kernarg segment.
1933   if (Info.hasImplicitArgPtr())
1934     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1935 
1936   if (Info.hasDispatchID())
1937     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1938 
1939   // flat_scratch_init is not applicable for non-kernel functions.
1940 
1941   if (Info.hasWorkGroupIDX())
1942     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1943 
1944   if (Info.hasWorkGroupIDY())
1945     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1946 
1947   if (Info.hasWorkGroupIDZ())
1948     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1949 }
1950 
1951 // Allocate special inputs passed in user SGPRs.
1952 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1953                                             MachineFunction &MF,
1954                                             const SIRegisterInfo &TRI,
1955                                             SIMachineFunctionInfo &Info) const {
1956   if (Info.hasImplicitBufferPtr()) {
1957     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1958     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1959     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1960   }
1961 
1962   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1963   if (Info.hasPrivateSegmentBuffer()) {
1964     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1965     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1966     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1967   }
1968 
1969   if (Info.hasDispatchPtr()) {
1970     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
1971     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1972     CCInfo.AllocateReg(DispatchPtrReg);
1973   }
1974 
1975   if (Info.hasQueuePtr()) {
1976     Register QueuePtrReg = Info.addQueuePtr(TRI);
1977     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1978     CCInfo.AllocateReg(QueuePtrReg);
1979   }
1980 
1981   if (Info.hasKernargSegmentPtr()) {
1982     MachineRegisterInfo &MRI = MF.getRegInfo();
1983     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1984     CCInfo.AllocateReg(InputPtrReg);
1985 
1986     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1987     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1988   }
1989 
1990   if (Info.hasDispatchID()) {
1991     Register DispatchIDReg = Info.addDispatchID(TRI);
1992     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1993     CCInfo.AllocateReg(DispatchIDReg);
1994   }
1995 
1996   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
1997     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1998     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1999     CCInfo.AllocateReg(FlatScratchInitReg);
2000   }
2001 
2002   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2003   // these from the dispatch pointer.
2004 }
2005 
2006 // Allocate special input registers that are initialized per-wave.
2007 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2008                                            MachineFunction &MF,
2009                                            SIMachineFunctionInfo &Info,
2010                                            CallingConv::ID CallConv,
2011                                            bool IsShader) const {
2012   if (Info.hasWorkGroupIDX()) {
2013     Register Reg = Info.addWorkGroupIDX();
2014     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2015     CCInfo.AllocateReg(Reg);
2016   }
2017 
2018   if (Info.hasWorkGroupIDY()) {
2019     Register Reg = Info.addWorkGroupIDY();
2020     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2021     CCInfo.AllocateReg(Reg);
2022   }
2023 
2024   if (Info.hasWorkGroupIDZ()) {
2025     Register Reg = Info.addWorkGroupIDZ();
2026     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2027     CCInfo.AllocateReg(Reg);
2028   }
2029 
2030   if (Info.hasWorkGroupInfo()) {
2031     Register Reg = Info.addWorkGroupInfo();
2032     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2033     CCInfo.AllocateReg(Reg);
2034   }
2035 
2036   if (Info.hasPrivateSegmentWaveByteOffset()) {
2037     // Scratch wave offset passed in system SGPR.
2038     unsigned PrivateSegmentWaveByteOffsetReg;
2039 
2040     if (IsShader) {
2041       PrivateSegmentWaveByteOffsetReg =
2042         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2043 
2044       // This is true if the scratch wave byte offset doesn't have a fixed
2045       // location.
2046       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2047         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2048         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2049       }
2050     } else
2051       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2052 
2053     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2054     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2055   }
2056 }
2057 
2058 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2059                                      MachineFunction &MF,
2060                                      const SIRegisterInfo &TRI,
2061                                      SIMachineFunctionInfo &Info) {
2062   // Now that we've figured out where the scratch register inputs are, see if
2063   // should reserve the arguments and use them directly.
2064   MachineFrameInfo &MFI = MF.getFrameInfo();
2065   bool HasStackObjects = MFI.hasStackObjects();
2066   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2067 
2068   // Record that we know we have non-spill stack objects so we don't need to
2069   // check all stack objects later.
2070   if (HasStackObjects)
2071     Info.setHasNonSpillStackObjects(true);
2072 
2073   // Everything live out of a block is spilled with fast regalloc, so it's
2074   // almost certain that spilling will be required.
2075   if (TM.getOptLevel() == CodeGenOpt::None)
2076     HasStackObjects = true;
2077 
2078   // For now assume stack access is needed in any callee functions, so we need
2079   // the scratch registers to pass in.
2080   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2081 
2082   if (!ST.enableFlatScratch()) {
2083     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2084       // If we have stack objects, we unquestionably need the private buffer
2085       // resource. For the Code Object V2 ABI, this will be the first 4 user
2086       // SGPR inputs. We can reserve those and use them directly.
2087 
2088       Register PrivateSegmentBufferReg =
2089           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2090       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2091     } else {
2092       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2093       // We tentatively reserve the last registers (skipping the last registers
2094       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2095       // we'll replace these with the ones immediately after those which were
2096       // really allocated. In the prologue copies will be inserted from the
2097       // argument to these reserved registers.
2098 
2099       // Without HSA, relocations are used for the scratch pointer and the
2100       // buffer resource setup is always inserted in the prologue. Scratch wave
2101       // offset is still in an input SGPR.
2102       Info.setScratchRSrcReg(ReservedBufferReg);
2103     }
2104   }
2105 
2106   MachineRegisterInfo &MRI = MF.getRegInfo();
2107 
2108   // For entry functions we have to set up the stack pointer if we use it,
2109   // whereas non-entry functions get this "for free". This means there is no
2110   // intrinsic advantage to using S32 over S34 in cases where we do not have
2111   // calls but do need a frame pointer (i.e. if we are requested to have one
2112   // because frame pointer elimination is disabled). To keep things simple we
2113   // only ever use S32 as the call ABI stack pointer, and so using it does not
2114   // imply we need a separate frame pointer.
2115   //
2116   // Try to use s32 as the SP, but move it if it would interfere with input
2117   // arguments. This won't work with calls though.
2118   //
2119   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2120   // registers.
2121   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2122     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2123   } else {
2124     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2125 
2126     if (MFI.hasCalls())
2127       report_fatal_error("call in graphics shader with too many input SGPRs");
2128 
2129     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2130       if (!MRI.isLiveIn(Reg)) {
2131         Info.setStackPtrOffsetReg(Reg);
2132         break;
2133       }
2134     }
2135 
2136     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2137       report_fatal_error("failed to find register for SP");
2138   }
2139 
2140   // hasFP should be accurate for entry functions even before the frame is
2141   // finalized, because it does not rely on the known stack size, only
2142   // properties like whether variable sized objects are present.
2143   if (ST.getFrameLowering()->hasFP(MF)) {
2144     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2145   }
2146 }
2147 
2148 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2149   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2150   return !Info->isEntryFunction();
2151 }
2152 
2153 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2154 
2155 }
2156 
2157 void SITargetLowering::insertCopiesSplitCSR(
2158   MachineBasicBlock *Entry,
2159   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2160   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2161 
2162   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2163   if (!IStart)
2164     return;
2165 
2166   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2167   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2168   MachineBasicBlock::iterator MBBI = Entry->begin();
2169   for (const MCPhysReg *I = IStart; *I; ++I) {
2170     const TargetRegisterClass *RC = nullptr;
2171     if (AMDGPU::SReg_64RegClass.contains(*I))
2172       RC = &AMDGPU::SGPR_64RegClass;
2173     else if (AMDGPU::SReg_32RegClass.contains(*I))
2174       RC = &AMDGPU::SGPR_32RegClass;
2175     else
2176       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2177 
2178     Register NewVR = MRI->createVirtualRegister(RC);
2179     // Create copy from CSR to a virtual register.
2180     Entry->addLiveIn(*I);
2181     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2182       .addReg(*I);
2183 
2184     // Insert the copy-back instructions right before the terminator.
2185     for (auto *Exit : Exits)
2186       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2187               TII->get(TargetOpcode::COPY), *I)
2188         .addReg(NewVR);
2189   }
2190 }
2191 
2192 SDValue SITargetLowering::LowerFormalArguments(
2193     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2194     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2195     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2196   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2197 
2198   MachineFunction &MF = DAG.getMachineFunction();
2199   const Function &Fn = MF.getFunction();
2200   FunctionType *FType = MF.getFunction().getFunctionType();
2201   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2202 
2203   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2204     DiagnosticInfoUnsupported NoGraphicsHSA(
2205         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2206     DAG.getContext()->diagnose(NoGraphicsHSA);
2207     return DAG.getEntryNode();
2208   }
2209 
2210   SmallVector<ISD::InputArg, 16> Splits;
2211   SmallVector<CCValAssign, 16> ArgLocs;
2212   BitVector Skipped(Ins.size());
2213   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2214                  *DAG.getContext());
2215 
2216   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2217   bool IsKernel = AMDGPU::isKernel(CallConv);
2218   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2219 
2220   if (IsGraphics) {
2221     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2222            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2223            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2224            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2225            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2226            !Info->hasWorkItemIDZ());
2227   }
2228 
2229   if (CallConv == CallingConv::AMDGPU_PS) {
2230     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2231 
2232     // At least one interpolation mode must be enabled or else the GPU will
2233     // hang.
2234     //
2235     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2236     // set PSInputAddr, the user wants to enable some bits after the compilation
2237     // based on run-time states. Since we can't know what the final PSInputEna
2238     // will look like, so we shouldn't do anything here and the user should take
2239     // responsibility for the correct programming.
2240     //
2241     // Otherwise, the following restrictions apply:
2242     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2243     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2244     //   enabled too.
2245     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2246         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2247       CCInfo.AllocateReg(AMDGPU::VGPR0);
2248       CCInfo.AllocateReg(AMDGPU::VGPR1);
2249       Info->markPSInputAllocated(0);
2250       Info->markPSInputEnabled(0);
2251     }
2252     if (Subtarget->isAmdPalOS()) {
2253       // For isAmdPalOS, the user does not enable some bits after compilation
2254       // based on run-time states; the register values being generated here are
2255       // the final ones set in hardware. Therefore we need to apply the
2256       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2257       // a bit is set in PSInputAddr but not PSInputEnable is where the
2258       // frontend set up an input arg for a particular interpolation mode, but
2259       // nothing uses that input arg. Really we should have an earlier pass
2260       // that removes such an arg.)
2261       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2262       if ((PsInputBits & 0x7F) == 0 ||
2263           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2264         Info->markPSInputEnabled(
2265             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2266     }
2267   } else if (IsKernel) {
2268     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2269   } else {
2270     Splits.append(Ins.begin(), Ins.end());
2271   }
2272 
2273   if (IsEntryFunc) {
2274     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2275     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2276   } else {
2277     // For the fixed ABI, pass workitem IDs in the last argument register.
2278     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2279       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2280   }
2281 
2282   if (IsKernel) {
2283     analyzeFormalArgumentsCompute(CCInfo, Ins);
2284   } else {
2285     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2286     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2287   }
2288 
2289   SmallVector<SDValue, 16> Chains;
2290 
2291   // FIXME: This is the minimum kernel argument alignment. We should improve
2292   // this to the maximum alignment of the arguments.
2293   //
2294   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2295   // kern arg offset.
2296   const Align KernelArgBaseAlign = Align(16);
2297 
2298   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2299     const ISD::InputArg &Arg = Ins[i];
2300     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2301       InVals.push_back(DAG.getUNDEF(Arg.VT));
2302       continue;
2303     }
2304 
2305     CCValAssign &VA = ArgLocs[ArgIdx++];
2306     MVT VT = VA.getLocVT();
2307 
2308     if (IsEntryFunc && VA.isMemLoc()) {
2309       VT = Ins[i].VT;
2310       EVT MemVT = VA.getLocVT();
2311 
2312       const uint64_t Offset = VA.getLocMemOffset();
2313       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2314 
2315       if (Arg.Flags.isByRef()) {
2316         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2317 
2318         const GCNTargetMachine &TM =
2319             static_cast<const GCNTargetMachine &>(getTargetMachine());
2320         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2321                                     Arg.Flags.getPointerAddrSpace())) {
2322           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2323                                      Arg.Flags.getPointerAddrSpace());
2324         }
2325 
2326         InVals.push_back(Ptr);
2327         continue;
2328       }
2329 
2330       SDValue Arg = lowerKernargMemParameter(
2331         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2332       Chains.push_back(Arg.getValue(1));
2333 
2334       auto *ParamTy =
2335         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2336       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2337           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2338                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2339         // On SI local pointers are just offsets into LDS, so they are always
2340         // less than 16-bits.  On CI and newer they could potentially be
2341         // real pointers, so we can't guarantee their size.
2342         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2343                           DAG.getValueType(MVT::i16));
2344       }
2345 
2346       InVals.push_back(Arg);
2347       continue;
2348     } else if (!IsEntryFunc && VA.isMemLoc()) {
2349       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2350       InVals.push_back(Val);
2351       if (!Arg.Flags.isByVal())
2352         Chains.push_back(Val.getValue(1));
2353       continue;
2354     }
2355 
2356     assert(VA.isRegLoc() && "Parameter must be in a register!");
2357 
2358     Register Reg = VA.getLocReg();
2359     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2360     EVT ValVT = VA.getValVT();
2361 
2362     Reg = MF.addLiveIn(Reg, RC);
2363     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2364 
2365     if (Arg.Flags.isSRet()) {
2366       // The return object should be reasonably addressable.
2367 
2368       // FIXME: This helps when the return is a real sret. If it is a
2369       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2370       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2371       unsigned NumBits
2372         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2373       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2374         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2375     }
2376 
2377     // If this is an 8 or 16-bit value, it is really passed promoted
2378     // to 32 bits. Insert an assert[sz]ext to capture this, then
2379     // truncate to the right size.
2380     switch (VA.getLocInfo()) {
2381     case CCValAssign::Full:
2382       break;
2383     case CCValAssign::BCvt:
2384       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2385       break;
2386     case CCValAssign::SExt:
2387       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2388                         DAG.getValueType(ValVT));
2389       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2390       break;
2391     case CCValAssign::ZExt:
2392       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2393                         DAG.getValueType(ValVT));
2394       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2395       break;
2396     case CCValAssign::AExt:
2397       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2398       break;
2399     default:
2400       llvm_unreachable("Unknown loc info!");
2401     }
2402 
2403     InVals.push_back(Val);
2404   }
2405 
2406   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2407     // Special inputs come after user arguments.
2408     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2409   }
2410 
2411   // Start adding system SGPRs.
2412   if (IsEntryFunc) {
2413     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2414   } else {
2415     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2416     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2417   }
2418 
2419   auto &ArgUsageInfo =
2420     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2421   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2422 
2423   unsigned StackArgSize = CCInfo.getNextStackOffset();
2424   Info->setBytesInStackArgArea(StackArgSize);
2425 
2426   return Chains.empty() ? Chain :
2427     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2428 }
2429 
2430 // TODO: If return values can't fit in registers, we should return as many as
2431 // possible in registers before passing on stack.
2432 bool SITargetLowering::CanLowerReturn(
2433   CallingConv::ID CallConv,
2434   MachineFunction &MF, bool IsVarArg,
2435   const SmallVectorImpl<ISD::OutputArg> &Outs,
2436   LLVMContext &Context) const {
2437   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2438   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2439   // for shaders. Vector types should be explicitly handled by CC.
2440   if (AMDGPU::isEntryFunctionCC(CallConv))
2441     return true;
2442 
2443   SmallVector<CCValAssign, 16> RVLocs;
2444   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2445   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2446 }
2447 
2448 SDValue
2449 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2450                               bool isVarArg,
2451                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2452                               const SmallVectorImpl<SDValue> &OutVals,
2453                               const SDLoc &DL, SelectionDAG &DAG) const {
2454   MachineFunction &MF = DAG.getMachineFunction();
2455   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2456 
2457   if (AMDGPU::isKernel(CallConv)) {
2458     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2459                                              OutVals, DL, DAG);
2460   }
2461 
2462   bool IsShader = AMDGPU::isShader(CallConv);
2463 
2464   Info->setIfReturnsVoid(Outs.empty());
2465   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2466 
2467   // CCValAssign - represent the assignment of the return value to a location.
2468   SmallVector<CCValAssign, 48> RVLocs;
2469   SmallVector<ISD::OutputArg, 48> Splits;
2470 
2471   // CCState - Info about the registers and stack slots.
2472   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2473                  *DAG.getContext());
2474 
2475   // Analyze outgoing return values.
2476   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2477 
2478   SDValue Flag;
2479   SmallVector<SDValue, 48> RetOps;
2480   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2481 
2482   // Add return address for callable functions.
2483   if (!Info->isEntryFunction()) {
2484     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2485     SDValue ReturnAddrReg = CreateLiveInRegister(
2486       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2487 
2488     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2489         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2490         MVT::i64);
2491     Chain =
2492         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2493     Flag = Chain.getValue(1);
2494     RetOps.push_back(ReturnAddrVirtualReg);
2495   }
2496 
2497   // Copy the result values into the output registers.
2498   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2499        ++I, ++RealRVLocIdx) {
2500     CCValAssign &VA = RVLocs[I];
2501     assert(VA.isRegLoc() && "Can only return in registers!");
2502     // TODO: Partially return in registers if return values don't fit.
2503     SDValue Arg = OutVals[RealRVLocIdx];
2504 
2505     // Copied from other backends.
2506     switch (VA.getLocInfo()) {
2507     case CCValAssign::Full:
2508       break;
2509     case CCValAssign::BCvt:
2510       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2511       break;
2512     case CCValAssign::SExt:
2513       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2514       break;
2515     case CCValAssign::ZExt:
2516       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2517       break;
2518     case CCValAssign::AExt:
2519       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2520       break;
2521     default:
2522       llvm_unreachable("Unknown loc info!");
2523     }
2524 
2525     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2526     Flag = Chain.getValue(1);
2527     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2528   }
2529 
2530   // FIXME: Does sret work properly?
2531   if (!Info->isEntryFunction()) {
2532     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2533     const MCPhysReg *I =
2534       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2535     if (I) {
2536       for (; *I; ++I) {
2537         if (AMDGPU::SReg_64RegClass.contains(*I))
2538           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2539         else if (AMDGPU::SReg_32RegClass.contains(*I))
2540           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2541         else
2542           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2543       }
2544     }
2545   }
2546 
2547   // Update chain and glue.
2548   RetOps[0] = Chain;
2549   if (Flag.getNode())
2550     RetOps.push_back(Flag);
2551 
2552   unsigned Opc = AMDGPUISD::ENDPGM;
2553   if (!IsWaveEnd)
2554     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2555   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2556 }
2557 
2558 SDValue SITargetLowering::LowerCallResult(
2559     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2560     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2561     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2562     SDValue ThisVal) const {
2563   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2564 
2565   // Assign locations to each value returned by this call.
2566   SmallVector<CCValAssign, 16> RVLocs;
2567   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2568                  *DAG.getContext());
2569   CCInfo.AnalyzeCallResult(Ins, RetCC);
2570 
2571   // Copy all of the result registers out of their specified physreg.
2572   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2573     CCValAssign VA = RVLocs[i];
2574     SDValue Val;
2575 
2576     if (VA.isRegLoc()) {
2577       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2578       Chain = Val.getValue(1);
2579       InFlag = Val.getValue(2);
2580     } else if (VA.isMemLoc()) {
2581       report_fatal_error("TODO: return values in memory");
2582     } else
2583       llvm_unreachable("unknown argument location type");
2584 
2585     switch (VA.getLocInfo()) {
2586     case CCValAssign::Full:
2587       break;
2588     case CCValAssign::BCvt:
2589       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2590       break;
2591     case CCValAssign::ZExt:
2592       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2593                         DAG.getValueType(VA.getValVT()));
2594       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2595       break;
2596     case CCValAssign::SExt:
2597       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2598                         DAG.getValueType(VA.getValVT()));
2599       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2600       break;
2601     case CCValAssign::AExt:
2602       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2603       break;
2604     default:
2605       llvm_unreachable("Unknown loc info!");
2606     }
2607 
2608     InVals.push_back(Val);
2609   }
2610 
2611   return Chain;
2612 }
2613 
2614 // Add code to pass special inputs required depending on used features separate
2615 // from the explicit user arguments present in the IR.
2616 void SITargetLowering::passSpecialInputs(
2617     CallLoweringInfo &CLI,
2618     CCState &CCInfo,
2619     const SIMachineFunctionInfo &Info,
2620     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2621     SmallVectorImpl<SDValue> &MemOpChains,
2622     SDValue Chain) const {
2623   // If we don't have a call site, this was a call inserted by
2624   // legalization. These can never use special inputs.
2625   if (!CLI.CB)
2626     return;
2627 
2628   SelectionDAG &DAG = CLI.DAG;
2629   const SDLoc &DL = CLI.DL;
2630 
2631   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2632   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2633 
2634   const AMDGPUFunctionArgInfo *CalleeArgInfo
2635     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2636   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2637     auto &ArgUsageInfo =
2638       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2639     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2640   }
2641 
2642   // TODO: Unify with private memory register handling. This is complicated by
2643   // the fact that at least in kernels, the input argument is not necessarily
2644   // in the same location as the input.
2645   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2646     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2647     AMDGPUFunctionArgInfo::QUEUE_PTR,
2648     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2649     AMDGPUFunctionArgInfo::DISPATCH_ID,
2650     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2651     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2652     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2653   };
2654 
2655   for (auto InputID : InputRegs) {
2656     const ArgDescriptor *OutgoingArg;
2657     const TargetRegisterClass *ArgRC;
2658     LLT ArgTy;
2659 
2660     std::tie(OutgoingArg, ArgRC, ArgTy) =
2661         CalleeArgInfo->getPreloadedValue(InputID);
2662     if (!OutgoingArg)
2663       continue;
2664 
2665     const ArgDescriptor *IncomingArg;
2666     const TargetRegisterClass *IncomingArgRC;
2667     LLT Ty;
2668     std::tie(IncomingArg, IncomingArgRC, Ty) =
2669         CallerArgInfo.getPreloadedValue(InputID);
2670     assert(IncomingArgRC == ArgRC);
2671 
2672     // All special arguments are ints for now.
2673     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2674     SDValue InputReg;
2675 
2676     if (IncomingArg) {
2677       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2678     } else {
2679       // The implicit arg ptr is special because it doesn't have a corresponding
2680       // input for kernels, and is computed from the kernarg segment pointer.
2681       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2682       InputReg = getImplicitArgPtr(DAG, DL);
2683     }
2684 
2685     if (OutgoingArg->isRegister()) {
2686       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2687       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2688         report_fatal_error("failed to allocate implicit input argument");
2689     } else {
2690       unsigned SpecialArgOffset =
2691           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2692       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2693                                               SpecialArgOffset);
2694       MemOpChains.push_back(ArgStore);
2695     }
2696   }
2697 
2698   // Pack workitem IDs into a single register or pass it as is if already
2699   // packed.
2700   const ArgDescriptor *OutgoingArg;
2701   const TargetRegisterClass *ArgRC;
2702   LLT Ty;
2703 
2704   std::tie(OutgoingArg, ArgRC, Ty) =
2705       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2706   if (!OutgoingArg)
2707     std::tie(OutgoingArg, ArgRC, Ty) =
2708         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2709   if (!OutgoingArg)
2710     std::tie(OutgoingArg, ArgRC, Ty) =
2711         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2712   if (!OutgoingArg)
2713     return;
2714 
2715   const ArgDescriptor *IncomingArgX = std::get<0>(
2716       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2717   const ArgDescriptor *IncomingArgY = std::get<0>(
2718       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2719   const ArgDescriptor *IncomingArgZ = std::get<0>(
2720       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2721 
2722   SDValue InputReg;
2723   SDLoc SL;
2724 
2725   // If incoming ids are not packed we need to pack them.
2726   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2727     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2728 
2729   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2730     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2731     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2732                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2733     InputReg = InputReg.getNode() ?
2734                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2735   }
2736 
2737   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2738     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2739     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2740                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2741     InputReg = InputReg.getNode() ?
2742                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2743   }
2744 
2745   if (!InputReg.getNode()) {
2746     // Workitem ids are already packed, any of present incoming arguments
2747     // will carry all required fields.
2748     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2749       IncomingArgX ? *IncomingArgX :
2750       IncomingArgY ? *IncomingArgY :
2751                      *IncomingArgZ, ~0u);
2752     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2753   }
2754 
2755   if (OutgoingArg->isRegister()) {
2756     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2757     CCInfo.AllocateReg(OutgoingArg->getRegister());
2758   } else {
2759     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2760     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2761                                             SpecialArgOffset);
2762     MemOpChains.push_back(ArgStore);
2763   }
2764 }
2765 
2766 static bool canGuaranteeTCO(CallingConv::ID CC) {
2767   return CC == CallingConv::Fast;
2768 }
2769 
2770 /// Return true if we might ever do TCO for calls with this calling convention.
2771 static bool mayTailCallThisCC(CallingConv::ID CC) {
2772   switch (CC) {
2773   case CallingConv::C:
2774     return true;
2775   default:
2776     return canGuaranteeTCO(CC);
2777   }
2778 }
2779 
2780 bool SITargetLowering::isEligibleForTailCallOptimization(
2781     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2782     const SmallVectorImpl<ISD::OutputArg> &Outs,
2783     const SmallVectorImpl<SDValue> &OutVals,
2784     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2785   if (!mayTailCallThisCC(CalleeCC))
2786     return false;
2787 
2788   MachineFunction &MF = DAG.getMachineFunction();
2789   const Function &CallerF = MF.getFunction();
2790   CallingConv::ID CallerCC = CallerF.getCallingConv();
2791   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2792   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2793 
2794   // Kernels aren't callable, and don't have a live in return address so it
2795   // doesn't make sense to do a tail call with entry functions.
2796   if (!CallerPreserved)
2797     return false;
2798 
2799   bool CCMatch = CallerCC == CalleeCC;
2800 
2801   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2802     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2803       return true;
2804     return false;
2805   }
2806 
2807   // TODO: Can we handle var args?
2808   if (IsVarArg)
2809     return false;
2810 
2811   for (const Argument &Arg : CallerF.args()) {
2812     if (Arg.hasByValAttr())
2813       return false;
2814   }
2815 
2816   LLVMContext &Ctx = *DAG.getContext();
2817 
2818   // Check that the call results are passed in the same way.
2819   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2820                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2821                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2822     return false;
2823 
2824   // The callee has to preserve all registers the caller needs to preserve.
2825   if (!CCMatch) {
2826     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2827     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2828       return false;
2829   }
2830 
2831   // Nothing more to check if the callee is taking no arguments.
2832   if (Outs.empty())
2833     return true;
2834 
2835   SmallVector<CCValAssign, 16> ArgLocs;
2836   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2837 
2838   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2839 
2840   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2841   // If the stack arguments for this call do not fit into our own save area then
2842   // the call cannot be made tail.
2843   // TODO: Is this really necessary?
2844   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2845     return false;
2846 
2847   const MachineRegisterInfo &MRI = MF.getRegInfo();
2848   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2849 }
2850 
2851 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2852   if (!CI->isTailCall())
2853     return false;
2854 
2855   const Function *ParentFn = CI->getParent()->getParent();
2856   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2857     return false;
2858   return true;
2859 }
2860 
2861 // The wave scratch offset register is used as the global base pointer.
2862 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2863                                     SmallVectorImpl<SDValue> &InVals) const {
2864   SelectionDAG &DAG = CLI.DAG;
2865   const SDLoc &DL = CLI.DL;
2866   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2867   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2868   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2869   SDValue Chain = CLI.Chain;
2870   SDValue Callee = CLI.Callee;
2871   bool &IsTailCall = CLI.IsTailCall;
2872   CallingConv::ID CallConv = CLI.CallConv;
2873   bool IsVarArg = CLI.IsVarArg;
2874   bool IsSibCall = false;
2875   bool IsThisReturn = false;
2876   MachineFunction &MF = DAG.getMachineFunction();
2877 
2878   if (Callee.isUndef() || isNullConstant(Callee)) {
2879     if (!CLI.IsTailCall) {
2880       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2881         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2882     }
2883 
2884     return Chain;
2885   }
2886 
2887   if (IsVarArg) {
2888     return lowerUnhandledCall(CLI, InVals,
2889                               "unsupported call to variadic function ");
2890   }
2891 
2892   if (!CLI.CB)
2893     report_fatal_error("unsupported libcall legalization");
2894 
2895   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2896       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2897     return lowerUnhandledCall(CLI, InVals,
2898                               "unsupported indirect call to function ");
2899   }
2900 
2901   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2902     return lowerUnhandledCall(CLI, InVals,
2903                               "unsupported required tail call to function ");
2904   }
2905 
2906   if (AMDGPU::isShader(CallConv)) {
2907     // Note the issue is with the CC of the called function, not of the call
2908     // itself.
2909     return lowerUnhandledCall(CLI, InVals,
2910                               "unsupported call to a shader function ");
2911   }
2912 
2913   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2914       CallConv != CallingConv::AMDGPU_Gfx) {
2915     // Only allow calls with specific calling conventions.
2916     return lowerUnhandledCall(CLI, InVals,
2917                               "unsupported calling convention for call from "
2918                               "graphics shader of function ");
2919   }
2920 
2921   if (IsTailCall) {
2922     IsTailCall = isEligibleForTailCallOptimization(
2923       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2924     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2925       report_fatal_error("failed to perform tail call elimination on a call "
2926                          "site marked musttail");
2927     }
2928 
2929     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2930 
2931     // A sibling call is one where we're under the usual C ABI and not planning
2932     // to change that but can still do a tail call:
2933     if (!TailCallOpt && IsTailCall)
2934       IsSibCall = true;
2935 
2936     if (IsTailCall)
2937       ++NumTailCalls;
2938   }
2939 
2940   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2941   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2942   SmallVector<SDValue, 8> MemOpChains;
2943 
2944   // Analyze operands of the call, assigning locations to each operand.
2945   SmallVector<CCValAssign, 16> ArgLocs;
2946   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2947   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2948 
2949   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
2950       CallConv != CallingConv::AMDGPU_Gfx) {
2951     // With a fixed ABI, allocate fixed registers before user arguments.
2952     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2953   }
2954 
2955   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2956 
2957   // Get a count of how many bytes are to be pushed on the stack.
2958   unsigned NumBytes = CCInfo.getNextStackOffset();
2959 
2960   if (IsSibCall) {
2961     // Since we're not changing the ABI to make this a tail call, the memory
2962     // operands are already available in the caller's incoming argument space.
2963     NumBytes = 0;
2964   }
2965 
2966   // FPDiff is the byte offset of the call's argument area from the callee's.
2967   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2968   // by this amount for a tail call. In a sibling call it must be 0 because the
2969   // caller will deallocate the entire stack and the callee still expects its
2970   // arguments to begin at SP+0. Completely unused for non-tail calls.
2971   int32_t FPDiff = 0;
2972   MachineFrameInfo &MFI = MF.getFrameInfo();
2973 
2974   // Adjust the stack pointer for the new arguments...
2975   // These operations are automatically eliminated by the prolog/epilog pass
2976   if (!IsSibCall) {
2977     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2978 
2979     if (!Subtarget->enableFlatScratch()) {
2980       SmallVector<SDValue, 4> CopyFromChains;
2981 
2982       // In the HSA case, this should be an identity copy.
2983       SDValue ScratchRSrcReg
2984         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2985       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2986       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2987       Chain = DAG.getTokenFactor(DL, CopyFromChains);
2988     }
2989   }
2990 
2991   MVT PtrVT = MVT::i32;
2992 
2993   // Walk the register/memloc assignments, inserting copies/loads.
2994   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2995     CCValAssign &VA = ArgLocs[i];
2996     SDValue Arg = OutVals[i];
2997 
2998     // Promote the value if needed.
2999     switch (VA.getLocInfo()) {
3000     case CCValAssign::Full:
3001       break;
3002     case CCValAssign::BCvt:
3003       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3004       break;
3005     case CCValAssign::ZExt:
3006       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3007       break;
3008     case CCValAssign::SExt:
3009       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3010       break;
3011     case CCValAssign::AExt:
3012       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3013       break;
3014     case CCValAssign::FPExt:
3015       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3016       break;
3017     default:
3018       llvm_unreachable("Unknown loc info!");
3019     }
3020 
3021     if (VA.isRegLoc()) {
3022       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3023     } else {
3024       assert(VA.isMemLoc());
3025 
3026       SDValue DstAddr;
3027       MachinePointerInfo DstInfo;
3028 
3029       unsigned LocMemOffset = VA.getLocMemOffset();
3030       int32_t Offset = LocMemOffset;
3031 
3032       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3033       MaybeAlign Alignment;
3034 
3035       if (IsTailCall) {
3036         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3037         unsigned OpSize = Flags.isByVal() ?
3038           Flags.getByValSize() : VA.getValVT().getStoreSize();
3039 
3040         // FIXME: We can have better than the minimum byval required alignment.
3041         Alignment =
3042             Flags.isByVal()
3043                 ? Flags.getNonZeroByValAlign()
3044                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3045 
3046         Offset = Offset + FPDiff;
3047         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3048 
3049         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3050         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3051 
3052         // Make sure any stack arguments overlapping with where we're storing
3053         // are loaded before this eventual operation. Otherwise they'll be
3054         // clobbered.
3055 
3056         // FIXME: Why is this really necessary? This seems to just result in a
3057         // lot of code to copy the stack and write them back to the same
3058         // locations, which are supposed to be immutable?
3059         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3060       } else {
3061         DstAddr = PtrOff;
3062         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3063         Alignment =
3064             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3065       }
3066 
3067       if (Outs[i].Flags.isByVal()) {
3068         SDValue SizeNode =
3069             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3070         SDValue Cpy =
3071             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3072                           Outs[i].Flags.getNonZeroByValAlign(),
3073                           /*isVol = */ false, /*AlwaysInline = */ true,
3074                           /*isTailCall = */ false, DstInfo,
3075                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3076 
3077         MemOpChains.push_back(Cpy);
3078       } else {
3079         SDValue Store =
3080             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3081         MemOpChains.push_back(Store);
3082       }
3083     }
3084   }
3085 
3086   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3087       CallConv != CallingConv::AMDGPU_Gfx) {
3088     // Copy special input registers after user input arguments.
3089     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3090   }
3091 
3092   if (!MemOpChains.empty())
3093     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3094 
3095   // Build a sequence of copy-to-reg nodes chained together with token chain
3096   // and flag operands which copy the outgoing args into the appropriate regs.
3097   SDValue InFlag;
3098   for (auto &RegToPass : RegsToPass) {
3099     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3100                              RegToPass.second, InFlag);
3101     InFlag = Chain.getValue(1);
3102   }
3103 
3104 
3105   SDValue PhysReturnAddrReg;
3106   if (IsTailCall) {
3107     // Since the return is being combined with the call, we need to pass on the
3108     // return address.
3109 
3110     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3111     SDValue ReturnAddrReg = CreateLiveInRegister(
3112       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3113 
3114     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3115                                         MVT::i64);
3116     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3117     InFlag = Chain.getValue(1);
3118   }
3119 
3120   // We don't usually want to end the call-sequence here because we would tidy
3121   // the frame up *after* the call, however in the ABI-changing tail-call case
3122   // we've carefully laid out the parameters so that when sp is reset they'll be
3123   // in the correct location.
3124   if (IsTailCall && !IsSibCall) {
3125     Chain = DAG.getCALLSEQ_END(Chain,
3126                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3127                                DAG.getTargetConstant(0, DL, MVT::i32),
3128                                InFlag, DL);
3129     InFlag = Chain.getValue(1);
3130   }
3131 
3132   std::vector<SDValue> Ops;
3133   Ops.push_back(Chain);
3134   Ops.push_back(Callee);
3135   // Add a redundant copy of the callee global which will not be legalized, as
3136   // we need direct access to the callee later.
3137   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3138     const GlobalValue *GV = GSD->getGlobal();
3139     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3140   } else {
3141     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3142   }
3143 
3144   if (IsTailCall) {
3145     // Each tail call may have to adjust the stack by a different amount, so
3146     // this information must travel along with the operation for eventual
3147     // consumption by emitEpilogue.
3148     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3149 
3150     Ops.push_back(PhysReturnAddrReg);
3151   }
3152 
3153   // Add argument registers to the end of the list so that they are known live
3154   // into the call.
3155   for (auto &RegToPass : RegsToPass) {
3156     Ops.push_back(DAG.getRegister(RegToPass.first,
3157                                   RegToPass.second.getValueType()));
3158   }
3159 
3160   // Add a register mask operand representing the call-preserved registers.
3161 
3162   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3163   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3164   assert(Mask && "Missing call preserved mask for calling convention");
3165   Ops.push_back(DAG.getRegisterMask(Mask));
3166 
3167   if (InFlag.getNode())
3168     Ops.push_back(InFlag);
3169 
3170   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3171 
3172   // If we're doing a tall call, use a TC_RETURN here rather than an
3173   // actual call instruction.
3174   if (IsTailCall) {
3175     MFI.setHasTailCall();
3176     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3177   }
3178 
3179   // Returns a chain and a flag for retval copy to use.
3180   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3181   Chain = Call.getValue(0);
3182   InFlag = Call.getValue(1);
3183 
3184   uint64_t CalleePopBytes = NumBytes;
3185   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3186                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3187                              InFlag, DL);
3188   if (!Ins.empty())
3189     InFlag = Chain.getValue(1);
3190 
3191   // Handle result values, copying them out of physregs into vregs that we
3192   // return.
3193   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3194                          InVals, IsThisReturn,
3195                          IsThisReturn ? OutVals[0] : SDValue());
3196 }
3197 
3198 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3199 // except for applying the wave size scale to the increment amount.
3200 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3201     SDValue Op, SelectionDAG &DAG) const {
3202   const MachineFunction &MF = DAG.getMachineFunction();
3203   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3204 
3205   SDLoc dl(Op);
3206   EVT VT = Op.getValueType();
3207   SDValue Tmp1 = Op;
3208   SDValue Tmp2 = Op.getValue(1);
3209   SDValue Tmp3 = Op.getOperand(2);
3210   SDValue Chain = Tmp1.getOperand(0);
3211 
3212   Register SPReg = Info->getStackPtrOffsetReg();
3213 
3214   // Chain the dynamic stack allocation so that it doesn't modify the stack
3215   // pointer when other instructions are using the stack.
3216   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3217 
3218   SDValue Size  = Tmp2.getOperand(1);
3219   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3220   Chain = SP.getValue(1);
3221   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3222   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3223   const TargetFrameLowering *TFL = ST.getFrameLowering();
3224   unsigned Opc =
3225     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3226     ISD::ADD : ISD::SUB;
3227 
3228   SDValue ScaledSize = DAG.getNode(
3229       ISD::SHL, dl, VT, Size,
3230       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3231 
3232   Align StackAlign = TFL->getStackAlign();
3233   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3234   if (Alignment && *Alignment > StackAlign) {
3235     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3236                        DAG.getConstant(-(uint64_t)Alignment->value()
3237                                            << ST.getWavefrontSizeLog2(),
3238                                        dl, VT));
3239   }
3240 
3241   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3242   Tmp2 = DAG.getCALLSEQ_END(
3243       Chain, DAG.getIntPtrConstant(0, dl, true),
3244       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3245 
3246   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3247 }
3248 
3249 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3250                                                   SelectionDAG &DAG) const {
3251   // We only handle constant sizes here to allow non-entry block, static sized
3252   // allocas. A truly dynamic value is more difficult to support because we
3253   // don't know if the size value is uniform or not. If the size isn't uniform,
3254   // we would need to do a wave reduction to get the maximum size to know how
3255   // much to increment the uniform stack pointer.
3256   SDValue Size = Op.getOperand(1);
3257   if (isa<ConstantSDNode>(Size))
3258       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3259 
3260   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3261 }
3262 
3263 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3264                                              const MachineFunction &MF) const {
3265   Register Reg = StringSwitch<Register>(RegName)
3266     .Case("m0", AMDGPU::M0)
3267     .Case("exec", AMDGPU::EXEC)
3268     .Case("exec_lo", AMDGPU::EXEC_LO)
3269     .Case("exec_hi", AMDGPU::EXEC_HI)
3270     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3271     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3272     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3273     .Default(Register());
3274 
3275   if (Reg == AMDGPU::NoRegister) {
3276     report_fatal_error(Twine("invalid register name \""
3277                              + StringRef(RegName)  + "\"."));
3278 
3279   }
3280 
3281   if (!Subtarget->hasFlatScrRegister() &&
3282        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3283     report_fatal_error(Twine("invalid register \""
3284                              + StringRef(RegName)  + "\" for subtarget."));
3285   }
3286 
3287   switch (Reg) {
3288   case AMDGPU::M0:
3289   case AMDGPU::EXEC_LO:
3290   case AMDGPU::EXEC_HI:
3291   case AMDGPU::FLAT_SCR_LO:
3292   case AMDGPU::FLAT_SCR_HI:
3293     if (VT.getSizeInBits() == 32)
3294       return Reg;
3295     break;
3296   case AMDGPU::EXEC:
3297   case AMDGPU::FLAT_SCR:
3298     if (VT.getSizeInBits() == 64)
3299       return Reg;
3300     break;
3301   default:
3302     llvm_unreachable("missing register type checking");
3303   }
3304 
3305   report_fatal_error(Twine("invalid type for register \""
3306                            + StringRef(RegName) + "\"."));
3307 }
3308 
3309 // If kill is not the last instruction, split the block so kill is always a
3310 // proper terminator.
3311 MachineBasicBlock *
3312 SITargetLowering::splitKillBlock(MachineInstr &MI,
3313                                  MachineBasicBlock *BB) const {
3314   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3315   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3316   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3317   return SplitBB;
3318 }
3319 
3320 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3321 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3322 // be the first instruction in the remainder block.
3323 //
3324 /// \returns { LoopBody, Remainder }
3325 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3326 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3327   MachineFunction *MF = MBB.getParent();
3328   MachineBasicBlock::iterator I(&MI);
3329 
3330   // To insert the loop we need to split the block. Move everything after this
3331   // point to a new block, and insert a new empty block between the two.
3332   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3333   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3334   MachineFunction::iterator MBBI(MBB);
3335   ++MBBI;
3336 
3337   MF->insert(MBBI, LoopBB);
3338   MF->insert(MBBI, RemainderBB);
3339 
3340   LoopBB->addSuccessor(LoopBB);
3341   LoopBB->addSuccessor(RemainderBB);
3342 
3343   // Move the rest of the block into a new block.
3344   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3345 
3346   if (InstInLoop) {
3347     auto Next = std::next(I);
3348 
3349     // Move instruction to loop body.
3350     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3351 
3352     // Move the rest of the block.
3353     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3354   } else {
3355     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3356   }
3357 
3358   MBB.addSuccessor(LoopBB);
3359 
3360   return std::make_pair(LoopBB, RemainderBB);
3361 }
3362 
3363 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3364 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3365   MachineBasicBlock *MBB = MI.getParent();
3366   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3367   auto I = MI.getIterator();
3368   auto E = std::next(I);
3369 
3370   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3371     .addImm(0);
3372 
3373   MIBundleBuilder Bundler(*MBB, I, E);
3374   finalizeBundle(*MBB, Bundler.begin());
3375 }
3376 
3377 MachineBasicBlock *
3378 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3379                                          MachineBasicBlock *BB) const {
3380   const DebugLoc &DL = MI.getDebugLoc();
3381 
3382   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3383 
3384   MachineBasicBlock *LoopBB;
3385   MachineBasicBlock *RemainderBB;
3386   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3387 
3388   // Apparently kill flags are only valid if the def is in the same block?
3389   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3390     Src->setIsKill(false);
3391 
3392   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3393 
3394   MachineBasicBlock::iterator I = LoopBB->end();
3395 
3396   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3397     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3398 
3399   // Clear TRAP_STS.MEM_VIOL
3400   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3401     .addImm(0)
3402     .addImm(EncodedReg);
3403 
3404   bundleInstWithWaitcnt(MI);
3405 
3406   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3407 
3408   // Load and check TRAP_STS.MEM_VIOL
3409   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3410     .addImm(EncodedReg);
3411 
3412   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3413   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3414     .addReg(Reg, RegState::Kill)
3415     .addImm(0);
3416   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3417     .addMBB(LoopBB);
3418 
3419   return RemainderBB;
3420 }
3421 
3422 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3423 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3424 // will only do one iteration. In the worst case, this will loop 64 times.
3425 //
3426 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3427 static MachineBasicBlock::iterator
3428 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3429                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3430                        const DebugLoc &DL, const MachineOperand &Idx,
3431                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3432                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3433                        Register &SGPRIdxReg) {
3434 
3435   MachineFunction *MF = OrigBB.getParent();
3436   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3437   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3438   MachineBasicBlock::iterator I = LoopBB.begin();
3439 
3440   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3441   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3442   Register NewExec = MRI.createVirtualRegister(BoolRC);
3443   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3444   Register CondReg = MRI.createVirtualRegister(BoolRC);
3445 
3446   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3447     .addReg(InitReg)
3448     .addMBB(&OrigBB)
3449     .addReg(ResultReg)
3450     .addMBB(&LoopBB);
3451 
3452   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3453     .addReg(InitSaveExecReg)
3454     .addMBB(&OrigBB)
3455     .addReg(NewExec)
3456     .addMBB(&LoopBB);
3457 
3458   // Read the next variant <- also loop target.
3459   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3460       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3461 
3462   // Compare the just read M0 value to all possible Idx values.
3463   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3464       .addReg(CurrentIdxReg)
3465       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3466 
3467   // Update EXEC, save the original EXEC value to VCC.
3468   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3469                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3470           NewExec)
3471     .addReg(CondReg, RegState::Kill);
3472 
3473   MRI.setSimpleHint(NewExec, CondReg);
3474 
3475   if (UseGPRIdxMode) {
3476     if (Offset == 0) {
3477       SGPRIdxReg = CurrentIdxReg;
3478     } else {
3479       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3480       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3481           .addReg(CurrentIdxReg, RegState::Kill)
3482           .addImm(Offset);
3483     }
3484   } else {
3485     // Move index from VCC into M0
3486     if (Offset == 0) {
3487       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3488         .addReg(CurrentIdxReg, RegState::Kill);
3489     } else {
3490       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3491         .addReg(CurrentIdxReg, RegState::Kill)
3492         .addImm(Offset);
3493     }
3494   }
3495 
3496   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3497   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3498   MachineInstr *InsertPt =
3499     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3500                                                   : AMDGPU::S_XOR_B64_term), Exec)
3501       .addReg(Exec)
3502       .addReg(NewExec);
3503 
3504   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3505   // s_cbranch_scc0?
3506 
3507   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3508   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3509     .addMBB(&LoopBB);
3510 
3511   return InsertPt->getIterator();
3512 }
3513 
3514 // This has slightly sub-optimal regalloc when the source vector is killed by
3515 // the read. The register allocator does not understand that the kill is
3516 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3517 // subregister from it, using 1 more VGPR than necessary. This was saved when
3518 // this was expanded after register allocation.
3519 static MachineBasicBlock::iterator
3520 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3521                unsigned InitResultReg, unsigned PhiReg, int Offset,
3522                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3523   MachineFunction *MF = MBB.getParent();
3524   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3525   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3526   MachineRegisterInfo &MRI = MF->getRegInfo();
3527   const DebugLoc &DL = MI.getDebugLoc();
3528   MachineBasicBlock::iterator I(&MI);
3529 
3530   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3531   Register DstReg = MI.getOperand(0).getReg();
3532   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3533   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3534   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3535   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3536 
3537   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3538 
3539   // Save the EXEC mask
3540   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3541     .addReg(Exec);
3542 
3543   MachineBasicBlock *LoopBB;
3544   MachineBasicBlock *RemainderBB;
3545   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3546 
3547   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3548 
3549   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3550                                       InitResultReg, DstReg, PhiReg, TmpExec,
3551                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3552 
3553   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3554   MachineFunction::iterator MBBI(LoopBB);
3555   ++MBBI;
3556   MF->insert(MBBI, LandingPad);
3557   LoopBB->removeSuccessor(RemainderBB);
3558   LandingPad->addSuccessor(RemainderBB);
3559   LoopBB->addSuccessor(LandingPad);
3560   MachineBasicBlock::iterator First = LandingPad->begin();
3561   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3562     .addReg(SaveExec);
3563 
3564   return InsPt;
3565 }
3566 
3567 // Returns subreg index, offset
3568 static std::pair<unsigned, int>
3569 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3570                             const TargetRegisterClass *SuperRC,
3571                             unsigned VecReg,
3572                             int Offset) {
3573   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3574 
3575   // Skip out of bounds offsets, or else we would end up using an undefined
3576   // register.
3577   if (Offset >= NumElts || Offset < 0)
3578     return std::make_pair(AMDGPU::sub0, Offset);
3579 
3580   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3581 }
3582 
3583 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3584                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3585                                  int Offset) {
3586   MachineBasicBlock *MBB = MI.getParent();
3587   const DebugLoc &DL = MI.getDebugLoc();
3588   MachineBasicBlock::iterator I(&MI);
3589 
3590   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3591 
3592   assert(Idx->getReg() != AMDGPU::NoRegister);
3593 
3594   if (Offset == 0) {
3595     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3596   } else {
3597     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3598         .add(*Idx)
3599         .addImm(Offset);
3600   }
3601 }
3602 
3603 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3604                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3605                                    int Offset) {
3606   MachineBasicBlock *MBB = MI.getParent();
3607   const DebugLoc &DL = MI.getDebugLoc();
3608   MachineBasicBlock::iterator I(&MI);
3609 
3610   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3611 
3612   if (Offset == 0)
3613     return Idx->getReg();
3614 
3615   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3616   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3617       .add(*Idx)
3618       .addImm(Offset);
3619   return Tmp;
3620 }
3621 
3622 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3623                                           MachineBasicBlock &MBB,
3624                                           const GCNSubtarget &ST) {
3625   const SIInstrInfo *TII = ST.getInstrInfo();
3626   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3627   MachineFunction *MF = MBB.getParent();
3628   MachineRegisterInfo &MRI = MF->getRegInfo();
3629 
3630   Register Dst = MI.getOperand(0).getReg();
3631   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3632   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3633   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3634 
3635   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3636   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3637 
3638   unsigned SubReg;
3639   std::tie(SubReg, Offset)
3640     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3641 
3642   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3643 
3644   // Check for a SGPR index.
3645   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3646     MachineBasicBlock::iterator I(&MI);
3647     const DebugLoc &DL = MI.getDebugLoc();
3648 
3649     if (UseGPRIdxMode) {
3650       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3651       // to avoid interfering with other uses, so probably requires a new
3652       // optimization pass.
3653       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3654 
3655       const MCInstrDesc &GPRIDXDesc =
3656           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3657       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3658           .addReg(SrcReg)
3659           .addReg(Idx)
3660           .addImm(SubReg);
3661     } else {
3662       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3663 
3664       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3665         .addReg(SrcReg, 0, SubReg)
3666         .addReg(SrcReg, RegState::Implicit);
3667     }
3668 
3669     MI.eraseFromParent();
3670 
3671     return &MBB;
3672   }
3673 
3674   // Control flow needs to be inserted if indexing with a VGPR.
3675   const DebugLoc &DL = MI.getDebugLoc();
3676   MachineBasicBlock::iterator I(&MI);
3677 
3678   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3679   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3680 
3681   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3682 
3683   Register SGPRIdxReg;
3684   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3685                               UseGPRIdxMode, SGPRIdxReg);
3686 
3687   MachineBasicBlock *LoopBB = InsPt->getParent();
3688 
3689   if (UseGPRIdxMode) {
3690     const MCInstrDesc &GPRIDXDesc =
3691         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3692 
3693     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3694         .addReg(SrcReg)
3695         .addReg(SGPRIdxReg)
3696         .addImm(SubReg);
3697   } else {
3698     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3699       .addReg(SrcReg, 0, SubReg)
3700       .addReg(SrcReg, RegState::Implicit);
3701   }
3702 
3703   MI.eraseFromParent();
3704 
3705   return LoopBB;
3706 }
3707 
3708 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3709                                           MachineBasicBlock &MBB,
3710                                           const GCNSubtarget &ST) {
3711   const SIInstrInfo *TII = ST.getInstrInfo();
3712   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3713   MachineFunction *MF = MBB.getParent();
3714   MachineRegisterInfo &MRI = MF->getRegInfo();
3715 
3716   Register Dst = MI.getOperand(0).getReg();
3717   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3718   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3719   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3720   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3721   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3722   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3723 
3724   // This can be an immediate, but will be folded later.
3725   assert(Val->getReg());
3726 
3727   unsigned SubReg;
3728   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3729                                                          SrcVec->getReg(),
3730                                                          Offset);
3731   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3732 
3733   if (Idx->getReg() == AMDGPU::NoRegister) {
3734     MachineBasicBlock::iterator I(&MI);
3735     const DebugLoc &DL = MI.getDebugLoc();
3736 
3737     assert(Offset == 0);
3738 
3739     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3740         .add(*SrcVec)
3741         .add(*Val)
3742         .addImm(SubReg);
3743 
3744     MI.eraseFromParent();
3745     return &MBB;
3746   }
3747 
3748   // Check for a SGPR index.
3749   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3750     MachineBasicBlock::iterator I(&MI);
3751     const DebugLoc &DL = MI.getDebugLoc();
3752 
3753     if (UseGPRIdxMode) {
3754       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3755 
3756       const MCInstrDesc &GPRIDXDesc =
3757           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3758       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3759           .addReg(SrcVec->getReg())
3760           .add(*Val)
3761           .addReg(Idx)
3762           .addImm(SubReg);
3763     } else {
3764       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3765 
3766       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3767           TRI.getRegSizeInBits(*VecRC), 32, false);
3768       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3769           .addReg(SrcVec->getReg())
3770           .add(*Val)
3771           .addImm(SubReg);
3772     }
3773     MI.eraseFromParent();
3774     return &MBB;
3775   }
3776 
3777   // Control flow needs to be inserted if indexing with a VGPR.
3778   if (Val->isReg())
3779     MRI.clearKillFlags(Val->getReg());
3780 
3781   const DebugLoc &DL = MI.getDebugLoc();
3782 
3783   Register PhiReg = MRI.createVirtualRegister(VecRC);
3784 
3785   Register SGPRIdxReg;
3786   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3787                               UseGPRIdxMode, SGPRIdxReg);
3788   MachineBasicBlock *LoopBB = InsPt->getParent();
3789 
3790   if (UseGPRIdxMode) {
3791     const MCInstrDesc &GPRIDXDesc =
3792         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3793 
3794     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3795         .addReg(PhiReg)
3796         .add(*Val)
3797         .addReg(SGPRIdxReg)
3798         .addImm(AMDGPU::sub0);
3799   } else {
3800     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3801         TRI.getRegSizeInBits(*VecRC), 32, false);
3802     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3803         .addReg(PhiReg)
3804         .add(*Val)
3805         .addImm(AMDGPU::sub0);
3806   }
3807 
3808   MI.eraseFromParent();
3809   return LoopBB;
3810 }
3811 
3812 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3813   MachineInstr &MI, MachineBasicBlock *BB) const {
3814 
3815   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3816   MachineFunction *MF = BB->getParent();
3817   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3818 
3819   switch (MI.getOpcode()) {
3820   case AMDGPU::S_UADDO_PSEUDO:
3821   case AMDGPU::S_USUBO_PSEUDO: {
3822     const DebugLoc &DL = MI.getDebugLoc();
3823     MachineOperand &Dest0 = MI.getOperand(0);
3824     MachineOperand &Dest1 = MI.getOperand(1);
3825     MachineOperand &Src0 = MI.getOperand(2);
3826     MachineOperand &Src1 = MI.getOperand(3);
3827 
3828     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3829                        ? AMDGPU::S_ADD_I32
3830                        : AMDGPU::S_SUB_I32;
3831     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3832 
3833     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3834         .addImm(1)
3835         .addImm(0);
3836 
3837     MI.eraseFromParent();
3838     return BB;
3839   }
3840   case AMDGPU::S_ADD_U64_PSEUDO:
3841   case AMDGPU::S_SUB_U64_PSEUDO: {
3842     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3843     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3844     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3845     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3846     const DebugLoc &DL = MI.getDebugLoc();
3847 
3848     MachineOperand &Dest = MI.getOperand(0);
3849     MachineOperand &Src0 = MI.getOperand(1);
3850     MachineOperand &Src1 = MI.getOperand(2);
3851 
3852     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3853     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3854 
3855     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3856         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3857     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3858         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3859 
3860     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3861         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3862     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3863         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3864 
3865     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3866 
3867     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3868     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3869     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3870     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3871     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3872         .addReg(DestSub0)
3873         .addImm(AMDGPU::sub0)
3874         .addReg(DestSub1)
3875         .addImm(AMDGPU::sub1);
3876     MI.eraseFromParent();
3877     return BB;
3878   }
3879   case AMDGPU::V_ADD_U64_PSEUDO:
3880   case AMDGPU::V_SUB_U64_PSEUDO: {
3881     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3882     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3883     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3884     const DebugLoc &DL = MI.getDebugLoc();
3885 
3886     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3887 
3888     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3889 
3890     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3891     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3892 
3893     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3894     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3895 
3896     MachineOperand &Dest = MI.getOperand(0);
3897     MachineOperand &Src0 = MI.getOperand(1);
3898     MachineOperand &Src1 = MI.getOperand(2);
3899 
3900     const TargetRegisterClass *Src0RC = Src0.isReg()
3901                                             ? MRI.getRegClass(Src0.getReg())
3902                                             : &AMDGPU::VReg_64RegClass;
3903     const TargetRegisterClass *Src1RC = Src1.isReg()
3904                                             ? MRI.getRegClass(Src1.getReg())
3905                                             : &AMDGPU::VReg_64RegClass;
3906 
3907     const TargetRegisterClass *Src0SubRC =
3908         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3909     const TargetRegisterClass *Src1SubRC =
3910         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3911 
3912     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3913         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3914     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3915         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3916 
3917     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3918         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3919     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3920         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3921 
3922     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3923     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3924                                .addReg(CarryReg, RegState::Define)
3925                                .add(SrcReg0Sub0)
3926                                .add(SrcReg1Sub0)
3927                                .addImm(0); // clamp bit
3928 
3929     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3930     MachineInstr *HiHalf =
3931         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3932             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3933             .add(SrcReg0Sub1)
3934             .add(SrcReg1Sub1)
3935             .addReg(CarryReg, RegState::Kill)
3936             .addImm(0); // clamp bit
3937 
3938     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3939         .addReg(DestSub0)
3940         .addImm(AMDGPU::sub0)
3941         .addReg(DestSub1)
3942         .addImm(AMDGPU::sub1);
3943     TII->legalizeOperands(*LoHalf);
3944     TII->legalizeOperands(*HiHalf);
3945     MI.eraseFromParent();
3946     return BB;
3947   }
3948   case AMDGPU::S_ADD_CO_PSEUDO:
3949   case AMDGPU::S_SUB_CO_PSEUDO: {
3950     // This pseudo has a chance to be selected
3951     // only from uniform add/subcarry node. All the VGPR operands
3952     // therefore assumed to be splat vectors.
3953     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3954     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3955     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3956     MachineBasicBlock::iterator MII = MI;
3957     const DebugLoc &DL = MI.getDebugLoc();
3958     MachineOperand &Dest = MI.getOperand(0);
3959     MachineOperand &CarryDest = MI.getOperand(1);
3960     MachineOperand &Src0 = MI.getOperand(2);
3961     MachineOperand &Src1 = MI.getOperand(3);
3962     MachineOperand &Src2 = MI.getOperand(4);
3963     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3964                        ? AMDGPU::S_ADDC_U32
3965                        : AMDGPU::S_SUBB_U32;
3966     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3967       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3968       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3969           .addReg(Src0.getReg());
3970       Src0.setReg(RegOp0);
3971     }
3972     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3973       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3974       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3975           .addReg(Src1.getReg());
3976       Src1.setReg(RegOp1);
3977     }
3978     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3979     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3980       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3981           .addReg(Src2.getReg());
3982       Src2.setReg(RegOp2);
3983     }
3984 
3985     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
3986     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
3987       if (ST.hasScalarCompareEq64()) {
3988         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3989             .addReg(Src2.getReg())
3990             .addImm(0);
3991       } else {
3992         const TargetRegisterClass *SubRC =
3993             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
3994         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
3995             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
3996         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
3997             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
3998         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3999 
4000         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4001             .add(Src2Sub0)
4002             .add(Src2Sub1);
4003 
4004         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4005             .addReg(Src2_32, RegState::Kill)
4006             .addImm(0);
4007       }
4008     } else {
4009       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4010           .addReg(Src2.getReg())
4011           .addImm(0);
4012     }
4013 
4014     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4015 
4016     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4017       .addReg(AMDGPU::SCC);
4018     MI.eraseFromParent();
4019     return BB;
4020   }
4021   case AMDGPU::SI_INIT_M0: {
4022     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4023             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4024         .add(MI.getOperand(0));
4025     MI.eraseFromParent();
4026     return BB;
4027   }
4028   case AMDGPU::SI_INIT_EXEC:
4029     // This should be before all vector instructions.
4030     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4031             AMDGPU::EXEC)
4032         .addImm(MI.getOperand(0).getImm());
4033     MI.eraseFromParent();
4034     return BB;
4035 
4036   case AMDGPU::SI_INIT_EXEC_LO:
4037     // This should be before all vector instructions.
4038     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4039             AMDGPU::EXEC_LO)
4040         .addImm(MI.getOperand(0).getImm());
4041     MI.eraseFromParent();
4042     return BB;
4043 
4044   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4045     // Extract the thread count from an SGPR input and set EXEC accordingly.
4046     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4047     //
4048     // S_BFE_U32 count, input, {shift, 7}
4049     // S_BFM_B64 exec, count, 0
4050     // S_CMP_EQ_U32 count, 64
4051     // S_CMOV_B64 exec, -1
4052     MachineInstr *FirstMI = &*BB->begin();
4053     MachineRegisterInfo &MRI = MF->getRegInfo();
4054     Register InputReg = MI.getOperand(0).getReg();
4055     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4056     bool Found = false;
4057 
4058     // Move the COPY of the input reg to the beginning, so that we can use it.
4059     for (auto I = BB->begin(); I != &MI; I++) {
4060       if (I->getOpcode() != TargetOpcode::COPY ||
4061           I->getOperand(0).getReg() != InputReg)
4062         continue;
4063 
4064       if (I == FirstMI) {
4065         FirstMI = &*++BB->begin();
4066       } else {
4067         I->removeFromParent();
4068         BB->insert(FirstMI, &*I);
4069       }
4070       Found = true;
4071       break;
4072     }
4073     assert(Found);
4074     (void)Found;
4075 
4076     // This should be before all vector instructions.
4077     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4078     bool isWave32 = getSubtarget()->isWave32();
4079     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4080     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4081         .addReg(InputReg)
4082         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4083     BuildMI(*BB, FirstMI, DebugLoc(),
4084             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4085             Exec)
4086         .addReg(CountReg)
4087         .addImm(0);
4088     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4089         .addReg(CountReg, RegState::Kill)
4090         .addImm(getSubtarget()->getWavefrontSize());
4091     BuildMI(*BB, FirstMI, DebugLoc(),
4092             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4093             Exec)
4094         .addImm(-1);
4095     MI.eraseFromParent();
4096     return BB;
4097   }
4098 
4099   case AMDGPU::GET_GROUPSTATICSIZE: {
4100     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4101            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4102     DebugLoc DL = MI.getDebugLoc();
4103     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4104         .add(MI.getOperand(0))
4105         .addImm(MFI->getLDSSize());
4106     MI.eraseFromParent();
4107     return BB;
4108   }
4109   case AMDGPU::SI_INDIRECT_SRC_V1:
4110   case AMDGPU::SI_INDIRECT_SRC_V2:
4111   case AMDGPU::SI_INDIRECT_SRC_V4:
4112   case AMDGPU::SI_INDIRECT_SRC_V8:
4113   case AMDGPU::SI_INDIRECT_SRC_V16:
4114   case AMDGPU::SI_INDIRECT_SRC_V32:
4115     return emitIndirectSrc(MI, *BB, *getSubtarget());
4116   case AMDGPU::SI_INDIRECT_DST_V1:
4117   case AMDGPU::SI_INDIRECT_DST_V2:
4118   case AMDGPU::SI_INDIRECT_DST_V4:
4119   case AMDGPU::SI_INDIRECT_DST_V8:
4120   case AMDGPU::SI_INDIRECT_DST_V16:
4121   case AMDGPU::SI_INDIRECT_DST_V32:
4122     return emitIndirectDst(MI, *BB, *getSubtarget());
4123   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4124   case AMDGPU::SI_KILL_I1_PSEUDO:
4125     return splitKillBlock(MI, BB);
4126   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4127     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4128     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4129     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4130 
4131     Register Dst = MI.getOperand(0).getReg();
4132     Register Src0 = MI.getOperand(1).getReg();
4133     Register Src1 = MI.getOperand(2).getReg();
4134     const DebugLoc &DL = MI.getDebugLoc();
4135     Register SrcCond = MI.getOperand(3).getReg();
4136 
4137     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4138     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4139     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4140     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4141 
4142     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4143       .addReg(SrcCond);
4144     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4145       .addImm(0)
4146       .addReg(Src0, 0, AMDGPU::sub0)
4147       .addImm(0)
4148       .addReg(Src1, 0, AMDGPU::sub0)
4149       .addReg(SrcCondCopy);
4150     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4151       .addImm(0)
4152       .addReg(Src0, 0, AMDGPU::sub1)
4153       .addImm(0)
4154       .addReg(Src1, 0, AMDGPU::sub1)
4155       .addReg(SrcCondCopy);
4156 
4157     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4158       .addReg(DstLo)
4159       .addImm(AMDGPU::sub0)
4160       .addReg(DstHi)
4161       .addImm(AMDGPU::sub1);
4162     MI.eraseFromParent();
4163     return BB;
4164   }
4165   case AMDGPU::SI_BR_UNDEF: {
4166     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4167     const DebugLoc &DL = MI.getDebugLoc();
4168     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4169                            .add(MI.getOperand(0));
4170     Br->getOperand(1).setIsUndef(true); // read undef SCC
4171     MI.eraseFromParent();
4172     return BB;
4173   }
4174   case AMDGPU::ADJCALLSTACKUP:
4175   case AMDGPU::ADJCALLSTACKDOWN: {
4176     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4177     MachineInstrBuilder MIB(*MF, &MI);
4178     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4179        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4180     return BB;
4181   }
4182   case AMDGPU::SI_CALL_ISEL: {
4183     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4184     const DebugLoc &DL = MI.getDebugLoc();
4185 
4186     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4187 
4188     MachineInstrBuilder MIB;
4189     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4190 
4191     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4192       MIB.add(MI.getOperand(I));
4193 
4194     MIB.cloneMemRefs(MI);
4195     MI.eraseFromParent();
4196     return BB;
4197   }
4198   case AMDGPU::V_ADD_CO_U32_e32:
4199   case AMDGPU::V_SUB_CO_U32_e32:
4200   case AMDGPU::V_SUBREV_CO_U32_e32: {
4201     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4202     const DebugLoc &DL = MI.getDebugLoc();
4203     unsigned Opc = MI.getOpcode();
4204 
4205     bool NeedClampOperand = false;
4206     if (TII->pseudoToMCOpcode(Opc) == -1) {
4207       Opc = AMDGPU::getVOPe64(Opc);
4208       NeedClampOperand = true;
4209     }
4210 
4211     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4212     if (TII->isVOP3(*I)) {
4213       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4214       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4215       I.addReg(TRI->getVCC(), RegState::Define);
4216     }
4217     I.add(MI.getOperand(1))
4218      .add(MI.getOperand(2));
4219     if (NeedClampOperand)
4220       I.addImm(0); // clamp bit for e64 encoding
4221 
4222     TII->legalizeOperands(*I);
4223 
4224     MI.eraseFromParent();
4225     return BB;
4226   }
4227   case AMDGPU::DS_GWS_INIT:
4228   case AMDGPU::DS_GWS_SEMA_V:
4229   case AMDGPU::DS_GWS_SEMA_BR:
4230   case AMDGPU::DS_GWS_SEMA_P:
4231   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4232   case AMDGPU::DS_GWS_BARRIER:
4233     // A s_waitcnt 0 is required to be the instruction immediately following.
4234     if (getSubtarget()->hasGWSAutoReplay()) {
4235       bundleInstWithWaitcnt(MI);
4236       return BB;
4237     }
4238 
4239     return emitGWSMemViolTestLoop(MI, BB);
4240   case AMDGPU::S_SETREG_B32: {
4241     // Try to optimize cases that only set the denormal mode or rounding mode.
4242     //
4243     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4244     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4245     // instead.
4246     //
4247     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4248     // allow you to have a no side effect instruction in the output of a
4249     // sideeffecting pattern.
4250     unsigned ID, Offset, Width;
4251     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4252     if (ID != AMDGPU::Hwreg::ID_MODE)
4253       return BB;
4254 
4255     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4256     const unsigned SetMask = WidthMask << Offset;
4257 
4258     if (getSubtarget()->hasDenormModeInst()) {
4259       unsigned SetDenormOp = 0;
4260       unsigned SetRoundOp = 0;
4261 
4262       // The dedicated instructions can only set the whole denorm or round mode
4263       // at once, not a subset of bits in either.
4264       if (SetMask ==
4265           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4266         // If this fully sets both the round and denorm mode, emit the two
4267         // dedicated instructions for these.
4268         SetRoundOp = AMDGPU::S_ROUND_MODE;
4269         SetDenormOp = AMDGPU::S_DENORM_MODE;
4270       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4271         SetRoundOp = AMDGPU::S_ROUND_MODE;
4272       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4273         SetDenormOp = AMDGPU::S_DENORM_MODE;
4274       }
4275 
4276       if (SetRoundOp || SetDenormOp) {
4277         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4278         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4279         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4280           unsigned ImmVal = Def->getOperand(1).getImm();
4281           if (SetRoundOp) {
4282             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4283                 .addImm(ImmVal & 0xf);
4284 
4285             // If we also have the denorm mode, get just the denorm mode bits.
4286             ImmVal >>= 4;
4287           }
4288 
4289           if (SetDenormOp) {
4290             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4291                 .addImm(ImmVal & 0xf);
4292           }
4293 
4294           MI.eraseFromParent();
4295           return BB;
4296         }
4297       }
4298     }
4299 
4300     // If only FP bits are touched, used the no side effects pseudo.
4301     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4302                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4303       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4304 
4305     return BB;
4306   }
4307   default:
4308     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4309   }
4310 }
4311 
4312 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4313   return isTypeLegal(VT.getScalarType());
4314 }
4315 
4316 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4317   // This currently forces unfolding various combinations of fsub into fma with
4318   // free fneg'd operands. As long as we have fast FMA (controlled by
4319   // isFMAFasterThanFMulAndFAdd), we should perform these.
4320 
4321   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4322   // most of these combines appear to be cycle neutral but save on instruction
4323   // count / code size.
4324   return true;
4325 }
4326 
4327 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4328                                          EVT VT) const {
4329   if (!VT.isVector()) {
4330     return MVT::i1;
4331   }
4332   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4333 }
4334 
4335 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4336   // TODO: Should i16 be used always if legal? For now it would force VALU
4337   // shifts.
4338   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4339 }
4340 
4341 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4342   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4343              ? Ty.changeElementSize(16)
4344              : Ty.changeElementSize(32);
4345 }
4346 
4347 // Answering this is somewhat tricky and depends on the specific device which
4348 // have different rates for fma or all f64 operations.
4349 //
4350 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4351 // regardless of which device (although the number of cycles differs between
4352 // devices), so it is always profitable for f64.
4353 //
4354 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4355 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4356 // which we can always do even without fused FP ops since it returns the same
4357 // result as the separate operations and since it is always full
4358 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4359 // however does not support denormals, so we do report fma as faster if we have
4360 // a fast fma device and require denormals.
4361 //
4362 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4363                                                   EVT VT) const {
4364   VT = VT.getScalarType();
4365 
4366   switch (VT.getSimpleVT().SimpleTy) {
4367   case MVT::f32: {
4368     // If mad is not available this depends only on if f32 fma is full rate.
4369     if (!Subtarget->hasMadMacF32Insts())
4370       return Subtarget->hasFastFMAF32();
4371 
4372     // Otherwise f32 mad is always full rate and returns the same result as
4373     // the separate operations so should be preferred over fma.
4374     // However does not support denomals.
4375     if (hasFP32Denormals(MF))
4376       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4377 
4378     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4379     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4380   }
4381   case MVT::f64:
4382     return true;
4383   case MVT::f16:
4384     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4385   default:
4386     break;
4387   }
4388 
4389   return false;
4390 }
4391 
4392 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4393                                    const SDNode *N) const {
4394   // TODO: Check future ftz flag
4395   // v_mad_f32/v_mac_f32 do not support denormals.
4396   EVT VT = N->getValueType(0);
4397   if (VT == MVT::f32)
4398     return Subtarget->hasMadMacF32Insts() &&
4399            !hasFP32Denormals(DAG.getMachineFunction());
4400   if (VT == MVT::f16) {
4401     return Subtarget->hasMadF16() &&
4402            !hasFP64FP16Denormals(DAG.getMachineFunction());
4403   }
4404 
4405   return false;
4406 }
4407 
4408 //===----------------------------------------------------------------------===//
4409 // Custom DAG Lowering Operations
4410 //===----------------------------------------------------------------------===//
4411 
4412 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4413 // wider vector type is legal.
4414 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4415                                              SelectionDAG &DAG) const {
4416   unsigned Opc = Op.getOpcode();
4417   EVT VT = Op.getValueType();
4418   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4419 
4420   SDValue Lo, Hi;
4421   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4422 
4423   SDLoc SL(Op);
4424   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4425                              Op->getFlags());
4426   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4427                              Op->getFlags());
4428 
4429   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4430 }
4431 
4432 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4433 // wider vector type is legal.
4434 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4435                                               SelectionDAG &DAG) const {
4436   unsigned Opc = Op.getOpcode();
4437   EVT VT = Op.getValueType();
4438   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4439 
4440   SDValue Lo0, Hi0;
4441   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4442   SDValue Lo1, Hi1;
4443   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4444 
4445   SDLoc SL(Op);
4446 
4447   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4448                              Op->getFlags());
4449   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4450                              Op->getFlags());
4451 
4452   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4453 }
4454 
4455 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4456                                               SelectionDAG &DAG) const {
4457   unsigned Opc = Op.getOpcode();
4458   EVT VT = Op.getValueType();
4459   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4460 
4461   SDValue Lo0, Hi0;
4462   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4463   SDValue Lo1, Hi1;
4464   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4465   SDValue Lo2, Hi2;
4466   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4467 
4468   SDLoc SL(Op);
4469 
4470   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4471                              Op->getFlags());
4472   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4473                              Op->getFlags());
4474 
4475   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4476 }
4477 
4478 
4479 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4480   switch (Op.getOpcode()) {
4481   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4482   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4483   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4484   case ISD::LOAD: {
4485     SDValue Result = LowerLOAD(Op, DAG);
4486     assert((!Result.getNode() ||
4487             Result.getNode()->getNumValues() == 2) &&
4488            "Load should return a value and a chain");
4489     return Result;
4490   }
4491 
4492   case ISD::FSIN:
4493   case ISD::FCOS:
4494     return LowerTrig(Op, DAG);
4495   case ISD::SELECT: return LowerSELECT(Op, DAG);
4496   case ISD::FDIV: return LowerFDIV(Op, DAG);
4497   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4498   case ISD::STORE: return LowerSTORE(Op, DAG);
4499   case ISD::GlobalAddress: {
4500     MachineFunction &MF = DAG.getMachineFunction();
4501     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4502     return LowerGlobalAddress(MFI, Op, DAG);
4503   }
4504   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4505   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4506   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4507   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4508   case ISD::INSERT_SUBVECTOR:
4509     return lowerINSERT_SUBVECTOR(Op, DAG);
4510   case ISD::INSERT_VECTOR_ELT:
4511     return lowerINSERT_VECTOR_ELT(Op, DAG);
4512   case ISD::EXTRACT_VECTOR_ELT:
4513     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4514   case ISD::VECTOR_SHUFFLE:
4515     return lowerVECTOR_SHUFFLE(Op, DAG);
4516   case ISD::BUILD_VECTOR:
4517     return lowerBUILD_VECTOR(Op, DAG);
4518   case ISD::FP_ROUND:
4519     return lowerFP_ROUND(Op, DAG);
4520   case ISD::TRAP:
4521     return lowerTRAP(Op, DAG);
4522   case ISD::DEBUGTRAP:
4523     return lowerDEBUGTRAP(Op, DAG);
4524   case ISD::FABS:
4525   case ISD::FNEG:
4526   case ISD::FCANONICALIZE:
4527   case ISD::BSWAP:
4528     return splitUnaryVectorOp(Op, DAG);
4529   case ISD::FMINNUM:
4530   case ISD::FMAXNUM:
4531     return lowerFMINNUM_FMAXNUM(Op, DAG);
4532   case ISD::FMA:
4533     return splitTernaryVectorOp(Op, DAG);
4534   case ISD::SHL:
4535   case ISD::SRA:
4536   case ISD::SRL:
4537   case ISD::ADD:
4538   case ISD::SUB:
4539   case ISD::MUL:
4540   case ISD::SMIN:
4541   case ISD::SMAX:
4542   case ISD::UMIN:
4543   case ISD::UMAX:
4544   case ISD::FADD:
4545   case ISD::FMUL:
4546   case ISD::FMINNUM_IEEE:
4547   case ISD::FMAXNUM_IEEE:
4548   case ISD::UADDSAT:
4549   case ISD::USUBSAT:
4550   case ISD::SADDSAT:
4551   case ISD::SSUBSAT:
4552     return splitBinaryVectorOp(Op, DAG);
4553   case ISD::SMULO:
4554   case ISD::UMULO:
4555     return lowerXMULO(Op, DAG);
4556   case ISD::DYNAMIC_STACKALLOC:
4557     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4558   }
4559   return SDValue();
4560 }
4561 
4562 // Used for D16: Casts the result of an instruction into the right vector,
4563 // packs values if loads return unpacked values.
4564 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4565                                        const SDLoc &DL,
4566                                        SelectionDAG &DAG, bool Unpacked) {
4567   if (!LoadVT.isVector())
4568     return Result;
4569 
4570   // Cast back to the original packed type or to a larger type that is a
4571   // multiple of 32 bit for D16. Widening the return type is a required for
4572   // legalization.
4573   EVT FittingLoadVT = LoadVT;
4574   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4575     FittingLoadVT =
4576         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4577                          LoadVT.getVectorNumElements() + 1);
4578   }
4579 
4580   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4581     // Truncate to v2i16/v4i16.
4582     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4583 
4584     // Workaround legalizer not scalarizing truncate after vector op
4585     // legalization but not creating intermediate vector trunc.
4586     SmallVector<SDValue, 4> Elts;
4587     DAG.ExtractVectorElements(Result, Elts);
4588     for (SDValue &Elt : Elts)
4589       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4590 
4591     // Pad illegal v1i16/v3fi6 to v4i16
4592     if ((LoadVT.getVectorNumElements() % 2) == 1)
4593       Elts.push_back(DAG.getUNDEF(MVT::i16));
4594 
4595     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4596 
4597     // Bitcast to original type (v2f16/v4f16).
4598     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4599   }
4600 
4601   // Cast back to the original packed type.
4602   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4603 }
4604 
4605 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4606                                               MemSDNode *M,
4607                                               SelectionDAG &DAG,
4608                                               ArrayRef<SDValue> Ops,
4609                                               bool IsIntrinsic) const {
4610   SDLoc DL(M);
4611 
4612   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4613   EVT LoadVT = M->getValueType(0);
4614 
4615   EVT EquivLoadVT = LoadVT;
4616   if (LoadVT.isVector()) {
4617     if (Unpacked) {
4618       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4619                                      LoadVT.getVectorNumElements());
4620     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4621       // Widen v3f16 to legal type
4622       EquivLoadVT =
4623           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4624                            LoadVT.getVectorNumElements() + 1);
4625     }
4626   }
4627 
4628   // Change from v4f16/v2f16 to EquivLoadVT.
4629   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4630 
4631   SDValue Load
4632     = DAG.getMemIntrinsicNode(
4633       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4634       VTList, Ops, M->getMemoryVT(),
4635       M->getMemOperand());
4636 
4637   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4638 
4639   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4640 }
4641 
4642 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4643                                              SelectionDAG &DAG,
4644                                              ArrayRef<SDValue> Ops) const {
4645   SDLoc DL(M);
4646   EVT LoadVT = M->getValueType(0);
4647   EVT EltType = LoadVT.getScalarType();
4648   EVT IntVT = LoadVT.changeTypeToInteger();
4649 
4650   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4651 
4652   unsigned Opc =
4653       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4654 
4655   if (IsD16) {
4656     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4657   }
4658 
4659   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4660   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4661     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4662 
4663   if (isTypeLegal(LoadVT)) {
4664     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4665                                M->getMemOperand(), DAG);
4666   }
4667 
4668   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4669   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4670   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4671                                         M->getMemOperand(), DAG);
4672   return DAG.getMergeValues(
4673       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4674       DL);
4675 }
4676 
4677 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4678                                   SDNode *N, SelectionDAG &DAG) {
4679   EVT VT = N->getValueType(0);
4680   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4681   unsigned CondCode = CD->getZExtValue();
4682   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4683     return DAG.getUNDEF(VT);
4684 
4685   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4686 
4687   SDValue LHS = N->getOperand(1);
4688   SDValue RHS = N->getOperand(2);
4689 
4690   SDLoc DL(N);
4691 
4692   EVT CmpVT = LHS.getValueType();
4693   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4694     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4695       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4696     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4697     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4698   }
4699 
4700   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4701 
4702   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4703   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4704 
4705   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4706                               DAG.getCondCode(CCOpcode));
4707   if (VT.bitsEq(CCVT))
4708     return SetCC;
4709   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4710 }
4711 
4712 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4713                                   SDNode *N, SelectionDAG &DAG) {
4714   EVT VT = N->getValueType(0);
4715   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4716 
4717   unsigned CondCode = CD->getZExtValue();
4718   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4719     return DAG.getUNDEF(VT);
4720 
4721   SDValue Src0 = N->getOperand(1);
4722   SDValue Src1 = N->getOperand(2);
4723   EVT CmpVT = Src0.getValueType();
4724   SDLoc SL(N);
4725 
4726   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4727     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4728     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4729   }
4730 
4731   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4732   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4733   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4734   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4735   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4736                               Src1, DAG.getCondCode(CCOpcode));
4737   if (VT.bitsEq(CCVT))
4738     return SetCC;
4739   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4740 }
4741 
4742 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4743                                     SelectionDAG &DAG) {
4744   EVT VT = N->getValueType(0);
4745   SDValue Src = N->getOperand(1);
4746   SDLoc SL(N);
4747 
4748   if (Src.getOpcode() == ISD::SETCC) {
4749     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4750     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4751                        Src.getOperand(1), Src.getOperand(2));
4752   }
4753   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4754     // (ballot 0) -> 0
4755     if (Arg->isNullValue())
4756       return DAG.getConstant(0, SL, VT);
4757 
4758     // (ballot 1) -> EXEC/EXEC_LO
4759     if (Arg->isOne()) {
4760       Register Exec;
4761       if (VT.getScalarSizeInBits() == 32)
4762         Exec = AMDGPU::EXEC_LO;
4763       else if (VT.getScalarSizeInBits() == 64)
4764         Exec = AMDGPU::EXEC;
4765       else
4766         return SDValue();
4767 
4768       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4769     }
4770   }
4771 
4772   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4773   // ISD::SETNE)
4774   return DAG.getNode(
4775       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4776       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4777 }
4778 
4779 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4780                                           SmallVectorImpl<SDValue> &Results,
4781                                           SelectionDAG &DAG) const {
4782   switch (N->getOpcode()) {
4783   case ISD::INSERT_VECTOR_ELT: {
4784     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4785       Results.push_back(Res);
4786     return;
4787   }
4788   case ISD::EXTRACT_VECTOR_ELT: {
4789     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4790       Results.push_back(Res);
4791     return;
4792   }
4793   case ISD::INTRINSIC_WO_CHAIN: {
4794     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4795     switch (IID) {
4796     case Intrinsic::amdgcn_cvt_pkrtz: {
4797       SDValue Src0 = N->getOperand(1);
4798       SDValue Src1 = N->getOperand(2);
4799       SDLoc SL(N);
4800       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4801                                 Src0, Src1);
4802       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4803       return;
4804     }
4805     case Intrinsic::amdgcn_cvt_pknorm_i16:
4806     case Intrinsic::amdgcn_cvt_pknorm_u16:
4807     case Intrinsic::amdgcn_cvt_pk_i16:
4808     case Intrinsic::amdgcn_cvt_pk_u16: {
4809       SDValue Src0 = N->getOperand(1);
4810       SDValue Src1 = N->getOperand(2);
4811       SDLoc SL(N);
4812       unsigned Opcode;
4813 
4814       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4815         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4816       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4817         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4818       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4819         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4820       else
4821         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4822 
4823       EVT VT = N->getValueType(0);
4824       if (isTypeLegal(VT))
4825         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4826       else {
4827         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4828         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4829       }
4830       return;
4831     }
4832     }
4833     break;
4834   }
4835   case ISD::INTRINSIC_W_CHAIN: {
4836     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4837       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4838         // FIXME: Hacky
4839         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4840           Results.push_back(Res.getOperand(I));
4841         }
4842       } else {
4843         Results.push_back(Res);
4844         Results.push_back(Res.getValue(1));
4845       }
4846       return;
4847     }
4848 
4849     break;
4850   }
4851   case ISD::SELECT: {
4852     SDLoc SL(N);
4853     EVT VT = N->getValueType(0);
4854     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4855     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4856     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4857 
4858     EVT SelectVT = NewVT;
4859     if (NewVT.bitsLT(MVT::i32)) {
4860       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4861       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4862       SelectVT = MVT::i32;
4863     }
4864 
4865     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4866                                     N->getOperand(0), LHS, RHS);
4867 
4868     if (NewVT != SelectVT)
4869       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4870     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4871     return;
4872   }
4873   case ISD::FNEG: {
4874     if (N->getValueType(0) != MVT::v2f16)
4875       break;
4876 
4877     SDLoc SL(N);
4878     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4879 
4880     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4881                              BC,
4882                              DAG.getConstant(0x80008000, SL, MVT::i32));
4883     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4884     return;
4885   }
4886   case ISD::FABS: {
4887     if (N->getValueType(0) != MVT::v2f16)
4888       break;
4889 
4890     SDLoc SL(N);
4891     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4892 
4893     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4894                              BC,
4895                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4896     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4897     return;
4898   }
4899   default:
4900     break;
4901   }
4902 }
4903 
4904 /// Helper function for LowerBRCOND
4905 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4906 
4907   SDNode *Parent = Value.getNode();
4908   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4909        I != E; ++I) {
4910 
4911     if (I.getUse().get() != Value)
4912       continue;
4913 
4914     if (I->getOpcode() == Opcode)
4915       return *I;
4916   }
4917   return nullptr;
4918 }
4919 
4920 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4921   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4922     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4923     case Intrinsic::amdgcn_if:
4924       return AMDGPUISD::IF;
4925     case Intrinsic::amdgcn_else:
4926       return AMDGPUISD::ELSE;
4927     case Intrinsic::amdgcn_loop:
4928       return AMDGPUISD::LOOP;
4929     case Intrinsic::amdgcn_end_cf:
4930       llvm_unreachable("should not occur");
4931     default:
4932       return 0;
4933     }
4934   }
4935 
4936   // break, if_break, else_break are all only used as inputs to loop, not
4937   // directly as branch conditions.
4938   return 0;
4939 }
4940 
4941 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4942   const Triple &TT = getTargetMachine().getTargetTriple();
4943   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4944           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4945          AMDGPU::shouldEmitConstantsToTextSection(TT);
4946 }
4947 
4948 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4949   // FIXME: Either avoid relying on address space here or change the default
4950   // address space for functions to avoid the explicit check.
4951   return (GV->getValueType()->isFunctionTy() ||
4952           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4953          !shouldEmitFixup(GV) &&
4954          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4955 }
4956 
4957 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4958   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4959 }
4960 
4961 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4962   if (!GV->hasExternalLinkage())
4963     return true;
4964 
4965   const auto OS = getTargetMachine().getTargetTriple().getOS();
4966   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4967 }
4968 
4969 /// This transforms the control flow intrinsics to get the branch destination as
4970 /// last parameter, also switches branch target with BR if the need arise
4971 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4972                                       SelectionDAG &DAG) const {
4973   SDLoc DL(BRCOND);
4974 
4975   SDNode *Intr = BRCOND.getOperand(1).getNode();
4976   SDValue Target = BRCOND.getOperand(2);
4977   SDNode *BR = nullptr;
4978   SDNode *SetCC = nullptr;
4979 
4980   if (Intr->getOpcode() == ISD::SETCC) {
4981     // As long as we negate the condition everything is fine
4982     SetCC = Intr;
4983     Intr = SetCC->getOperand(0).getNode();
4984 
4985   } else {
4986     // Get the target from BR if we don't negate the condition
4987     BR = findUser(BRCOND, ISD::BR);
4988     assert(BR && "brcond missing unconditional branch user");
4989     Target = BR->getOperand(1);
4990   }
4991 
4992   unsigned CFNode = isCFIntrinsic(Intr);
4993   if (CFNode == 0) {
4994     // This is a uniform branch so we don't need to legalize.
4995     return BRCOND;
4996   }
4997 
4998   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4999                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5000 
5001   assert(!SetCC ||
5002         (SetCC->getConstantOperandVal(1) == 1 &&
5003          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5004                                                              ISD::SETNE));
5005 
5006   // operands of the new intrinsic call
5007   SmallVector<SDValue, 4> Ops;
5008   if (HaveChain)
5009     Ops.push_back(BRCOND.getOperand(0));
5010 
5011   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5012   Ops.push_back(Target);
5013 
5014   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5015 
5016   // build the new intrinsic call
5017   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5018 
5019   if (!HaveChain) {
5020     SDValue Ops[] =  {
5021       SDValue(Result, 0),
5022       BRCOND.getOperand(0)
5023     };
5024 
5025     Result = DAG.getMergeValues(Ops, DL).getNode();
5026   }
5027 
5028   if (BR) {
5029     // Give the branch instruction our target
5030     SDValue Ops[] = {
5031       BR->getOperand(0),
5032       BRCOND.getOperand(2)
5033     };
5034     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5035     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5036   }
5037 
5038   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5039 
5040   // Copy the intrinsic results to registers
5041   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5042     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5043     if (!CopyToReg)
5044       continue;
5045 
5046     Chain = DAG.getCopyToReg(
5047       Chain, DL,
5048       CopyToReg->getOperand(1),
5049       SDValue(Result, i - 1),
5050       SDValue());
5051 
5052     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5053   }
5054 
5055   // Remove the old intrinsic from the chain
5056   DAG.ReplaceAllUsesOfValueWith(
5057     SDValue(Intr, Intr->getNumValues() - 1),
5058     Intr->getOperand(0));
5059 
5060   return Chain;
5061 }
5062 
5063 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5064                                           SelectionDAG &DAG) const {
5065   MVT VT = Op.getSimpleValueType();
5066   SDLoc DL(Op);
5067   // Checking the depth
5068   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5069     return DAG.getConstant(0, DL, VT);
5070 
5071   MachineFunction &MF = DAG.getMachineFunction();
5072   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5073   // Check for kernel and shader functions
5074   if (Info->isEntryFunction())
5075     return DAG.getConstant(0, DL, VT);
5076 
5077   MachineFrameInfo &MFI = MF.getFrameInfo();
5078   // There is a call to @llvm.returnaddress in this function
5079   MFI.setReturnAddressIsTaken(true);
5080 
5081   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5082   // Get the return address reg and mark it as an implicit live-in
5083   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5084 
5085   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5086 }
5087 
5088 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5089                                             SDValue Op,
5090                                             const SDLoc &DL,
5091                                             EVT VT) const {
5092   return Op.getValueType().bitsLE(VT) ?
5093       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5094     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5095                 DAG.getTargetConstant(0, DL, MVT::i32));
5096 }
5097 
5098 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5099   assert(Op.getValueType() == MVT::f16 &&
5100          "Do not know how to custom lower FP_ROUND for non-f16 type");
5101 
5102   SDValue Src = Op.getOperand(0);
5103   EVT SrcVT = Src.getValueType();
5104   if (SrcVT != MVT::f64)
5105     return Op;
5106 
5107   SDLoc DL(Op);
5108 
5109   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5110   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5111   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5112 }
5113 
5114 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5115                                                SelectionDAG &DAG) const {
5116   EVT VT = Op.getValueType();
5117   const MachineFunction &MF = DAG.getMachineFunction();
5118   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5119   bool IsIEEEMode = Info->getMode().IEEE;
5120 
5121   // FIXME: Assert during selection that this is only selected for
5122   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5123   // mode functions, but this happens to be OK since it's only done in cases
5124   // where there is known no sNaN.
5125   if (IsIEEEMode)
5126     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5127 
5128   if (VT == MVT::v4f16)
5129     return splitBinaryVectorOp(Op, DAG);
5130   return Op;
5131 }
5132 
5133 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5134   EVT VT = Op.getValueType();
5135   SDLoc SL(Op);
5136   SDValue LHS = Op.getOperand(0);
5137   SDValue RHS = Op.getOperand(1);
5138   bool isSigned = Op.getOpcode() == ISD::SMULO;
5139 
5140   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5141     const APInt &C = RHSC->getAPIntValue();
5142     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5143     if (C.isPowerOf2()) {
5144       // smulo(x, signed_min) is same as umulo(x, signed_min).
5145       bool UseArithShift = isSigned && !C.isMinSignedValue();
5146       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5147       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5148       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5149           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5150                       SL, VT, Result, ShiftAmt),
5151           LHS, ISD::SETNE);
5152       return DAG.getMergeValues({ Result, Overflow }, SL);
5153     }
5154   }
5155 
5156   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5157   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5158                             SL, VT, LHS, RHS);
5159 
5160   SDValue Sign = isSigned
5161     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5162                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5163     : DAG.getConstant(0, SL, VT);
5164   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5165 
5166   return DAG.getMergeValues({ Result, Overflow }, SL);
5167 }
5168 
5169 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5170   SDLoc SL(Op);
5171   SDValue Chain = Op.getOperand(0);
5172 
5173   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5174       !Subtarget->isTrapHandlerEnabled())
5175     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5176 
5177   MachineFunction &MF = DAG.getMachineFunction();
5178   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5179   Register UserSGPR = Info->getQueuePtrUserSGPR();
5180   assert(UserSGPR != AMDGPU::NoRegister);
5181   SDValue QueuePtr = CreateLiveInRegister(
5182     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5183   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5184   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5185                                    QueuePtr, SDValue());
5186   SDValue Ops[] = {
5187     ToReg,
5188     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5189     SGPR01,
5190     ToReg.getValue(1)
5191   };
5192   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5193 }
5194 
5195 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5196   SDLoc SL(Op);
5197   SDValue Chain = Op.getOperand(0);
5198   MachineFunction &MF = DAG.getMachineFunction();
5199 
5200   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5201       !Subtarget->isTrapHandlerEnabled()) {
5202     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5203                                      "debugtrap handler not supported",
5204                                      Op.getDebugLoc(),
5205                                      DS_Warning);
5206     LLVMContext &Ctx = MF.getFunction().getContext();
5207     Ctx.diagnose(NoTrap);
5208     return Chain;
5209   }
5210 
5211   SDValue Ops[] = {
5212     Chain,
5213     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5214   };
5215   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5216 }
5217 
5218 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5219                                              SelectionDAG &DAG) const {
5220   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5221   if (Subtarget->hasApertureRegs()) {
5222     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5223         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5224         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5225     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5226         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5227         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5228     unsigned Encoding =
5229         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5230         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5231         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5232 
5233     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5234     SDValue ApertureReg = SDValue(
5235         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5236     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5237     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5238   }
5239 
5240   MachineFunction &MF = DAG.getMachineFunction();
5241   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5242   Register UserSGPR = Info->getQueuePtrUserSGPR();
5243   assert(UserSGPR != AMDGPU::NoRegister);
5244 
5245   SDValue QueuePtr = CreateLiveInRegister(
5246     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5247 
5248   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5249   // private_segment_aperture_base_hi.
5250   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5251 
5252   SDValue Ptr =
5253       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5254 
5255   // TODO: Use custom target PseudoSourceValue.
5256   // TODO: We should use the value from the IR intrinsic call, but it might not
5257   // be available and how do we get it?
5258   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5259   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5260                      commonAlignment(Align(64), StructOffset),
5261                      MachineMemOperand::MODereferenceable |
5262                          MachineMemOperand::MOInvariant);
5263 }
5264 
5265 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5266                                              SelectionDAG &DAG) const {
5267   SDLoc SL(Op);
5268   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5269 
5270   SDValue Src = ASC->getOperand(0);
5271   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5272 
5273   const AMDGPUTargetMachine &TM =
5274     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5275 
5276   // flat -> local/private
5277   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5278     unsigned DestAS = ASC->getDestAddressSpace();
5279 
5280     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5281         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5282       unsigned NullVal = TM.getNullPointerValue(DestAS);
5283       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5284       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5285       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5286 
5287       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5288                          NonNull, Ptr, SegmentNullPtr);
5289     }
5290   }
5291 
5292   // local/private -> flat
5293   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5294     unsigned SrcAS = ASC->getSrcAddressSpace();
5295 
5296     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5297         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5298       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5299       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5300 
5301       SDValue NonNull
5302         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5303 
5304       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5305       SDValue CvtPtr
5306         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5307 
5308       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5309                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5310                          FlatNullPtr);
5311     }
5312   }
5313 
5314   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5315       Src.getValueType() == MVT::i64)
5316     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5317 
5318   // global <-> flat are no-ops and never emitted.
5319 
5320   const MachineFunction &MF = DAG.getMachineFunction();
5321   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5322     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5323   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5324 
5325   return DAG.getUNDEF(ASC->getValueType(0));
5326 }
5327 
5328 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5329 // the small vector and inserting them into the big vector. That is better than
5330 // the default expansion of doing it via a stack slot. Even though the use of
5331 // the stack slot would be optimized away afterwards, the stack slot itself
5332 // remains.
5333 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5334                                                 SelectionDAG &DAG) const {
5335   SDValue Vec = Op.getOperand(0);
5336   SDValue Ins = Op.getOperand(1);
5337   SDValue Idx = Op.getOperand(2);
5338   EVT VecVT = Vec.getValueType();
5339   EVT InsVT = Ins.getValueType();
5340   EVT EltVT = VecVT.getVectorElementType();
5341   unsigned InsNumElts = InsVT.getVectorNumElements();
5342   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5343   SDLoc SL(Op);
5344 
5345   for (unsigned I = 0; I != InsNumElts; ++I) {
5346     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5347                               DAG.getConstant(I, SL, MVT::i32));
5348     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5349                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5350   }
5351   return Vec;
5352 }
5353 
5354 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5355                                                  SelectionDAG &DAG) const {
5356   SDValue Vec = Op.getOperand(0);
5357   SDValue InsVal = Op.getOperand(1);
5358   SDValue Idx = Op.getOperand(2);
5359   EVT VecVT = Vec.getValueType();
5360   EVT EltVT = VecVT.getVectorElementType();
5361   unsigned VecSize = VecVT.getSizeInBits();
5362   unsigned EltSize = EltVT.getSizeInBits();
5363 
5364 
5365   assert(VecSize <= 64);
5366 
5367   unsigned NumElts = VecVT.getVectorNumElements();
5368   SDLoc SL(Op);
5369   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5370 
5371   if (NumElts == 4 && EltSize == 16 && KIdx) {
5372     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5373 
5374     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5375                                  DAG.getConstant(0, SL, MVT::i32));
5376     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5377                                  DAG.getConstant(1, SL, MVT::i32));
5378 
5379     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5380     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5381 
5382     unsigned Idx = KIdx->getZExtValue();
5383     bool InsertLo = Idx < 2;
5384     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5385       InsertLo ? LoVec : HiVec,
5386       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5387       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5388 
5389     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5390 
5391     SDValue Concat = InsertLo ?
5392       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5393       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5394 
5395     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5396   }
5397 
5398   if (isa<ConstantSDNode>(Idx))
5399     return SDValue();
5400 
5401   MVT IntVT = MVT::getIntegerVT(VecSize);
5402 
5403   // Avoid stack access for dynamic indexing.
5404   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5405 
5406   // Create a congruent vector with the target value in each element so that
5407   // the required element can be masked and ORed into the target vector.
5408   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5409                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5410 
5411   assert(isPowerOf2_32(EltSize));
5412   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5413 
5414   // Convert vector index to bit-index.
5415   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5416 
5417   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5418   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5419                             DAG.getConstant(0xffff, SL, IntVT),
5420                             ScaledIdx);
5421 
5422   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5423   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5424                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5425 
5426   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5427   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5428 }
5429 
5430 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5431                                                   SelectionDAG &DAG) const {
5432   SDLoc SL(Op);
5433 
5434   EVT ResultVT = Op.getValueType();
5435   SDValue Vec = Op.getOperand(0);
5436   SDValue Idx = Op.getOperand(1);
5437   EVT VecVT = Vec.getValueType();
5438   unsigned VecSize = VecVT.getSizeInBits();
5439   EVT EltVT = VecVT.getVectorElementType();
5440   assert(VecSize <= 64);
5441 
5442   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5443 
5444   // Make sure we do any optimizations that will make it easier to fold
5445   // source modifiers before obscuring it with bit operations.
5446 
5447   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5448   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5449     return Combined;
5450 
5451   unsigned EltSize = EltVT.getSizeInBits();
5452   assert(isPowerOf2_32(EltSize));
5453 
5454   MVT IntVT = MVT::getIntegerVT(VecSize);
5455   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5456 
5457   // Convert vector index to bit-index (* EltSize)
5458   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5459 
5460   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5461   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5462 
5463   if (ResultVT == MVT::f16) {
5464     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5465     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5466   }
5467 
5468   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5469 }
5470 
5471 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5472   assert(Elt % 2 == 0);
5473   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5474 }
5475 
5476 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5477                                               SelectionDAG &DAG) const {
5478   SDLoc SL(Op);
5479   EVT ResultVT = Op.getValueType();
5480   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5481 
5482   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5483   EVT EltVT = PackVT.getVectorElementType();
5484   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5485 
5486   // vector_shuffle <0,1,6,7> lhs, rhs
5487   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5488   //
5489   // vector_shuffle <6,7,2,3> lhs, rhs
5490   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5491   //
5492   // vector_shuffle <6,7,0,1> lhs, rhs
5493   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5494 
5495   // Avoid scalarizing when both halves are reading from consecutive elements.
5496   SmallVector<SDValue, 4> Pieces;
5497   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5498     if (elementPairIsContiguous(SVN->getMask(), I)) {
5499       const int Idx = SVN->getMaskElt(I);
5500       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5501       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5502       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5503                                     PackVT, SVN->getOperand(VecIdx),
5504                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5505       Pieces.push_back(SubVec);
5506     } else {
5507       const int Idx0 = SVN->getMaskElt(I);
5508       const int Idx1 = SVN->getMaskElt(I + 1);
5509       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5510       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5511       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5512       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5513 
5514       SDValue Vec0 = SVN->getOperand(VecIdx0);
5515       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5516                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5517 
5518       SDValue Vec1 = SVN->getOperand(VecIdx1);
5519       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5520                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5521       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5522     }
5523   }
5524 
5525   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5526 }
5527 
5528 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5529                                             SelectionDAG &DAG) const {
5530   SDLoc SL(Op);
5531   EVT VT = Op.getValueType();
5532 
5533   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5534     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5535 
5536     // Turn into pair of packed build_vectors.
5537     // TODO: Special case for constants that can be materialized with s_mov_b64.
5538     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5539                                     { Op.getOperand(0), Op.getOperand(1) });
5540     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5541                                     { Op.getOperand(2), Op.getOperand(3) });
5542 
5543     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5544     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5545 
5546     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5547     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5548   }
5549 
5550   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5551   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5552 
5553   SDValue Lo = Op.getOperand(0);
5554   SDValue Hi = Op.getOperand(1);
5555 
5556   // Avoid adding defined bits with the zero_extend.
5557   if (Hi.isUndef()) {
5558     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5559     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5560     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5561   }
5562 
5563   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5564   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5565 
5566   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5567                               DAG.getConstant(16, SL, MVT::i32));
5568   if (Lo.isUndef())
5569     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5570 
5571   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5572   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5573 
5574   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5575   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5576 }
5577 
5578 bool
5579 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5580   // We can fold offsets for anything that doesn't require a GOT relocation.
5581   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5582           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5583           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5584          !shouldEmitGOTReloc(GA->getGlobal());
5585 }
5586 
5587 static SDValue
5588 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5589                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5590                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5591   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5592   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5593   // lowered to the following code sequence:
5594   //
5595   // For constant address space:
5596   //   s_getpc_b64 s[0:1]
5597   //   s_add_u32 s0, s0, $symbol
5598   //   s_addc_u32 s1, s1, 0
5599   //
5600   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5601   //   a fixup or relocation is emitted to replace $symbol with a literal
5602   //   constant, which is a pc-relative offset from the encoding of the $symbol
5603   //   operand to the global variable.
5604   //
5605   // For global address space:
5606   //   s_getpc_b64 s[0:1]
5607   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5608   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5609   //
5610   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5611   //   fixups or relocations are emitted to replace $symbol@*@lo and
5612   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5613   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5614   //   operand to the global variable.
5615   //
5616   // What we want here is an offset from the value returned by s_getpc
5617   // (which is the address of the s_add_u32 instruction) to the global
5618   // variable, but since the encoding of $symbol starts 4 bytes after the start
5619   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5620   // small. This requires us to add 4 to the global variable offset in order to
5621   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5622   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5623   // instruction.
5624   SDValue PtrLo =
5625       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5626   SDValue PtrHi;
5627   if (GAFlags == SIInstrInfo::MO_NONE) {
5628     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5629   } else {
5630     PtrHi =
5631         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5632   }
5633   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5634 }
5635 
5636 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5637                                              SDValue Op,
5638                                              SelectionDAG &DAG) const {
5639   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5640   SDLoc DL(GSD);
5641   EVT PtrVT = Op.getValueType();
5642 
5643   const GlobalValue *GV = GSD->getGlobal();
5644   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5645        shouldUseLDSConstAddress(GV)) ||
5646       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5647       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5648     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5649         GV->hasExternalLinkage()) {
5650       Type *Ty = GV->getValueType();
5651       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5652       // zero-sized type in other languages to declare the dynamic shared
5653       // memory which size is not known at the compile time. They will be
5654       // allocated by the runtime and placed directly after the static
5655       // allocated ones. They all share the same offset.
5656       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5657         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5658         // Adjust alignment for that dynamic shared memory array.
5659         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5660         return SDValue(
5661             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5662       }
5663     }
5664     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5665   }
5666 
5667   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5668     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5669                                             SIInstrInfo::MO_ABS32_LO);
5670     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5671   }
5672 
5673   if (shouldEmitFixup(GV))
5674     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5675   else if (shouldEmitPCReloc(GV))
5676     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5677                                    SIInstrInfo::MO_REL32);
5678 
5679   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5680                                             SIInstrInfo::MO_GOTPCREL32);
5681 
5682   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5683   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5684   const DataLayout &DataLayout = DAG.getDataLayout();
5685   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5686   MachinePointerInfo PtrInfo
5687     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5688 
5689   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5690                      MachineMemOperand::MODereferenceable |
5691                          MachineMemOperand::MOInvariant);
5692 }
5693 
5694 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5695                                    const SDLoc &DL, SDValue V) const {
5696   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5697   // the destination register.
5698   //
5699   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5700   // so we will end up with redundant moves to m0.
5701   //
5702   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5703 
5704   // A Null SDValue creates a glue result.
5705   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5706                                   V, Chain);
5707   return SDValue(M0, 0);
5708 }
5709 
5710 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5711                                                  SDValue Op,
5712                                                  MVT VT,
5713                                                  unsigned Offset) const {
5714   SDLoc SL(Op);
5715   SDValue Param = lowerKernargMemParameter(
5716       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5717   // The local size values will have the hi 16-bits as zero.
5718   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5719                      DAG.getValueType(VT));
5720 }
5721 
5722 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5723                                         EVT VT) {
5724   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5725                                       "non-hsa intrinsic with hsa target",
5726                                       DL.getDebugLoc());
5727   DAG.getContext()->diagnose(BadIntrin);
5728   return DAG.getUNDEF(VT);
5729 }
5730 
5731 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5732                                          EVT VT) {
5733   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5734                                       "intrinsic not supported on subtarget",
5735                                       DL.getDebugLoc());
5736   DAG.getContext()->diagnose(BadIntrin);
5737   return DAG.getUNDEF(VT);
5738 }
5739 
5740 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5741                                     ArrayRef<SDValue> Elts) {
5742   assert(!Elts.empty());
5743   MVT Type;
5744   unsigned NumElts;
5745 
5746   if (Elts.size() == 1) {
5747     Type = MVT::f32;
5748     NumElts = 1;
5749   } else if (Elts.size() == 2) {
5750     Type = MVT::v2f32;
5751     NumElts = 2;
5752   } else if (Elts.size() == 3) {
5753     Type = MVT::v3f32;
5754     NumElts = 3;
5755   } else if (Elts.size() <= 4) {
5756     Type = MVT::v4f32;
5757     NumElts = 4;
5758   } else if (Elts.size() <= 8) {
5759     Type = MVT::v8f32;
5760     NumElts = 8;
5761   } else {
5762     assert(Elts.size() <= 16);
5763     Type = MVT::v16f32;
5764     NumElts = 16;
5765   }
5766 
5767   SmallVector<SDValue, 16> VecElts(NumElts);
5768   for (unsigned i = 0; i < Elts.size(); ++i) {
5769     SDValue Elt = Elts[i];
5770     if (Elt.getValueType() != MVT::f32)
5771       Elt = DAG.getBitcast(MVT::f32, Elt);
5772     VecElts[i] = Elt;
5773   }
5774   for (unsigned i = Elts.size(); i < NumElts; ++i)
5775     VecElts[i] = DAG.getUNDEF(MVT::f32);
5776 
5777   if (NumElts == 1)
5778     return VecElts[0];
5779   return DAG.getBuildVector(Type, DL, VecElts);
5780 }
5781 
5782 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5783                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5784   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5785 
5786   uint64_t Value = CachePolicyConst->getZExtValue();
5787   SDLoc DL(CachePolicy);
5788   if (GLC) {
5789     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5790     Value &= ~(uint64_t)0x1;
5791   }
5792   if (SLC) {
5793     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5794     Value &= ~(uint64_t)0x2;
5795   }
5796   if (DLC) {
5797     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5798     Value &= ~(uint64_t)0x4;
5799   }
5800 
5801   return Value == 0;
5802 }
5803 
5804 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5805                               SDValue Src, int ExtraElts) {
5806   EVT SrcVT = Src.getValueType();
5807 
5808   SmallVector<SDValue, 8> Elts;
5809 
5810   if (SrcVT.isVector())
5811     DAG.ExtractVectorElements(Src, Elts);
5812   else
5813     Elts.push_back(Src);
5814 
5815   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5816   while (ExtraElts--)
5817     Elts.push_back(Undef);
5818 
5819   return DAG.getBuildVector(CastVT, DL, Elts);
5820 }
5821 
5822 // Re-construct the required return value for a image load intrinsic.
5823 // This is more complicated due to the optional use TexFailCtrl which means the required
5824 // return type is an aggregate
5825 static SDValue constructRetValue(SelectionDAG &DAG,
5826                                  MachineSDNode *Result,
5827                                  ArrayRef<EVT> ResultTypes,
5828                                  bool IsTexFail, bool Unpacked, bool IsD16,
5829                                  int DMaskPop, int NumVDataDwords,
5830                                  const SDLoc &DL, LLVMContext &Context) {
5831   // Determine the required return type. This is the same regardless of IsTexFail flag
5832   EVT ReqRetVT = ResultTypes[0];
5833   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5834   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5835     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5836 
5837   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5838     DMaskPop : (DMaskPop + 1) / 2;
5839 
5840   MVT DataDwordVT = NumDataDwords == 1 ?
5841     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5842 
5843   MVT MaskPopVT = MaskPopDwords == 1 ?
5844     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5845 
5846   SDValue Data(Result, 0);
5847   SDValue TexFail;
5848 
5849   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5850     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5851     if (MaskPopVT.isVector()) {
5852       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5853                          SDValue(Result, 0), ZeroIdx);
5854     } else {
5855       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5856                          SDValue(Result, 0), ZeroIdx);
5857     }
5858   }
5859 
5860   if (DataDwordVT.isVector())
5861     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5862                           NumDataDwords - MaskPopDwords);
5863 
5864   if (IsD16)
5865     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5866 
5867   EVT LegalReqRetVT = ReqRetVT;
5868   if (!ReqRetVT.isVector()) {
5869     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5870   } else {
5871     // We need to widen the return vector to a legal type
5872     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5873         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5874       LegalReqRetVT =
5875           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5876                            ReqRetVT.getVectorNumElements() + 1);
5877     }
5878   }
5879   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5880 
5881   if (IsTexFail) {
5882     TexFail =
5883         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5884                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5885 
5886     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5887   }
5888 
5889   if (Result->getNumValues() == 1)
5890     return Data;
5891 
5892   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5893 }
5894 
5895 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5896                          SDValue *LWE, bool &IsTexFail) {
5897   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5898 
5899   uint64_t Value = TexFailCtrlConst->getZExtValue();
5900   if (Value) {
5901     IsTexFail = true;
5902   }
5903 
5904   SDLoc DL(TexFailCtrlConst);
5905   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5906   Value &= ~(uint64_t)0x1;
5907   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5908   Value &= ~(uint64_t)0x2;
5909 
5910   return Value == 0;
5911 }
5912 
5913 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5914                                         MVT PackVectorVT,
5915                                         SmallVectorImpl<SDValue> &PackedAddrs,
5916                                         unsigned DimIdx, unsigned EndIdx,
5917                                         unsigned NumGradients) {
5918   SDLoc DL(Op);
5919   for (unsigned I = DimIdx; I < EndIdx; I++) {
5920     SDValue Addr = Op.getOperand(I);
5921 
5922     // Gradients are packed with undef for each coordinate.
5923     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5924     // 1D: undef,dx/dh; undef,dx/dv
5925     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5926     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5927     if (((I + 1) >= EndIdx) ||
5928         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5929                                          I == DimIdx + NumGradients - 1))) {
5930       if (Addr.getValueType() != MVT::i16)
5931         Addr = DAG.getBitcast(MVT::i16, Addr);
5932       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5933     } else {
5934       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5935       I++;
5936     }
5937     Addr = DAG.getBitcast(MVT::f32, Addr);
5938     PackedAddrs.push_back(Addr);
5939   }
5940 }
5941 
5942 SDValue SITargetLowering::lowerImage(SDValue Op,
5943                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5944                                      SelectionDAG &DAG, bool WithChain) const {
5945   SDLoc DL(Op);
5946   MachineFunction &MF = DAG.getMachineFunction();
5947   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5948   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5949       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5950   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5951   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5952       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5953   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5954       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5955   unsigned IntrOpcode = Intr->BaseOpcode;
5956   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5957 
5958   SmallVector<EVT, 3> ResultTypes(Op->values());
5959   SmallVector<EVT, 3> OrigResultTypes(Op->values());
5960   bool IsD16 = false;
5961   bool IsG16 = false;
5962   bool IsA16 = false;
5963   SDValue VData;
5964   int NumVDataDwords;
5965   bool AdjustRetType = false;
5966 
5967   // Offset of intrinsic arguments
5968   const unsigned ArgOffset = WithChain ? 2 : 1;
5969 
5970   unsigned DMask;
5971   unsigned DMaskLanes = 0;
5972 
5973   if (BaseOpcode->Atomic) {
5974     VData = Op.getOperand(2);
5975 
5976     bool Is64Bit = VData.getValueType() == MVT::i64;
5977     if (BaseOpcode->AtomicX2) {
5978       SDValue VData2 = Op.getOperand(3);
5979       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5980                                  {VData, VData2});
5981       if (Is64Bit)
5982         VData = DAG.getBitcast(MVT::v4i32, VData);
5983 
5984       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5985       DMask = Is64Bit ? 0xf : 0x3;
5986       NumVDataDwords = Is64Bit ? 4 : 2;
5987     } else {
5988       DMask = Is64Bit ? 0x3 : 0x1;
5989       NumVDataDwords = Is64Bit ? 2 : 1;
5990     }
5991   } else {
5992     auto *DMaskConst =
5993         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
5994     DMask = DMaskConst->getZExtValue();
5995     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5996 
5997     if (BaseOpcode->Store) {
5998       VData = Op.getOperand(2);
5999 
6000       MVT StoreVT = VData.getSimpleValueType();
6001       if (StoreVT.getScalarType() == MVT::f16) {
6002         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6003           return Op; // D16 is unsupported for this instruction
6004 
6005         IsD16 = true;
6006         VData = handleD16VData(VData, DAG, true);
6007       }
6008 
6009       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6010     } else {
6011       // Work out the num dwords based on the dmask popcount and underlying type
6012       // and whether packing is supported.
6013       MVT LoadVT = ResultTypes[0].getSimpleVT();
6014       if (LoadVT.getScalarType() == MVT::f16) {
6015         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6016           return Op; // D16 is unsupported for this instruction
6017 
6018         IsD16 = true;
6019       }
6020 
6021       // Confirm that the return type is large enough for the dmask specified
6022       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6023           (!LoadVT.isVector() && DMaskLanes > 1))
6024           return Op;
6025 
6026       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6027       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6028       // instructions.
6029       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6030           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6031         NumVDataDwords = (DMaskLanes + 1) / 2;
6032       else
6033         NumVDataDwords = DMaskLanes;
6034 
6035       AdjustRetType = true;
6036     }
6037   }
6038 
6039   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6040   SmallVector<SDValue, 4> VAddrs;
6041 
6042   // Optimize _L to _LZ when _L is zero
6043   if (LZMappingInfo) {
6044     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6045             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6046       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6047         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6048         VAddrEnd--;                      // remove 'lod'
6049       }
6050     }
6051   }
6052 
6053   // Optimize _mip away, when 'lod' is zero
6054   if (MIPMappingInfo) {
6055     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6056             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6057       if (ConstantLod->isNullValue()) {
6058         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6059         VAddrEnd--;                           // remove 'mip'
6060       }
6061     }
6062   }
6063 
6064   // Push back extra arguments.
6065   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6066     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6067 
6068   // Check for 16 bit addresses or derivatives and pack if true.
6069   MVT VAddrVT =
6070       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6071   MVT VAddrScalarVT = VAddrVT.getScalarType();
6072   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6073   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6074 
6075   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6076   VAddrScalarVT = VAddrVT.getScalarType();
6077   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6078   if (IsA16 || IsG16) {
6079     if (IsA16) {
6080       if (!ST->hasA16()) {
6081         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6082                              "support 16 bit addresses\n");
6083         return Op;
6084       }
6085       if (!IsG16) {
6086         LLVM_DEBUG(
6087             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6088                       "need 16 bit derivatives but got 32 bit derivatives\n");
6089         return Op;
6090       }
6091     } else if (!ST->hasG16()) {
6092       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6093                            "support 16 bit derivatives\n");
6094       return Op;
6095     }
6096 
6097     if (BaseOpcode->Gradients && !IsA16) {
6098       if (!ST->hasG16()) {
6099         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6100                              "support 16 bit derivatives\n");
6101         return Op;
6102       }
6103       // Activate g16
6104       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6105           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6106       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6107     }
6108 
6109     // Don't compress addresses for G16
6110     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6111     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6112                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6113                                 Intr->NumGradients);
6114 
6115     if (!IsA16) {
6116       // Add uncompressed address
6117       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6118         VAddrs.push_back(Op.getOperand(I));
6119     }
6120   } else {
6121     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6122       VAddrs.push_back(Op.getOperand(I));
6123   }
6124 
6125   // If the register allocator cannot place the address registers contiguously
6126   // without introducing moves, then using the non-sequential address encoding
6127   // is always preferable, since it saves VALU instructions and is usually a
6128   // wash in terms of code size or even better.
6129   //
6130   // However, we currently have no way of hinting to the register allocator that
6131   // MIMG addresses should be placed contiguously when it is possible to do so,
6132   // so force non-NSA for the common 2-address case as a heuristic.
6133   //
6134   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6135   // allocation when possible.
6136   bool UseNSA =
6137       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6138   SDValue VAddr;
6139   if (!UseNSA)
6140     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6141 
6142   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6143   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6144   SDValue Unorm;
6145   if (!BaseOpcode->Sampler) {
6146     Unorm = True;
6147   } else {
6148     auto UnormConst =
6149         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6150 
6151     Unorm = UnormConst->getZExtValue() ? True : False;
6152   }
6153 
6154   SDValue TFE;
6155   SDValue LWE;
6156   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6157   bool IsTexFail = false;
6158   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6159     return Op;
6160 
6161   if (IsTexFail) {
6162     if (!DMaskLanes) {
6163       // Expecting to get an error flag since TFC is on - and dmask is 0
6164       // Force dmask to be at least 1 otherwise the instruction will fail
6165       DMask = 0x1;
6166       DMaskLanes = 1;
6167       NumVDataDwords = 1;
6168     }
6169     NumVDataDwords += 1;
6170     AdjustRetType = true;
6171   }
6172 
6173   // Has something earlier tagged that the return type needs adjusting
6174   // This happens if the instruction is a load or has set TexFailCtrl flags
6175   if (AdjustRetType) {
6176     // NumVDataDwords reflects the true number of dwords required in the return type
6177     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6178       // This is a no-op load. This can be eliminated
6179       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6180       if (isa<MemSDNode>(Op))
6181         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6182       return Undef;
6183     }
6184 
6185     EVT NewVT = NumVDataDwords > 1 ?
6186                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6187                 : MVT::i32;
6188 
6189     ResultTypes[0] = NewVT;
6190     if (ResultTypes.size() == 3) {
6191       // Original result was aggregate type used for TexFailCtrl results
6192       // The actual instruction returns as a vector type which has now been
6193       // created. Remove the aggregate result.
6194       ResultTypes.erase(&ResultTypes[1]);
6195     }
6196   }
6197 
6198   SDValue GLC;
6199   SDValue SLC;
6200   SDValue DLC;
6201   if (BaseOpcode->Atomic) {
6202     GLC = True; // TODO no-return optimization
6203     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6204                           DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr))
6205       return Op;
6206   } else {
6207     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6208                           DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr))
6209       return Op;
6210   }
6211 
6212   SmallVector<SDValue, 26> Ops;
6213   if (BaseOpcode->Store || BaseOpcode->Atomic)
6214     Ops.push_back(VData); // vdata
6215   if (UseNSA) {
6216     for (const SDValue &Addr : VAddrs)
6217       Ops.push_back(Addr);
6218   } else {
6219     Ops.push_back(VAddr);
6220   }
6221   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6222   if (BaseOpcode->Sampler)
6223     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6224   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6225   if (IsGFX10Plus)
6226     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6227   Ops.push_back(Unorm);
6228   if (IsGFX10Plus)
6229     Ops.push_back(DLC);
6230   Ops.push_back(GLC);
6231   Ops.push_back(SLC);
6232   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6233                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6234   if (IsGFX10Plus)
6235     Ops.push_back(IsA16 ? True : False);
6236   Ops.push_back(TFE);
6237   Ops.push_back(LWE);
6238   if (!IsGFX10Plus)
6239     Ops.push_back(DimInfo->DA ? True : False);
6240   if (BaseOpcode->HasD16)
6241     Ops.push_back(IsD16 ? True : False);
6242   if (isa<MemSDNode>(Op))
6243     Ops.push_back(Op.getOperand(0)); // chain
6244 
6245   int NumVAddrDwords =
6246       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6247   int Opcode = -1;
6248 
6249   if (IsGFX10Plus) {
6250     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6251                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6252                                           : AMDGPU::MIMGEncGfx10Default,
6253                                    NumVDataDwords, NumVAddrDwords);
6254   } else {
6255     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6256       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6257                                      NumVDataDwords, NumVAddrDwords);
6258     if (Opcode == -1)
6259       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6260                                      NumVDataDwords, NumVAddrDwords);
6261   }
6262   assert(Opcode != -1);
6263 
6264   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6265   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6266     MachineMemOperand *MemRef = MemOp->getMemOperand();
6267     DAG.setNodeMemRefs(NewNode, {MemRef});
6268   }
6269 
6270   if (BaseOpcode->AtomicX2) {
6271     SmallVector<SDValue, 1> Elt;
6272     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6273     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6274   } else if (!BaseOpcode->Store) {
6275     return constructRetValue(DAG, NewNode,
6276                              OrigResultTypes, IsTexFail,
6277                              Subtarget->hasUnpackedD16VMem(), IsD16,
6278                              DMaskLanes, NumVDataDwords, DL,
6279                              *DAG.getContext());
6280   }
6281 
6282   return SDValue(NewNode, 0);
6283 }
6284 
6285 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6286                                        SDValue Offset, SDValue CachePolicy,
6287                                        SelectionDAG &DAG) const {
6288   MachineFunction &MF = DAG.getMachineFunction();
6289 
6290   const DataLayout &DataLayout = DAG.getDataLayout();
6291   Align Alignment =
6292       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6293 
6294   MachineMemOperand *MMO = MF.getMachineMemOperand(
6295       MachinePointerInfo(),
6296       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6297           MachineMemOperand::MOInvariant,
6298       VT.getStoreSize(), Alignment);
6299 
6300   if (!Offset->isDivergent()) {
6301     SDValue Ops[] = {
6302         Rsrc,
6303         Offset, // Offset
6304         CachePolicy
6305     };
6306 
6307     // Widen vec3 load to vec4.
6308     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6309       EVT WidenedVT =
6310           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6311       auto WidenedOp = DAG.getMemIntrinsicNode(
6312           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6313           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6314       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6315                                    DAG.getVectorIdxConstant(0, DL));
6316       return Subvector;
6317     }
6318 
6319     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6320                                    DAG.getVTList(VT), Ops, VT, MMO);
6321   }
6322 
6323   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6324   // assume that the buffer is unswizzled.
6325   SmallVector<SDValue, 4> Loads;
6326   unsigned NumLoads = 1;
6327   MVT LoadVT = VT.getSimpleVT();
6328   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6329   assert((LoadVT.getScalarType() == MVT::i32 ||
6330           LoadVT.getScalarType() == MVT::f32));
6331 
6332   if (NumElts == 8 || NumElts == 16) {
6333     NumLoads = NumElts / 4;
6334     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6335   }
6336 
6337   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6338   SDValue Ops[] = {
6339       DAG.getEntryNode(),                               // Chain
6340       Rsrc,                                             // rsrc
6341       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6342       {},                                               // voffset
6343       {},                                               // soffset
6344       {},                                               // offset
6345       CachePolicy,                                      // cachepolicy
6346       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6347   };
6348 
6349   // Use the alignment to ensure that the required offsets will fit into the
6350   // immediate offsets.
6351   setBufferOffsets(Offset, DAG, &Ops[3],
6352                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6353 
6354   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6355   for (unsigned i = 0; i < NumLoads; ++i) {
6356     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6357     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6358                                         LoadVT, MMO, DAG));
6359   }
6360 
6361   if (NumElts == 8 || NumElts == 16)
6362     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6363 
6364   return Loads[0];
6365 }
6366 
6367 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6368                                                   SelectionDAG &DAG) const {
6369   MachineFunction &MF = DAG.getMachineFunction();
6370   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6371 
6372   EVT VT = Op.getValueType();
6373   SDLoc DL(Op);
6374   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6375 
6376   // TODO: Should this propagate fast-math-flags?
6377 
6378   switch (IntrinsicID) {
6379   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6380     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6381       return emitNonHSAIntrinsicError(DAG, DL, VT);
6382     return getPreloadedValue(DAG, *MFI, VT,
6383                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6384   }
6385   case Intrinsic::amdgcn_dispatch_ptr:
6386   case Intrinsic::amdgcn_queue_ptr: {
6387     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6388       DiagnosticInfoUnsupported BadIntrin(
6389           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6390           DL.getDebugLoc());
6391       DAG.getContext()->diagnose(BadIntrin);
6392       return DAG.getUNDEF(VT);
6393     }
6394 
6395     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6396       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6397     return getPreloadedValue(DAG, *MFI, VT, RegID);
6398   }
6399   case Intrinsic::amdgcn_implicitarg_ptr: {
6400     if (MFI->isEntryFunction())
6401       return getImplicitArgPtr(DAG, DL);
6402     return getPreloadedValue(DAG, *MFI, VT,
6403                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6404   }
6405   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6406     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6407       // This only makes sense to call in a kernel, so just lower to null.
6408       return DAG.getConstant(0, DL, VT);
6409     }
6410 
6411     return getPreloadedValue(DAG, *MFI, VT,
6412                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6413   }
6414   case Intrinsic::amdgcn_dispatch_id: {
6415     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6416   }
6417   case Intrinsic::amdgcn_rcp:
6418     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6419   case Intrinsic::amdgcn_rsq:
6420     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6421   case Intrinsic::amdgcn_rsq_legacy:
6422     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6423       return emitRemovedIntrinsicError(DAG, DL, VT);
6424     return SDValue();
6425   case Intrinsic::amdgcn_rcp_legacy:
6426     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6427       return emitRemovedIntrinsicError(DAG, DL, VT);
6428     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6429   case Intrinsic::amdgcn_rsq_clamp: {
6430     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6431       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6432 
6433     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6434     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6435     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6436 
6437     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6438     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6439                               DAG.getConstantFP(Max, DL, VT));
6440     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6441                        DAG.getConstantFP(Min, DL, VT));
6442   }
6443   case Intrinsic::r600_read_ngroups_x:
6444     if (Subtarget->isAmdHsaOS())
6445       return emitNonHSAIntrinsicError(DAG, DL, VT);
6446 
6447     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6448                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6449                                     false);
6450   case Intrinsic::r600_read_ngroups_y:
6451     if (Subtarget->isAmdHsaOS())
6452       return emitNonHSAIntrinsicError(DAG, DL, VT);
6453 
6454     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6455                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6456                                     false);
6457   case Intrinsic::r600_read_ngroups_z:
6458     if (Subtarget->isAmdHsaOS())
6459       return emitNonHSAIntrinsicError(DAG, DL, VT);
6460 
6461     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6462                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6463                                     false);
6464   case Intrinsic::r600_read_global_size_x:
6465     if (Subtarget->isAmdHsaOS())
6466       return emitNonHSAIntrinsicError(DAG, DL, VT);
6467 
6468     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6469                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6470                                     Align(4), false);
6471   case Intrinsic::r600_read_global_size_y:
6472     if (Subtarget->isAmdHsaOS())
6473       return emitNonHSAIntrinsicError(DAG, DL, VT);
6474 
6475     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6476                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6477                                     Align(4), false);
6478   case Intrinsic::r600_read_global_size_z:
6479     if (Subtarget->isAmdHsaOS())
6480       return emitNonHSAIntrinsicError(DAG, DL, VT);
6481 
6482     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6483                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6484                                     Align(4), false);
6485   case Intrinsic::r600_read_local_size_x:
6486     if (Subtarget->isAmdHsaOS())
6487       return emitNonHSAIntrinsicError(DAG, DL, VT);
6488 
6489     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6490                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6491   case Intrinsic::r600_read_local_size_y:
6492     if (Subtarget->isAmdHsaOS())
6493       return emitNonHSAIntrinsicError(DAG, DL, VT);
6494 
6495     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6496                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6497   case Intrinsic::r600_read_local_size_z:
6498     if (Subtarget->isAmdHsaOS())
6499       return emitNonHSAIntrinsicError(DAG, DL, VT);
6500 
6501     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6502                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6503   case Intrinsic::amdgcn_workgroup_id_x:
6504     return getPreloadedValue(DAG, *MFI, VT,
6505                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6506   case Intrinsic::amdgcn_workgroup_id_y:
6507     return getPreloadedValue(DAG, *MFI, VT,
6508                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6509   case Intrinsic::amdgcn_workgroup_id_z:
6510     return getPreloadedValue(DAG, *MFI, VT,
6511                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6512   case Intrinsic::amdgcn_workitem_id_x:
6513     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6514                           SDLoc(DAG.getEntryNode()),
6515                           MFI->getArgInfo().WorkItemIDX);
6516   case Intrinsic::amdgcn_workitem_id_y:
6517     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6518                           SDLoc(DAG.getEntryNode()),
6519                           MFI->getArgInfo().WorkItemIDY);
6520   case Intrinsic::amdgcn_workitem_id_z:
6521     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6522                           SDLoc(DAG.getEntryNode()),
6523                           MFI->getArgInfo().WorkItemIDZ);
6524   case Intrinsic::amdgcn_wavefrontsize:
6525     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6526                            SDLoc(Op), MVT::i32);
6527   case Intrinsic::amdgcn_s_buffer_load: {
6528     bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6529     SDValue GLC;
6530     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6531     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6532                           IsGFX10Plus ? &DLC : nullptr))
6533       return Op;
6534     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6535                         DAG);
6536   }
6537   case Intrinsic::amdgcn_fdiv_fast:
6538     return lowerFDIV_FAST(Op, DAG);
6539   case Intrinsic::amdgcn_sin:
6540     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6541 
6542   case Intrinsic::amdgcn_cos:
6543     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6544 
6545   case Intrinsic::amdgcn_mul_u24:
6546     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6547   case Intrinsic::amdgcn_mul_i24:
6548     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6549 
6550   case Intrinsic::amdgcn_log_clamp: {
6551     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6552       return SDValue();
6553 
6554     return emitRemovedIntrinsicError(DAG, DL, VT);
6555   }
6556   case Intrinsic::amdgcn_ldexp:
6557     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6558                        Op.getOperand(1), Op.getOperand(2));
6559 
6560   case Intrinsic::amdgcn_fract:
6561     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6562 
6563   case Intrinsic::amdgcn_class:
6564     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6565                        Op.getOperand(1), Op.getOperand(2));
6566   case Intrinsic::amdgcn_div_fmas:
6567     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6568                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6569                        Op.getOperand(4));
6570 
6571   case Intrinsic::amdgcn_div_fixup:
6572     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6573                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6574 
6575   case Intrinsic::amdgcn_div_scale: {
6576     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6577 
6578     // Translate to the operands expected by the machine instruction. The
6579     // first parameter must be the same as the first instruction.
6580     SDValue Numerator = Op.getOperand(1);
6581     SDValue Denominator = Op.getOperand(2);
6582 
6583     // Note this order is opposite of the machine instruction's operations,
6584     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6585     // intrinsic has the numerator as the first operand to match a normal
6586     // division operation.
6587 
6588     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6589 
6590     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6591                        Denominator, Numerator);
6592   }
6593   case Intrinsic::amdgcn_icmp: {
6594     // There is a Pat that handles this variant, so return it as-is.
6595     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6596         Op.getConstantOperandVal(2) == 0 &&
6597         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6598       return Op;
6599     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6600   }
6601   case Intrinsic::amdgcn_fcmp: {
6602     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6603   }
6604   case Intrinsic::amdgcn_ballot:
6605     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6606   case Intrinsic::amdgcn_fmed3:
6607     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6608                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6609   case Intrinsic::amdgcn_fdot2:
6610     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6611                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6612                        Op.getOperand(4));
6613   case Intrinsic::amdgcn_fmul_legacy:
6614     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6615                        Op.getOperand(1), Op.getOperand(2));
6616   case Intrinsic::amdgcn_sffbh:
6617     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6618   case Intrinsic::amdgcn_sbfe:
6619     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6620                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6621   case Intrinsic::amdgcn_ubfe:
6622     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6623                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6624   case Intrinsic::amdgcn_cvt_pkrtz:
6625   case Intrinsic::amdgcn_cvt_pknorm_i16:
6626   case Intrinsic::amdgcn_cvt_pknorm_u16:
6627   case Intrinsic::amdgcn_cvt_pk_i16:
6628   case Intrinsic::amdgcn_cvt_pk_u16: {
6629     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6630     EVT VT = Op.getValueType();
6631     unsigned Opcode;
6632 
6633     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6634       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6635     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6636       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6637     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6638       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6639     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6640       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6641     else
6642       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6643 
6644     if (isTypeLegal(VT))
6645       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6646 
6647     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6648                                Op.getOperand(1), Op.getOperand(2));
6649     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6650   }
6651   case Intrinsic::amdgcn_fmad_ftz:
6652     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6653                        Op.getOperand(2), Op.getOperand(3));
6654 
6655   case Intrinsic::amdgcn_if_break:
6656     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6657                                       Op->getOperand(1), Op->getOperand(2)), 0);
6658 
6659   case Intrinsic::amdgcn_groupstaticsize: {
6660     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6661     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6662       return Op;
6663 
6664     const Module *M = MF.getFunction().getParent();
6665     const GlobalValue *GV =
6666         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6667     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6668                                             SIInstrInfo::MO_ABS32_LO);
6669     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6670   }
6671   case Intrinsic::amdgcn_is_shared:
6672   case Intrinsic::amdgcn_is_private: {
6673     SDLoc SL(Op);
6674     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6675       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6676     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6677     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6678                                  Op.getOperand(1));
6679 
6680     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6681                                 DAG.getConstant(1, SL, MVT::i32));
6682     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6683   }
6684   case Intrinsic::amdgcn_alignbit:
6685     return DAG.getNode(ISD::FSHR, DL, VT,
6686                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6687   case Intrinsic::amdgcn_reloc_constant: {
6688     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6689     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6690     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6691     auto RelocSymbol = cast<GlobalVariable>(
6692         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6693     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6694                                             SIInstrInfo::MO_ABS32_LO);
6695     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6696   }
6697   default:
6698     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6699             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6700       return lowerImage(Op, ImageDimIntr, DAG, false);
6701 
6702     return Op;
6703   }
6704 }
6705 
6706 // This function computes an appropriate offset to pass to
6707 // MachineMemOperand::setOffset() based on the offset inputs to
6708 // an intrinsic.  If any of the offsets are non-contstant or
6709 // if VIndex is non-zero then this function returns 0.  Otherwise,
6710 // it returns the sum of VOffset, SOffset, and Offset.
6711 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6712                                       SDValue SOffset,
6713                                       SDValue Offset,
6714                                       SDValue VIndex = SDValue()) {
6715 
6716   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6717       !isa<ConstantSDNode>(Offset))
6718     return 0;
6719 
6720   if (VIndex) {
6721     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6722       return 0;
6723   }
6724 
6725   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6726          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6727          cast<ConstantSDNode>(Offset)->getSExtValue();
6728 }
6729 
6730 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6731                                                      SelectionDAG &DAG,
6732                                                      unsigned NewOpcode) const {
6733   SDLoc DL(Op);
6734 
6735   SDValue VData = Op.getOperand(2);
6736   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6737   SDValue Ops[] = {
6738     Op.getOperand(0), // Chain
6739     VData,            // vdata
6740     Op.getOperand(3), // rsrc
6741     DAG.getConstant(0, DL, MVT::i32), // vindex
6742     Offsets.first,    // voffset
6743     Op.getOperand(5), // soffset
6744     Offsets.second,   // offset
6745     Op.getOperand(6), // cachepolicy
6746     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6747   };
6748 
6749   auto *M = cast<MemSDNode>(Op);
6750   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6751 
6752   EVT MemVT = VData.getValueType();
6753   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6754                                  M->getMemOperand());
6755 }
6756 
6757 SDValue
6758 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6759                                                 unsigned NewOpcode) const {
6760   SDLoc DL(Op);
6761 
6762   SDValue VData = Op.getOperand(2);
6763   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6764   SDValue Ops[] = {
6765     Op.getOperand(0), // Chain
6766     VData,            // vdata
6767     Op.getOperand(3), // rsrc
6768     Op.getOperand(4), // vindex
6769     Offsets.first,    // voffset
6770     Op.getOperand(6), // soffset
6771     Offsets.second,   // offset
6772     Op.getOperand(7), // cachepolicy
6773     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6774   };
6775 
6776   auto *M = cast<MemSDNode>(Op);
6777   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6778                                                       Ops[3]));
6779 
6780   EVT MemVT = VData.getValueType();
6781   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6782                                  M->getMemOperand());
6783 }
6784 
6785 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6786                                                  SelectionDAG &DAG) const {
6787   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6788   SDLoc DL(Op);
6789 
6790   switch (IntrID) {
6791   case Intrinsic::amdgcn_ds_ordered_add:
6792   case Intrinsic::amdgcn_ds_ordered_swap: {
6793     MemSDNode *M = cast<MemSDNode>(Op);
6794     SDValue Chain = M->getOperand(0);
6795     SDValue M0 = M->getOperand(2);
6796     SDValue Value = M->getOperand(3);
6797     unsigned IndexOperand = M->getConstantOperandVal(7);
6798     unsigned WaveRelease = M->getConstantOperandVal(8);
6799     unsigned WaveDone = M->getConstantOperandVal(9);
6800 
6801     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6802     IndexOperand &= ~0x3f;
6803     unsigned CountDw = 0;
6804 
6805     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6806       CountDw = (IndexOperand >> 24) & 0xf;
6807       IndexOperand &= ~(0xf << 24);
6808 
6809       if (CountDw < 1 || CountDw > 4) {
6810         report_fatal_error(
6811             "ds_ordered_count: dword count must be between 1 and 4");
6812       }
6813     }
6814 
6815     if (IndexOperand)
6816       report_fatal_error("ds_ordered_count: bad index operand");
6817 
6818     if (WaveDone && !WaveRelease)
6819       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6820 
6821     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6822     unsigned ShaderType =
6823         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6824     unsigned Offset0 = OrderedCountIndex << 2;
6825     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6826                        (Instruction << 4);
6827 
6828     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6829       Offset1 |= (CountDw - 1) << 6;
6830 
6831     unsigned Offset = Offset0 | (Offset1 << 8);
6832 
6833     SDValue Ops[] = {
6834       Chain,
6835       Value,
6836       DAG.getTargetConstant(Offset, DL, MVT::i16),
6837       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6838     };
6839     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6840                                    M->getVTList(), Ops, M->getMemoryVT(),
6841                                    M->getMemOperand());
6842   }
6843   case Intrinsic::amdgcn_ds_fadd: {
6844     MemSDNode *M = cast<MemSDNode>(Op);
6845     unsigned Opc;
6846     switch (IntrID) {
6847     case Intrinsic::amdgcn_ds_fadd:
6848       Opc = ISD::ATOMIC_LOAD_FADD;
6849       break;
6850     }
6851 
6852     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6853                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6854                          M->getMemOperand());
6855   }
6856   case Intrinsic::amdgcn_atomic_inc:
6857   case Intrinsic::amdgcn_atomic_dec:
6858   case Intrinsic::amdgcn_ds_fmin:
6859   case Intrinsic::amdgcn_ds_fmax: {
6860     MemSDNode *M = cast<MemSDNode>(Op);
6861     unsigned Opc;
6862     switch (IntrID) {
6863     case Intrinsic::amdgcn_atomic_inc:
6864       Opc = AMDGPUISD::ATOMIC_INC;
6865       break;
6866     case Intrinsic::amdgcn_atomic_dec:
6867       Opc = AMDGPUISD::ATOMIC_DEC;
6868       break;
6869     case Intrinsic::amdgcn_ds_fmin:
6870       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6871       break;
6872     case Intrinsic::amdgcn_ds_fmax:
6873       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6874       break;
6875     default:
6876       llvm_unreachable("Unknown intrinsic!");
6877     }
6878     SDValue Ops[] = {
6879       M->getOperand(0), // Chain
6880       M->getOperand(2), // Ptr
6881       M->getOperand(3)  // Value
6882     };
6883 
6884     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6885                                    M->getMemoryVT(), M->getMemOperand());
6886   }
6887   case Intrinsic::amdgcn_buffer_load:
6888   case Intrinsic::amdgcn_buffer_load_format: {
6889     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6890     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6891     unsigned IdxEn = 1;
6892     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6893       IdxEn = Idx->getZExtValue() != 0;
6894     SDValue Ops[] = {
6895       Op.getOperand(0), // Chain
6896       Op.getOperand(2), // rsrc
6897       Op.getOperand(3), // vindex
6898       SDValue(),        // voffset -- will be set by setBufferOffsets
6899       SDValue(),        // soffset -- will be set by setBufferOffsets
6900       SDValue(),        // offset -- will be set by setBufferOffsets
6901       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6902       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6903     };
6904 
6905     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6906     // We don't know the offset if vindex is non-zero, so clear it.
6907     if (IdxEn)
6908       Offset = 0;
6909 
6910     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6911         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6912 
6913     EVT VT = Op.getValueType();
6914     EVT IntVT = VT.changeTypeToInteger();
6915     auto *M = cast<MemSDNode>(Op);
6916     M->getMemOperand()->setOffset(Offset);
6917     EVT LoadVT = Op.getValueType();
6918 
6919     if (LoadVT.getScalarType() == MVT::f16)
6920       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6921                                  M, DAG, Ops);
6922 
6923     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6924     if (LoadVT.getScalarType() == MVT::i8 ||
6925         LoadVT.getScalarType() == MVT::i16)
6926       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6927 
6928     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6929                                M->getMemOperand(), DAG);
6930   }
6931   case Intrinsic::amdgcn_raw_buffer_load:
6932   case Intrinsic::amdgcn_raw_buffer_load_format: {
6933     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6934 
6935     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6936     SDValue Ops[] = {
6937       Op.getOperand(0), // Chain
6938       Op.getOperand(2), // rsrc
6939       DAG.getConstant(0, DL, MVT::i32), // vindex
6940       Offsets.first,    // voffset
6941       Op.getOperand(4), // soffset
6942       Offsets.second,   // offset
6943       Op.getOperand(5), // cachepolicy, swizzled buffer
6944       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6945     };
6946 
6947     auto *M = cast<MemSDNode>(Op);
6948     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6949     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6950   }
6951   case Intrinsic::amdgcn_struct_buffer_load:
6952   case Intrinsic::amdgcn_struct_buffer_load_format: {
6953     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6954 
6955     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6956     SDValue Ops[] = {
6957       Op.getOperand(0), // Chain
6958       Op.getOperand(2), // rsrc
6959       Op.getOperand(3), // vindex
6960       Offsets.first,    // voffset
6961       Op.getOperand(5), // soffset
6962       Offsets.second,   // offset
6963       Op.getOperand(6), // cachepolicy, swizzled buffer
6964       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6965     };
6966 
6967     auto *M = cast<MemSDNode>(Op);
6968     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6969                                                         Ops[2]));
6970     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6971   }
6972   case Intrinsic::amdgcn_tbuffer_load: {
6973     MemSDNode *M = cast<MemSDNode>(Op);
6974     EVT LoadVT = Op.getValueType();
6975 
6976     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6977     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6978     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6979     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6980     unsigned IdxEn = 1;
6981     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6982       IdxEn = Idx->getZExtValue() != 0;
6983     SDValue Ops[] = {
6984       Op.getOperand(0),  // Chain
6985       Op.getOperand(2),  // rsrc
6986       Op.getOperand(3),  // vindex
6987       Op.getOperand(4),  // voffset
6988       Op.getOperand(5),  // soffset
6989       Op.getOperand(6),  // offset
6990       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6991       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6992       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6993     };
6994 
6995     if (LoadVT.getScalarType() == MVT::f16)
6996       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6997                                  M, DAG, Ops);
6998     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6999                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7000                                DAG);
7001   }
7002   case Intrinsic::amdgcn_raw_tbuffer_load: {
7003     MemSDNode *M = cast<MemSDNode>(Op);
7004     EVT LoadVT = Op.getValueType();
7005     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7006 
7007     SDValue Ops[] = {
7008       Op.getOperand(0),  // Chain
7009       Op.getOperand(2),  // rsrc
7010       DAG.getConstant(0, DL, MVT::i32), // vindex
7011       Offsets.first,     // voffset
7012       Op.getOperand(4),  // soffset
7013       Offsets.second,    // offset
7014       Op.getOperand(5),  // format
7015       Op.getOperand(6),  // cachepolicy, swizzled buffer
7016       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7017     };
7018 
7019     if (LoadVT.getScalarType() == MVT::f16)
7020       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7021                                  M, DAG, Ops);
7022     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7023                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7024                                DAG);
7025   }
7026   case Intrinsic::amdgcn_struct_tbuffer_load: {
7027     MemSDNode *M = cast<MemSDNode>(Op);
7028     EVT LoadVT = Op.getValueType();
7029     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7030 
7031     SDValue Ops[] = {
7032       Op.getOperand(0),  // Chain
7033       Op.getOperand(2),  // rsrc
7034       Op.getOperand(3),  // vindex
7035       Offsets.first,     // voffset
7036       Op.getOperand(5),  // soffset
7037       Offsets.second,    // offset
7038       Op.getOperand(6),  // format
7039       Op.getOperand(7),  // cachepolicy, swizzled buffer
7040       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7041     };
7042 
7043     if (LoadVT.getScalarType() == MVT::f16)
7044       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7045                                  M, DAG, Ops);
7046     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7047                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7048                                DAG);
7049   }
7050   case Intrinsic::amdgcn_buffer_atomic_swap:
7051   case Intrinsic::amdgcn_buffer_atomic_add:
7052   case Intrinsic::amdgcn_buffer_atomic_sub:
7053   case Intrinsic::amdgcn_buffer_atomic_csub:
7054   case Intrinsic::amdgcn_buffer_atomic_smin:
7055   case Intrinsic::amdgcn_buffer_atomic_umin:
7056   case Intrinsic::amdgcn_buffer_atomic_smax:
7057   case Intrinsic::amdgcn_buffer_atomic_umax:
7058   case Intrinsic::amdgcn_buffer_atomic_and:
7059   case Intrinsic::amdgcn_buffer_atomic_or:
7060   case Intrinsic::amdgcn_buffer_atomic_xor:
7061   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7062     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7063     unsigned IdxEn = 1;
7064     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7065       IdxEn = Idx->getZExtValue() != 0;
7066     SDValue Ops[] = {
7067       Op.getOperand(0), // Chain
7068       Op.getOperand(2), // vdata
7069       Op.getOperand(3), // rsrc
7070       Op.getOperand(4), // vindex
7071       SDValue(),        // voffset -- will be set by setBufferOffsets
7072       SDValue(),        // soffset -- will be set by setBufferOffsets
7073       SDValue(),        // offset -- will be set by setBufferOffsets
7074       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7075       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7076     };
7077     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7078     // We don't know the offset if vindex is non-zero, so clear it.
7079     if (IdxEn)
7080       Offset = 0;
7081     EVT VT = Op.getValueType();
7082 
7083     auto *M = cast<MemSDNode>(Op);
7084     M->getMemOperand()->setOffset(Offset);
7085     unsigned Opcode = 0;
7086 
7087     switch (IntrID) {
7088     case Intrinsic::amdgcn_buffer_atomic_swap:
7089       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7090       break;
7091     case Intrinsic::amdgcn_buffer_atomic_add:
7092       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7093       break;
7094     case Intrinsic::amdgcn_buffer_atomic_sub:
7095       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7096       break;
7097     case Intrinsic::amdgcn_buffer_atomic_csub:
7098       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7099       break;
7100     case Intrinsic::amdgcn_buffer_atomic_smin:
7101       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7102       break;
7103     case Intrinsic::amdgcn_buffer_atomic_umin:
7104       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7105       break;
7106     case Intrinsic::amdgcn_buffer_atomic_smax:
7107       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7108       break;
7109     case Intrinsic::amdgcn_buffer_atomic_umax:
7110       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7111       break;
7112     case Intrinsic::amdgcn_buffer_atomic_and:
7113       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7114       break;
7115     case Intrinsic::amdgcn_buffer_atomic_or:
7116       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7117       break;
7118     case Intrinsic::amdgcn_buffer_atomic_xor:
7119       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7120       break;
7121     case Intrinsic::amdgcn_buffer_atomic_fadd:
7122       if (!Op.getValue(0).use_empty()) {
7123         DiagnosticInfoUnsupported
7124           NoFpRet(DAG.getMachineFunction().getFunction(),
7125                   "return versions of fp atomics not supported",
7126                   DL.getDebugLoc(), DS_Error);
7127         DAG.getContext()->diagnose(NoFpRet);
7128         return SDValue();
7129       }
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7131       break;
7132     default:
7133       llvm_unreachable("unhandled atomic opcode");
7134     }
7135 
7136     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7137                                    M->getMemOperand());
7138   }
7139   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7140     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7141   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7142     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7143   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7144     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7145   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7146     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7147   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7148     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7149   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7150     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7151   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7152     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7153   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7154     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7155   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7156     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7157   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7158     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7159   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7160     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7161   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7162     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7163   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7164     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7165   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7166     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7167   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7168     return lowerStructBufferAtomicIntrin(Op, DAG,
7169                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7170   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7171     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7172   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7173     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7174   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7175     return lowerStructBufferAtomicIntrin(Op, DAG,
7176                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7177   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7178     return lowerStructBufferAtomicIntrin(Op, DAG,
7179                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7180   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7181     return lowerStructBufferAtomicIntrin(Op, DAG,
7182                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7183   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7184     return lowerStructBufferAtomicIntrin(Op, DAG,
7185                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7186   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7187     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7188   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7189     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7190   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7191     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7192   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7193     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7194   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7195     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7196 
7197   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7198     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7199     unsigned IdxEn = 1;
7200     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7201       IdxEn = Idx->getZExtValue() != 0;
7202     SDValue Ops[] = {
7203       Op.getOperand(0), // Chain
7204       Op.getOperand(2), // src
7205       Op.getOperand(3), // cmp
7206       Op.getOperand(4), // rsrc
7207       Op.getOperand(5), // vindex
7208       SDValue(),        // voffset -- will be set by setBufferOffsets
7209       SDValue(),        // soffset -- will be set by setBufferOffsets
7210       SDValue(),        // offset -- will be set by setBufferOffsets
7211       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7212       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7213     };
7214     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7215     // We don't know the offset if vindex is non-zero, so clear it.
7216     if (IdxEn)
7217       Offset = 0;
7218     EVT VT = Op.getValueType();
7219     auto *M = cast<MemSDNode>(Op);
7220     M->getMemOperand()->setOffset(Offset);
7221 
7222     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7223                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7224   }
7225   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7226     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7227     SDValue Ops[] = {
7228       Op.getOperand(0), // Chain
7229       Op.getOperand(2), // src
7230       Op.getOperand(3), // cmp
7231       Op.getOperand(4), // rsrc
7232       DAG.getConstant(0, DL, MVT::i32), // vindex
7233       Offsets.first,    // voffset
7234       Op.getOperand(6), // soffset
7235       Offsets.second,   // offset
7236       Op.getOperand(7), // cachepolicy
7237       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7238     };
7239     EVT VT = Op.getValueType();
7240     auto *M = cast<MemSDNode>(Op);
7241     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7242 
7243     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7244                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7245   }
7246   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7247     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7248     SDValue Ops[] = {
7249       Op.getOperand(0), // Chain
7250       Op.getOperand(2), // src
7251       Op.getOperand(3), // cmp
7252       Op.getOperand(4), // rsrc
7253       Op.getOperand(5), // vindex
7254       Offsets.first,    // voffset
7255       Op.getOperand(7), // soffset
7256       Offsets.second,   // offset
7257       Op.getOperand(8), // cachepolicy
7258       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7259     };
7260     EVT VT = Op.getValueType();
7261     auto *M = cast<MemSDNode>(Op);
7262     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7263                                                         Ops[4]));
7264 
7265     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7266                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7267   }
7268   case Intrinsic::amdgcn_global_atomic_fadd: {
7269     if (!Op.getValue(0).use_empty()) {
7270       DiagnosticInfoUnsupported
7271         NoFpRet(DAG.getMachineFunction().getFunction(),
7272                 "return versions of fp atomics not supported",
7273                 DL.getDebugLoc(), DS_Error);
7274       DAG.getContext()->diagnose(NoFpRet);
7275       return SDValue();
7276     }
7277     MemSDNode *M = cast<MemSDNode>(Op);
7278     SDValue Ops[] = {
7279       M->getOperand(0), // Chain
7280       M->getOperand(2), // Ptr
7281       M->getOperand(3)  // Value
7282     };
7283 
7284     EVT VT = Op.getOperand(3).getValueType();
7285     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7286                          DAG.getVTList(VT, MVT::Other), Ops,
7287                          M->getMemOperand());
7288   }
7289   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7290     SDLoc DL(Op);
7291     MemSDNode *M = cast<MemSDNode>(Op);
7292     SDValue NodePtr = M->getOperand(2);
7293     SDValue RayExtent = M->getOperand(3);
7294     SDValue RayOrigin = M->getOperand(4);
7295     SDValue RayDir = M->getOperand(5);
7296     SDValue RayInvDir = M->getOperand(6);
7297     SDValue TDescr = M->getOperand(7);
7298 
7299     assert(NodePtr.getValueType() == MVT::i32 ||
7300            NodePtr.getValueType() == MVT::i64);
7301     assert(RayDir.getValueType() == MVT::v4f16 ||
7302            RayDir.getValueType() == MVT::v4f32);
7303 
7304     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7305     bool Is64 = NodePtr.getValueType() == MVT::i64;
7306     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7307                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7308                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7309                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7310 
7311     SmallVector<SDValue, 16> Ops;
7312 
7313     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7314       SmallVector<SDValue, 3> Lanes;
7315       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7316       if (Lanes[0].getValueSizeInBits() == 32) {
7317         for (unsigned I = 0; I < 3; ++I)
7318           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7319       } else {
7320         if (IsAligned) {
7321           Ops.push_back(
7322             DAG.getBitcast(MVT::i32,
7323                            DAG.getBuildVector(MVT::v2f16, DL,
7324                                               { Lanes[0], Lanes[1] })));
7325           Ops.push_back(Lanes[2]);
7326         } else {
7327           SDValue Elt0 = Ops.pop_back_val();
7328           Ops.push_back(
7329             DAG.getBitcast(MVT::i32,
7330                            DAG.getBuildVector(MVT::v2f16, DL,
7331                                               { Elt0, Lanes[0] })));
7332           Ops.push_back(
7333             DAG.getBitcast(MVT::i32,
7334                            DAG.getBuildVector(MVT::v2f16, DL,
7335                                               { Lanes[1], Lanes[2] })));
7336         }
7337       }
7338     };
7339 
7340     if (Is64)
7341       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7342     else
7343       Ops.push_back(NodePtr);
7344 
7345     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7346     packLanes(RayOrigin, true);
7347     packLanes(RayDir, true);
7348     packLanes(RayInvDir, false);
7349     Ops.push_back(TDescr);
7350     if (IsA16)
7351       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7352     Ops.push_back(M->getChain());
7353 
7354     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7355     MachineMemOperand *MemRef = M->getMemOperand();
7356     DAG.setNodeMemRefs(NewNode, {MemRef});
7357     return SDValue(NewNode, 0);
7358   }
7359   default:
7360     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7361             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7362       return lowerImage(Op, ImageDimIntr, DAG, true);
7363 
7364     return SDValue();
7365   }
7366 }
7367 
7368 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7369 // dwordx4 if on SI.
7370 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7371                                               SDVTList VTList,
7372                                               ArrayRef<SDValue> Ops, EVT MemVT,
7373                                               MachineMemOperand *MMO,
7374                                               SelectionDAG &DAG) const {
7375   EVT VT = VTList.VTs[0];
7376   EVT WidenedVT = VT;
7377   EVT WidenedMemVT = MemVT;
7378   if (!Subtarget->hasDwordx3LoadStores() &&
7379       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7380     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7381                                  WidenedVT.getVectorElementType(), 4);
7382     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7383                                     WidenedMemVT.getVectorElementType(), 4);
7384     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7385   }
7386 
7387   assert(VTList.NumVTs == 2);
7388   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7389 
7390   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7391                                        WidenedMemVT, MMO);
7392   if (WidenedVT != VT) {
7393     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7394                                DAG.getVectorIdxConstant(0, DL));
7395     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7396   }
7397   return NewOp;
7398 }
7399 
7400 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7401                                          bool ImageStore) const {
7402   EVT StoreVT = VData.getValueType();
7403 
7404   // No change for f16 and legal vector D16 types.
7405   if (!StoreVT.isVector())
7406     return VData;
7407 
7408   SDLoc DL(VData);
7409   unsigned NumElements = StoreVT.getVectorNumElements();
7410 
7411   if (Subtarget->hasUnpackedD16VMem()) {
7412     // We need to unpack the packed data to store.
7413     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7414     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7415 
7416     EVT EquivStoreVT =
7417         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7418     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7419     return DAG.UnrollVectorOp(ZExt.getNode());
7420   }
7421 
7422   // The sq block of gfx8.1 does not estimate register use correctly for d16
7423   // image store instructions. The data operand is computed as if it were not a
7424   // d16 image instruction.
7425   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7426     // Bitcast to i16
7427     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7428     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7429 
7430     // Decompose into scalars
7431     SmallVector<SDValue, 4> Elts;
7432     DAG.ExtractVectorElements(IntVData, Elts);
7433 
7434     // Group pairs of i16 into v2i16 and bitcast to i32
7435     SmallVector<SDValue, 4> PackedElts;
7436     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7437       SDValue Pair =
7438           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7439       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7440       PackedElts.push_back(IntPair);
7441     }
7442     if ((NumElements % 2) == 1) {
7443       // Handle v3i16
7444       unsigned I = Elts.size() / 2;
7445       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7446                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7447       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7448       PackedElts.push_back(IntPair);
7449     }
7450 
7451     // Pad using UNDEF
7452     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7453 
7454     // Build final vector
7455     EVT VecVT =
7456         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7457     return DAG.getBuildVector(VecVT, DL, PackedElts);
7458   }
7459 
7460   if (NumElements == 3) {
7461     EVT IntStoreVT =
7462         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7463     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7464 
7465     EVT WidenedStoreVT = EVT::getVectorVT(
7466         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7467     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7468                                          WidenedStoreVT.getStoreSizeInBits());
7469     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7470     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7471   }
7472 
7473   assert(isTypeLegal(StoreVT));
7474   return VData;
7475 }
7476 
7477 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7478                                               SelectionDAG &DAG) const {
7479   SDLoc DL(Op);
7480   SDValue Chain = Op.getOperand(0);
7481   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7482   MachineFunction &MF = DAG.getMachineFunction();
7483 
7484   switch (IntrinsicID) {
7485   case Intrinsic::amdgcn_exp_compr: {
7486     SDValue Src0 = Op.getOperand(4);
7487     SDValue Src1 = Op.getOperand(5);
7488     // Hack around illegal type on SI by directly selecting it.
7489     if (isTypeLegal(Src0.getValueType()))
7490       return SDValue();
7491 
7492     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7493     SDValue Undef = DAG.getUNDEF(MVT::f32);
7494     const SDValue Ops[] = {
7495       Op.getOperand(2), // tgt
7496       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7497       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7498       Undef, // src2
7499       Undef, // src3
7500       Op.getOperand(7), // vm
7501       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7502       Op.getOperand(3), // en
7503       Op.getOperand(0) // Chain
7504     };
7505 
7506     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7507     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7508   }
7509   case Intrinsic::amdgcn_s_barrier: {
7510     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7511       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7512       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7513       if (WGSize <= ST.getWavefrontSize())
7514         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7515                                           Op.getOperand(0)), 0);
7516     }
7517     return SDValue();
7518   };
7519   case Intrinsic::amdgcn_tbuffer_store: {
7520     SDValue VData = Op.getOperand(2);
7521     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7522     if (IsD16)
7523       VData = handleD16VData(VData, DAG);
7524     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7525     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7526     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7527     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7528     unsigned IdxEn = 1;
7529     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7530       IdxEn = Idx->getZExtValue() != 0;
7531     SDValue Ops[] = {
7532       Chain,
7533       VData,             // vdata
7534       Op.getOperand(3),  // rsrc
7535       Op.getOperand(4),  // vindex
7536       Op.getOperand(5),  // voffset
7537       Op.getOperand(6),  // soffset
7538       Op.getOperand(7),  // offset
7539       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7540       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7541       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7542     };
7543     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7544                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7545     MemSDNode *M = cast<MemSDNode>(Op);
7546     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7547                                    M->getMemoryVT(), M->getMemOperand());
7548   }
7549 
7550   case Intrinsic::amdgcn_struct_tbuffer_store: {
7551     SDValue VData = Op.getOperand(2);
7552     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7553     if (IsD16)
7554       VData = handleD16VData(VData, DAG);
7555     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7556     SDValue Ops[] = {
7557       Chain,
7558       VData,             // vdata
7559       Op.getOperand(3),  // rsrc
7560       Op.getOperand(4),  // vindex
7561       Offsets.first,     // voffset
7562       Op.getOperand(6),  // soffset
7563       Offsets.second,    // offset
7564       Op.getOperand(7),  // format
7565       Op.getOperand(8),  // cachepolicy, swizzled buffer
7566       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7567     };
7568     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7569                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7570     MemSDNode *M = cast<MemSDNode>(Op);
7571     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7572                                    M->getMemoryVT(), M->getMemOperand());
7573   }
7574 
7575   case Intrinsic::amdgcn_raw_tbuffer_store: {
7576     SDValue VData = Op.getOperand(2);
7577     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7578     if (IsD16)
7579       VData = handleD16VData(VData, DAG);
7580     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7581     SDValue Ops[] = {
7582       Chain,
7583       VData,             // vdata
7584       Op.getOperand(3),  // rsrc
7585       DAG.getConstant(0, DL, MVT::i32), // vindex
7586       Offsets.first,     // voffset
7587       Op.getOperand(5),  // soffset
7588       Offsets.second,    // offset
7589       Op.getOperand(6),  // format
7590       Op.getOperand(7),  // cachepolicy, swizzled buffer
7591       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7592     };
7593     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7594                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7595     MemSDNode *M = cast<MemSDNode>(Op);
7596     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7597                                    M->getMemoryVT(), M->getMemOperand());
7598   }
7599 
7600   case Intrinsic::amdgcn_buffer_store:
7601   case Intrinsic::amdgcn_buffer_store_format: {
7602     SDValue VData = Op.getOperand(2);
7603     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7604     if (IsD16)
7605       VData = handleD16VData(VData, DAG);
7606     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7607     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7608     unsigned IdxEn = 1;
7609     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7610       IdxEn = Idx->getZExtValue() != 0;
7611     SDValue Ops[] = {
7612       Chain,
7613       VData,
7614       Op.getOperand(3), // rsrc
7615       Op.getOperand(4), // vindex
7616       SDValue(), // voffset -- will be set by setBufferOffsets
7617       SDValue(), // soffset -- will be set by setBufferOffsets
7618       SDValue(), // offset -- will be set by setBufferOffsets
7619       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7620       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7621     };
7622     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7623     // We don't know the offset if vindex is non-zero, so clear it.
7624     if (IdxEn)
7625       Offset = 0;
7626     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7627                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7628     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7629     MemSDNode *M = cast<MemSDNode>(Op);
7630     M->getMemOperand()->setOffset(Offset);
7631 
7632     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7633     EVT VDataType = VData.getValueType().getScalarType();
7634     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7635       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7636 
7637     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7638                                    M->getMemoryVT(), M->getMemOperand());
7639   }
7640 
7641   case Intrinsic::amdgcn_raw_buffer_store:
7642   case Intrinsic::amdgcn_raw_buffer_store_format: {
7643     const bool IsFormat =
7644         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7645 
7646     SDValue VData = Op.getOperand(2);
7647     EVT VDataVT = VData.getValueType();
7648     EVT EltType = VDataVT.getScalarType();
7649     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7650     if (IsD16) {
7651       VData = handleD16VData(VData, DAG);
7652       VDataVT = VData.getValueType();
7653     }
7654 
7655     if (!isTypeLegal(VDataVT)) {
7656       VData =
7657           DAG.getNode(ISD::BITCAST, DL,
7658                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7659     }
7660 
7661     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7662     SDValue Ops[] = {
7663       Chain,
7664       VData,
7665       Op.getOperand(3), // rsrc
7666       DAG.getConstant(0, DL, MVT::i32), // vindex
7667       Offsets.first,    // voffset
7668       Op.getOperand(5), // soffset
7669       Offsets.second,   // offset
7670       Op.getOperand(6), // cachepolicy, swizzled buffer
7671       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7672     };
7673     unsigned Opc =
7674         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7675     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7676     MemSDNode *M = cast<MemSDNode>(Op);
7677     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7678 
7679     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7680     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7681       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7682 
7683     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7684                                    M->getMemoryVT(), M->getMemOperand());
7685   }
7686 
7687   case Intrinsic::amdgcn_struct_buffer_store:
7688   case Intrinsic::amdgcn_struct_buffer_store_format: {
7689     const bool IsFormat =
7690         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7691 
7692     SDValue VData = Op.getOperand(2);
7693     EVT VDataVT = VData.getValueType();
7694     EVT EltType = VDataVT.getScalarType();
7695     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7696 
7697     if (IsD16) {
7698       VData = handleD16VData(VData, DAG);
7699       VDataVT = VData.getValueType();
7700     }
7701 
7702     if (!isTypeLegal(VDataVT)) {
7703       VData =
7704           DAG.getNode(ISD::BITCAST, DL,
7705                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7706     }
7707 
7708     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7709     SDValue Ops[] = {
7710       Chain,
7711       VData,
7712       Op.getOperand(3), // rsrc
7713       Op.getOperand(4), // vindex
7714       Offsets.first,    // voffset
7715       Op.getOperand(6), // soffset
7716       Offsets.second,   // offset
7717       Op.getOperand(7), // cachepolicy, swizzled buffer
7718       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7719     };
7720     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7721                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7722     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7723     MemSDNode *M = cast<MemSDNode>(Op);
7724     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7725                                                         Ops[3]));
7726 
7727     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7728     EVT VDataType = VData.getValueType().getScalarType();
7729     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7730       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7731 
7732     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7733                                    M->getMemoryVT(), M->getMemOperand());
7734   }
7735   case Intrinsic::amdgcn_end_cf:
7736     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7737                                       Op->getOperand(2), Chain), 0);
7738 
7739   default: {
7740     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7741             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7742       return lowerImage(Op, ImageDimIntr, DAG, true);
7743 
7744     return Op;
7745   }
7746   }
7747 }
7748 
7749 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7750 // offset (the offset that is included in bounds checking and swizzling, to be
7751 // split between the instruction's voffset and immoffset fields) and soffset
7752 // (the offset that is excluded from bounds checking and swizzling, to go in
7753 // the instruction's soffset field).  This function takes the first kind of
7754 // offset and figures out how to split it between voffset and immoffset.
7755 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7756     SDValue Offset, SelectionDAG &DAG) const {
7757   SDLoc DL(Offset);
7758   const unsigned MaxImm = 4095;
7759   SDValue N0 = Offset;
7760   ConstantSDNode *C1 = nullptr;
7761 
7762   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7763     N0 = SDValue();
7764   else if (DAG.isBaseWithConstantOffset(N0)) {
7765     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7766     N0 = N0.getOperand(0);
7767   }
7768 
7769   if (C1) {
7770     unsigned ImmOffset = C1->getZExtValue();
7771     // If the immediate value is too big for the immoffset field, put the value
7772     // and -4096 into the immoffset field so that the value that is copied/added
7773     // for the voffset field is a multiple of 4096, and it stands more chance
7774     // of being CSEd with the copy/add for another similar load/store.
7775     // However, do not do that rounding down to a multiple of 4096 if that is a
7776     // negative number, as it appears to be illegal to have a negative offset
7777     // in the vgpr, even if adding the immediate offset makes it positive.
7778     unsigned Overflow = ImmOffset & ~MaxImm;
7779     ImmOffset -= Overflow;
7780     if ((int32_t)Overflow < 0) {
7781       Overflow += ImmOffset;
7782       ImmOffset = 0;
7783     }
7784     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7785     if (Overflow) {
7786       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7787       if (!N0)
7788         N0 = OverflowVal;
7789       else {
7790         SDValue Ops[] = { N0, OverflowVal };
7791         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7792       }
7793     }
7794   }
7795   if (!N0)
7796     N0 = DAG.getConstant(0, DL, MVT::i32);
7797   if (!C1)
7798     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7799   return {N0, SDValue(C1, 0)};
7800 }
7801 
7802 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7803 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7804 // pointed to by Offsets.
7805 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7806                                             SelectionDAG &DAG, SDValue *Offsets,
7807                                             Align Alignment) const {
7808   SDLoc DL(CombinedOffset);
7809   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7810     uint32_t Imm = C->getZExtValue();
7811     uint32_t SOffset, ImmOffset;
7812     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7813                                  Alignment)) {
7814       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7815       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7816       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7817       return SOffset + ImmOffset;
7818     }
7819   }
7820   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7821     SDValue N0 = CombinedOffset.getOperand(0);
7822     SDValue N1 = CombinedOffset.getOperand(1);
7823     uint32_t SOffset, ImmOffset;
7824     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7825     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7826                                                 Subtarget, Alignment)) {
7827       Offsets[0] = N0;
7828       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7829       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7830       return 0;
7831     }
7832   }
7833   Offsets[0] = CombinedOffset;
7834   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7835   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7836   return 0;
7837 }
7838 
7839 // Handle 8 bit and 16 bit buffer loads
7840 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7841                                                      EVT LoadVT, SDLoc DL,
7842                                                      ArrayRef<SDValue> Ops,
7843                                                      MemSDNode *M) const {
7844   EVT IntVT = LoadVT.changeTypeToInteger();
7845   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7846          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7847 
7848   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7849   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7850                                                Ops, IntVT,
7851                                                M->getMemOperand());
7852   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7853   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7854 
7855   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7856 }
7857 
7858 // Handle 8 bit and 16 bit buffer stores
7859 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7860                                                       EVT VDataType, SDLoc DL,
7861                                                       SDValue Ops[],
7862                                                       MemSDNode *M) const {
7863   if (VDataType == MVT::f16)
7864     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7865 
7866   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7867   Ops[1] = BufferStoreExt;
7868   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7869                                  AMDGPUISD::BUFFER_STORE_SHORT;
7870   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7871   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7872                                      M->getMemOperand());
7873 }
7874 
7875 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7876                                  ISD::LoadExtType ExtType, SDValue Op,
7877                                  const SDLoc &SL, EVT VT) {
7878   if (VT.bitsLT(Op.getValueType()))
7879     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7880 
7881   switch (ExtType) {
7882   case ISD::SEXTLOAD:
7883     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7884   case ISD::ZEXTLOAD:
7885     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7886   case ISD::EXTLOAD:
7887     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7888   case ISD::NON_EXTLOAD:
7889     return Op;
7890   }
7891 
7892   llvm_unreachable("invalid ext type");
7893 }
7894 
7895 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7896   SelectionDAG &DAG = DCI.DAG;
7897   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7898     return SDValue();
7899 
7900   // FIXME: Constant loads should all be marked invariant.
7901   unsigned AS = Ld->getAddressSpace();
7902   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7903       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7904       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7905     return SDValue();
7906 
7907   // Don't do this early, since it may interfere with adjacent load merging for
7908   // illegal types. We can avoid losing alignment information for exotic types
7909   // pre-legalize.
7910   EVT MemVT = Ld->getMemoryVT();
7911   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7912       MemVT.getSizeInBits() >= 32)
7913     return SDValue();
7914 
7915   SDLoc SL(Ld);
7916 
7917   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7918          "unexpected vector extload");
7919 
7920   // TODO: Drop only high part of range.
7921   SDValue Ptr = Ld->getBasePtr();
7922   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7923                                 MVT::i32, SL, Ld->getChain(), Ptr,
7924                                 Ld->getOffset(),
7925                                 Ld->getPointerInfo(), MVT::i32,
7926                                 Ld->getAlignment(),
7927                                 Ld->getMemOperand()->getFlags(),
7928                                 Ld->getAAInfo(),
7929                                 nullptr); // Drop ranges
7930 
7931   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7932   if (MemVT.isFloatingPoint()) {
7933     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7934            "unexpected fp extload");
7935     TruncVT = MemVT.changeTypeToInteger();
7936   }
7937 
7938   SDValue Cvt = NewLoad;
7939   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7940     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7941                       DAG.getValueType(TruncVT));
7942   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7943              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7944     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7945   } else {
7946     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7947   }
7948 
7949   EVT VT = Ld->getValueType(0);
7950   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7951 
7952   DCI.AddToWorklist(Cvt.getNode());
7953 
7954   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7955   // the appropriate extension from the 32-bit load.
7956   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7957   DCI.AddToWorklist(Cvt.getNode());
7958 
7959   // Handle conversion back to floating point if necessary.
7960   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7961 
7962   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7963 }
7964 
7965 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7966   SDLoc DL(Op);
7967   LoadSDNode *Load = cast<LoadSDNode>(Op);
7968   ISD::LoadExtType ExtType = Load->getExtensionType();
7969   EVT MemVT = Load->getMemoryVT();
7970 
7971   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7972     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7973       return SDValue();
7974 
7975     // FIXME: Copied from PPC
7976     // First, load into 32 bits, then truncate to 1 bit.
7977 
7978     SDValue Chain = Load->getChain();
7979     SDValue BasePtr = Load->getBasePtr();
7980     MachineMemOperand *MMO = Load->getMemOperand();
7981 
7982     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7983 
7984     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7985                                    BasePtr, RealMemVT, MMO);
7986 
7987     if (!MemVT.isVector()) {
7988       SDValue Ops[] = {
7989         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7990         NewLD.getValue(1)
7991       };
7992 
7993       return DAG.getMergeValues(Ops, DL);
7994     }
7995 
7996     SmallVector<SDValue, 3> Elts;
7997     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7998       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7999                                 DAG.getConstant(I, DL, MVT::i32));
8000 
8001       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8002     }
8003 
8004     SDValue Ops[] = {
8005       DAG.getBuildVector(MemVT, DL, Elts),
8006       NewLD.getValue(1)
8007     };
8008 
8009     return DAG.getMergeValues(Ops, DL);
8010   }
8011 
8012   if (!MemVT.isVector())
8013     return SDValue();
8014 
8015   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8016          "Custom lowering for non-i32 vectors hasn't been implemented.");
8017 
8018   unsigned Alignment = Load->getAlignment();
8019   unsigned AS = Load->getAddressSpace();
8020   if (Subtarget->hasLDSMisalignedBug() &&
8021       AS == AMDGPUAS::FLAT_ADDRESS &&
8022       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8023     return SplitVectorLoad(Op, DAG);
8024   }
8025 
8026   MachineFunction &MF = DAG.getMachineFunction();
8027   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8028   // If there is a possibilty that flat instruction access scratch memory
8029   // then we need to use the same legalization rules we use for private.
8030   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8031       !Subtarget->hasMultiDwordFlatScratchAddressing())
8032     AS = MFI->hasFlatScratchInit() ?
8033          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8034 
8035   unsigned NumElements = MemVT.getVectorNumElements();
8036 
8037   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8038       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8039     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8040       if (MemVT.isPow2VectorType())
8041         return SDValue();
8042       return WidenOrSplitVectorLoad(Op, DAG);
8043     }
8044     // Non-uniform loads will be selected to MUBUF instructions, so they
8045     // have the same legalization requirements as global and private
8046     // loads.
8047     //
8048   }
8049 
8050   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8051       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8052       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8053     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8054         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8055         Alignment >= 4 && NumElements < 32) {
8056       if (MemVT.isPow2VectorType())
8057         return SDValue();
8058       return WidenOrSplitVectorLoad(Op, DAG);
8059     }
8060     // Non-uniform loads will be selected to MUBUF instructions, so they
8061     // have the same legalization requirements as global and private
8062     // loads.
8063     //
8064   }
8065   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8066       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8067       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8068       AS == AMDGPUAS::FLAT_ADDRESS) {
8069     if (NumElements > 4)
8070       return SplitVectorLoad(Op, DAG);
8071     // v3 loads not supported on SI.
8072     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8073       return WidenOrSplitVectorLoad(Op, DAG);
8074 
8075     // v3 and v4 loads are supported for private and global memory.
8076     return SDValue();
8077   }
8078   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8079     // Depending on the setting of the private_element_size field in the
8080     // resource descriptor, we can only make private accesses up to a certain
8081     // size.
8082     switch (Subtarget->getMaxPrivateElementSize()) {
8083     case 4: {
8084       SDValue Ops[2];
8085       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8086       return DAG.getMergeValues(Ops, DL);
8087     }
8088     case 8:
8089       if (NumElements > 2)
8090         return SplitVectorLoad(Op, DAG);
8091       return SDValue();
8092     case 16:
8093       // Same as global/flat
8094       if (NumElements > 4)
8095         return SplitVectorLoad(Op, DAG);
8096       // v3 loads not supported on SI.
8097       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8098         return WidenOrSplitVectorLoad(Op, DAG);
8099 
8100       return SDValue();
8101     default:
8102       llvm_unreachable("unsupported private_element_size");
8103     }
8104   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8105     // Use ds_read_b128 or ds_read_b96 when possible.
8106     if (Subtarget->hasDS96AndDS128() &&
8107         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8108          MemVT.getStoreSize() == 12) &&
8109         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8110                                            Load->getAlign()))
8111       return SDValue();
8112 
8113     if (NumElements > 2)
8114       return SplitVectorLoad(Op, DAG);
8115 
8116     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8117     // address is negative, then the instruction is incorrectly treated as
8118     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8119     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8120     // load later in the SILoadStoreOptimizer.
8121     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8122         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8123         Load->getAlignment() < 8) {
8124       return SplitVectorLoad(Op, DAG);
8125     }
8126   }
8127 
8128   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8129                                       MemVT, *Load->getMemOperand())) {
8130     SDValue Ops[2];
8131     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8132     return DAG.getMergeValues(Ops, DL);
8133   }
8134 
8135   return SDValue();
8136 }
8137 
8138 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8139   EVT VT = Op.getValueType();
8140   assert(VT.getSizeInBits() == 64);
8141 
8142   SDLoc DL(Op);
8143   SDValue Cond = Op.getOperand(0);
8144 
8145   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8146   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8147 
8148   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8149   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8150 
8151   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8152   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8153 
8154   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8155 
8156   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8157   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8158 
8159   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8160 
8161   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8162   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8163 }
8164 
8165 // Catch division cases where we can use shortcuts with rcp and rsq
8166 // instructions.
8167 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8168                                               SelectionDAG &DAG) const {
8169   SDLoc SL(Op);
8170   SDValue LHS = Op.getOperand(0);
8171   SDValue RHS = Op.getOperand(1);
8172   EVT VT = Op.getValueType();
8173   const SDNodeFlags Flags = Op->getFlags();
8174 
8175   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8176 
8177   // Without !fpmath accuracy information, we can't do more because we don't
8178   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8179   if (!AllowInaccurateRcp)
8180     return SDValue();
8181 
8182   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8183     if (CLHS->isExactlyValue(1.0)) {
8184       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8185       // the CI documentation has a worst case error of 1 ulp.
8186       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8187       // use it as long as we aren't trying to use denormals.
8188       //
8189       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8190 
8191       // 1.0 / sqrt(x) -> rsq(x)
8192 
8193       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8194       // error seems really high at 2^29 ULP.
8195       if (RHS.getOpcode() == ISD::FSQRT)
8196         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8197 
8198       // 1.0 / x -> rcp(x)
8199       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8200     }
8201 
8202     // Same as for 1.0, but expand the sign out of the constant.
8203     if (CLHS->isExactlyValue(-1.0)) {
8204       // -1.0 / x -> rcp (fneg x)
8205       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8206       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8207     }
8208   }
8209 
8210   // Turn into multiply by the reciprocal.
8211   // x / y -> x * (1.0 / y)
8212   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8213   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8214 }
8215 
8216 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8217                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8218                           SDNodeFlags Flags) {
8219   if (GlueChain->getNumValues() <= 1) {
8220     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8221   }
8222 
8223   assert(GlueChain->getNumValues() == 3);
8224 
8225   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8226   switch (Opcode) {
8227   default: llvm_unreachable("no chain equivalent for opcode");
8228   case ISD::FMUL:
8229     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8230     break;
8231   }
8232 
8233   return DAG.getNode(Opcode, SL, VTList,
8234                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8235                      Flags);
8236 }
8237 
8238 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8239                            EVT VT, SDValue A, SDValue B, SDValue C,
8240                            SDValue GlueChain, SDNodeFlags Flags) {
8241   if (GlueChain->getNumValues() <= 1) {
8242     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8243   }
8244 
8245   assert(GlueChain->getNumValues() == 3);
8246 
8247   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8248   switch (Opcode) {
8249   default: llvm_unreachable("no chain equivalent for opcode");
8250   case ISD::FMA:
8251     Opcode = AMDGPUISD::FMA_W_CHAIN;
8252     break;
8253   }
8254 
8255   return DAG.getNode(Opcode, SL, VTList,
8256                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8257                      Flags);
8258 }
8259 
8260 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8261   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8262     return FastLowered;
8263 
8264   SDLoc SL(Op);
8265   SDValue Src0 = Op.getOperand(0);
8266   SDValue Src1 = Op.getOperand(1);
8267 
8268   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8269   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8270 
8271   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8272   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8273 
8274   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8275   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8276 
8277   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8278 }
8279 
8280 // Faster 2.5 ULP division that does not support denormals.
8281 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8282   SDLoc SL(Op);
8283   SDValue LHS = Op.getOperand(1);
8284   SDValue RHS = Op.getOperand(2);
8285 
8286   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8287 
8288   const APFloat K0Val(BitsToFloat(0x6f800000));
8289   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8290 
8291   const APFloat K1Val(BitsToFloat(0x2f800000));
8292   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8293 
8294   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8295 
8296   EVT SetCCVT =
8297     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8298 
8299   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8300 
8301   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8302 
8303   // TODO: Should this propagate fast-math-flags?
8304   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8305 
8306   // rcp does not support denormals.
8307   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8308 
8309   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8310 
8311   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8312 }
8313 
8314 // Returns immediate value for setting the F32 denorm mode when using the
8315 // S_DENORM_MODE instruction.
8316 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8317                                           const SDLoc &SL, const GCNSubtarget *ST) {
8318   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8319   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8320                                 ? FP_DENORM_FLUSH_NONE
8321                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8322 
8323   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8324   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8325 }
8326 
8327 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8328   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8329     return FastLowered;
8330 
8331   // The selection matcher assumes anything with a chain selecting to a
8332   // mayRaiseFPException machine instruction. Since we're introducing a chain
8333   // here, we need to explicitly report nofpexcept for the regular fdiv
8334   // lowering.
8335   SDNodeFlags Flags = Op->getFlags();
8336   Flags.setNoFPExcept(true);
8337 
8338   SDLoc SL(Op);
8339   SDValue LHS = Op.getOperand(0);
8340   SDValue RHS = Op.getOperand(1);
8341 
8342   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8343 
8344   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8345 
8346   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8347                                           {RHS, RHS, LHS}, Flags);
8348   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8349                                         {LHS, RHS, LHS}, Flags);
8350 
8351   // Denominator is scaled to not be denormal, so using rcp is ok.
8352   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8353                                   DenominatorScaled, Flags);
8354   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8355                                      DenominatorScaled, Flags);
8356 
8357   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8358                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8359                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8360   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8361 
8362   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8363 
8364   if (!HasFP32Denormals) {
8365     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8366     // lowering. The chain dependence is insufficient, and we need glue. We do
8367     // not need the glue variants in a strictfp function.
8368 
8369     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8370 
8371     SDNode *EnableDenorm;
8372     if (Subtarget->hasDenormModeInst()) {
8373       const SDValue EnableDenormValue =
8374           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8375 
8376       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8377                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8378     } else {
8379       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8380                                                         SL, MVT::i32);
8381       EnableDenorm =
8382           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8383                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8384     }
8385 
8386     SDValue Ops[3] = {
8387       NegDivScale0,
8388       SDValue(EnableDenorm, 0),
8389       SDValue(EnableDenorm, 1)
8390     };
8391 
8392     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8393   }
8394 
8395   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8396                              ApproxRcp, One, NegDivScale0, Flags);
8397 
8398   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8399                              ApproxRcp, Fma0, Flags);
8400 
8401   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8402                            Fma1, Fma1, Flags);
8403 
8404   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8405                              NumeratorScaled, Mul, Flags);
8406 
8407   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8408                              Fma2, Fma1, Mul, Fma2, Flags);
8409 
8410   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8411                              NumeratorScaled, Fma3, Flags);
8412 
8413   if (!HasFP32Denormals) {
8414     SDNode *DisableDenorm;
8415     if (Subtarget->hasDenormModeInst()) {
8416       const SDValue DisableDenormValue =
8417           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8418 
8419       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8420                                   Fma4.getValue(1), DisableDenormValue,
8421                                   Fma4.getValue(2)).getNode();
8422     } else {
8423       const SDValue DisableDenormValue =
8424           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8425 
8426       DisableDenorm = DAG.getMachineNode(
8427           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8428           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8429     }
8430 
8431     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8432                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8433     DAG.setRoot(OutputChain);
8434   }
8435 
8436   SDValue Scale = NumeratorScaled.getValue(1);
8437   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8438                              {Fma4, Fma1, Fma3, Scale}, Flags);
8439 
8440   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8441 }
8442 
8443 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8444   if (DAG.getTarget().Options.UnsafeFPMath)
8445     return lowerFastUnsafeFDIV(Op, DAG);
8446 
8447   SDLoc SL(Op);
8448   SDValue X = Op.getOperand(0);
8449   SDValue Y = Op.getOperand(1);
8450 
8451   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8452 
8453   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8454 
8455   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8456 
8457   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8458 
8459   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8460 
8461   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8462 
8463   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8464 
8465   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8466 
8467   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8468 
8469   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8470   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8471 
8472   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8473                              NegDivScale0, Mul, DivScale1);
8474 
8475   SDValue Scale;
8476 
8477   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8478     // Workaround a hardware bug on SI where the condition output from div_scale
8479     // is not usable.
8480 
8481     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8482 
8483     // Figure out if the scale to use for div_fmas.
8484     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8485     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8486     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8487     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8488 
8489     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8490     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8491 
8492     SDValue Scale0Hi
8493       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8494     SDValue Scale1Hi
8495       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8496 
8497     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8498     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8499     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8500   } else {
8501     Scale = DivScale1.getValue(1);
8502   }
8503 
8504   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8505                              Fma4, Fma3, Mul, Scale);
8506 
8507   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8508 }
8509 
8510 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8511   EVT VT = Op.getValueType();
8512 
8513   if (VT == MVT::f32)
8514     return LowerFDIV32(Op, DAG);
8515 
8516   if (VT == MVT::f64)
8517     return LowerFDIV64(Op, DAG);
8518 
8519   if (VT == MVT::f16)
8520     return LowerFDIV16(Op, DAG);
8521 
8522   llvm_unreachable("Unexpected type for fdiv");
8523 }
8524 
8525 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8526   SDLoc DL(Op);
8527   StoreSDNode *Store = cast<StoreSDNode>(Op);
8528   EVT VT = Store->getMemoryVT();
8529 
8530   if (VT == MVT::i1) {
8531     return DAG.getTruncStore(Store->getChain(), DL,
8532        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8533        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8534   }
8535 
8536   assert(VT.isVector() &&
8537          Store->getValue().getValueType().getScalarType() == MVT::i32);
8538 
8539   unsigned AS = Store->getAddressSpace();
8540   if (Subtarget->hasLDSMisalignedBug() &&
8541       AS == AMDGPUAS::FLAT_ADDRESS &&
8542       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8543     return SplitVectorStore(Op, DAG);
8544   }
8545 
8546   MachineFunction &MF = DAG.getMachineFunction();
8547   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8548   // If there is a possibilty that flat instruction access scratch memory
8549   // then we need to use the same legalization rules we use for private.
8550   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8551       !Subtarget->hasMultiDwordFlatScratchAddressing())
8552     AS = MFI->hasFlatScratchInit() ?
8553          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8554 
8555   unsigned NumElements = VT.getVectorNumElements();
8556   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8557       AS == AMDGPUAS::FLAT_ADDRESS) {
8558     if (NumElements > 4)
8559       return SplitVectorStore(Op, DAG);
8560     // v3 stores not supported on SI.
8561     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8562       return SplitVectorStore(Op, DAG);
8563 
8564     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8565                                         VT, *Store->getMemOperand()))
8566       return expandUnalignedStore(Store, DAG);
8567 
8568     return SDValue();
8569   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8570     switch (Subtarget->getMaxPrivateElementSize()) {
8571     case 4:
8572       return scalarizeVectorStore(Store, DAG);
8573     case 8:
8574       if (NumElements > 2)
8575         return SplitVectorStore(Op, DAG);
8576       return SDValue();
8577     case 16:
8578       if (NumElements > 4 ||
8579           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8580         return SplitVectorStore(Op, DAG);
8581       return SDValue();
8582     default:
8583       llvm_unreachable("unsupported private_element_size");
8584     }
8585   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8586     // Use ds_write_b128 or ds_write_b96 when possible.
8587     if (Subtarget->hasDS96AndDS128() &&
8588         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8589          (VT.getStoreSize() == 12)) &&
8590         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8591                                            Store->getAlign()))
8592       return SDValue();
8593 
8594     if (NumElements > 2)
8595       return SplitVectorStore(Op, DAG);
8596 
8597     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8598     // address is negative, then the instruction is incorrectly treated as
8599     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8600     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8601     // store later in the SILoadStoreOptimizer.
8602     if (!Subtarget->hasUsableDSOffset() &&
8603         NumElements == 2 && VT.getStoreSize() == 8 &&
8604         Store->getAlignment() < 8) {
8605       return SplitVectorStore(Op, DAG);
8606     }
8607 
8608     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8609                                         VT, *Store->getMemOperand())) {
8610       if (VT.isVector())
8611         return SplitVectorStore(Op, DAG);
8612       return expandUnalignedStore(Store, DAG);
8613     }
8614 
8615     return SDValue();
8616   } else {
8617     llvm_unreachable("unhandled address space");
8618   }
8619 }
8620 
8621 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8622   SDLoc DL(Op);
8623   EVT VT = Op.getValueType();
8624   SDValue Arg = Op.getOperand(0);
8625   SDValue TrigVal;
8626 
8627   // Propagate fast-math flags so that the multiply we introduce can be folded
8628   // if Arg is already the result of a multiply by constant.
8629   auto Flags = Op->getFlags();
8630 
8631   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8632 
8633   if (Subtarget->hasTrigReducedRange()) {
8634     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8635     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8636   } else {
8637     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8638   }
8639 
8640   switch (Op.getOpcode()) {
8641   case ISD::FCOS:
8642     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8643   case ISD::FSIN:
8644     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8645   default:
8646     llvm_unreachable("Wrong trig opcode");
8647   }
8648 }
8649 
8650 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8651   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8652   assert(AtomicNode->isCompareAndSwap());
8653   unsigned AS = AtomicNode->getAddressSpace();
8654 
8655   // No custom lowering required for local address space
8656   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8657     return Op;
8658 
8659   // Non-local address space requires custom lowering for atomic compare
8660   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8661   SDLoc DL(Op);
8662   SDValue ChainIn = Op.getOperand(0);
8663   SDValue Addr = Op.getOperand(1);
8664   SDValue Old = Op.getOperand(2);
8665   SDValue New = Op.getOperand(3);
8666   EVT VT = Op.getValueType();
8667   MVT SimpleVT = VT.getSimpleVT();
8668   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8669 
8670   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8671   SDValue Ops[] = { ChainIn, Addr, NewOld };
8672 
8673   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8674                                  Ops, VT, AtomicNode->getMemOperand());
8675 }
8676 
8677 //===----------------------------------------------------------------------===//
8678 // Custom DAG optimizations
8679 //===----------------------------------------------------------------------===//
8680 
8681 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8682                                                      DAGCombinerInfo &DCI) const {
8683   EVT VT = N->getValueType(0);
8684   EVT ScalarVT = VT.getScalarType();
8685   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8686     return SDValue();
8687 
8688   SelectionDAG &DAG = DCI.DAG;
8689   SDLoc DL(N);
8690 
8691   SDValue Src = N->getOperand(0);
8692   EVT SrcVT = Src.getValueType();
8693 
8694   // TODO: We could try to match extracting the higher bytes, which would be
8695   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8696   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8697   // about in practice.
8698   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8699     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8700       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8701       DCI.AddToWorklist(Cvt.getNode());
8702 
8703       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8704       if (ScalarVT != MVT::f32) {
8705         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8706                           DAG.getTargetConstant(0, DL, MVT::i32));
8707       }
8708       return Cvt;
8709     }
8710   }
8711 
8712   return SDValue();
8713 }
8714 
8715 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8716 
8717 // This is a variant of
8718 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8719 //
8720 // The normal DAG combiner will do this, but only if the add has one use since
8721 // that would increase the number of instructions.
8722 //
8723 // This prevents us from seeing a constant offset that can be folded into a
8724 // memory instruction's addressing mode. If we know the resulting add offset of
8725 // a pointer can be folded into an addressing offset, we can replace the pointer
8726 // operand with the add of new constant offset. This eliminates one of the uses,
8727 // and may allow the remaining use to also be simplified.
8728 //
8729 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8730                                                unsigned AddrSpace,
8731                                                EVT MemVT,
8732                                                DAGCombinerInfo &DCI) const {
8733   SDValue N0 = N->getOperand(0);
8734   SDValue N1 = N->getOperand(1);
8735 
8736   // We only do this to handle cases where it's profitable when there are
8737   // multiple uses of the add, so defer to the standard combine.
8738   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8739       N0->hasOneUse())
8740     return SDValue();
8741 
8742   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8743   if (!CN1)
8744     return SDValue();
8745 
8746   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8747   if (!CAdd)
8748     return SDValue();
8749 
8750   // If the resulting offset is too large, we can't fold it into the addressing
8751   // mode offset.
8752   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8753   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8754 
8755   AddrMode AM;
8756   AM.HasBaseReg = true;
8757   AM.BaseOffs = Offset.getSExtValue();
8758   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8759     return SDValue();
8760 
8761   SelectionDAG &DAG = DCI.DAG;
8762   SDLoc SL(N);
8763   EVT VT = N->getValueType(0);
8764 
8765   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8766   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8767 
8768   SDNodeFlags Flags;
8769   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8770                           (N0.getOpcode() == ISD::OR ||
8771                            N0->getFlags().hasNoUnsignedWrap()));
8772 
8773   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8774 }
8775 
8776 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8777 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8778 /// specific intrinsic, but they all place the pointer operand first.
8779 static unsigned getBasePtrIndex(const MemSDNode *N) {
8780   switch (N->getOpcode()) {
8781   case ISD::STORE:
8782   case ISD::INTRINSIC_W_CHAIN:
8783   case ISD::INTRINSIC_VOID:
8784     return 2;
8785   default:
8786     return 1;
8787   }
8788 }
8789 
8790 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8791                                                   DAGCombinerInfo &DCI) const {
8792   SelectionDAG &DAG = DCI.DAG;
8793   SDLoc SL(N);
8794 
8795   unsigned PtrIdx = getBasePtrIndex(N);
8796   SDValue Ptr = N->getOperand(PtrIdx);
8797 
8798   // TODO: We could also do this for multiplies.
8799   if (Ptr.getOpcode() == ISD::SHL) {
8800     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8801                                           N->getMemoryVT(), DCI);
8802     if (NewPtr) {
8803       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8804 
8805       NewOps[PtrIdx] = NewPtr;
8806       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8807     }
8808   }
8809 
8810   return SDValue();
8811 }
8812 
8813 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8814   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8815          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8816          (Opc == ISD::XOR && Val == 0);
8817 }
8818 
8819 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8820 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8821 // integer combine opportunities since most 64-bit operations are decomposed
8822 // this way.  TODO: We won't want this for SALU especially if it is an inline
8823 // immediate.
8824 SDValue SITargetLowering::splitBinaryBitConstantOp(
8825   DAGCombinerInfo &DCI,
8826   const SDLoc &SL,
8827   unsigned Opc, SDValue LHS,
8828   const ConstantSDNode *CRHS) const {
8829   uint64_t Val = CRHS->getZExtValue();
8830   uint32_t ValLo = Lo_32(Val);
8831   uint32_t ValHi = Hi_32(Val);
8832   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8833 
8834     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8835          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8836         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8837     // If we need to materialize a 64-bit immediate, it will be split up later
8838     // anyway. Avoid creating the harder to understand 64-bit immediate
8839     // materialization.
8840     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8841   }
8842 
8843   return SDValue();
8844 }
8845 
8846 // Returns true if argument is a boolean value which is not serialized into
8847 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8848 static bool isBoolSGPR(SDValue V) {
8849   if (V.getValueType() != MVT::i1)
8850     return false;
8851   switch (V.getOpcode()) {
8852   default: break;
8853   case ISD::SETCC:
8854   case ISD::AND:
8855   case ISD::OR:
8856   case ISD::XOR:
8857   case AMDGPUISD::FP_CLASS:
8858     return true;
8859   }
8860   return false;
8861 }
8862 
8863 // If a constant has all zeroes or all ones within each byte return it.
8864 // Otherwise return 0.
8865 static uint32_t getConstantPermuteMask(uint32_t C) {
8866   // 0xff for any zero byte in the mask
8867   uint32_t ZeroByteMask = 0;
8868   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8869   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8870   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8871   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8872   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8873   if ((NonZeroByteMask & C) != NonZeroByteMask)
8874     return 0; // Partial bytes selected.
8875   return C;
8876 }
8877 
8878 // Check if a node selects whole bytes from its operand 0 starting at a byte
8879 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8880 // or -1 if not succeeded.
8881 // Note byte select encoding:
8882 // value 0-3 selects corresponding source byte;
8883 // value 0xc selects zero;
8884 // value 0xff selects 0xff.
8885 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8886   assert(V.getValueSizeInBits() == 32);
8887 
8888   if (V.getNumOperands() != 2)
8889     return ~0;
8890 
8891   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8892   if (!N1)
8893     return ~0;
8894 
8895   uint32_t C = N1->getZExtValue();
8896 
8897   switch (V.getOpcode()) {
8898   default:
8899     break;
8900   case ISD::AND:
8901     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8902       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8903     }
8904     break;
8905 
8906   case ISD::OR:
8907     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8908       return (0x03020100 & ~ConstMask) | ConstMask;
8909     }
8910     break;
8911 
8912   case ISD::SHL:
8913     if (C % 8)
8914       return ~0;
8915 
8916     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8917 
8918   case ISD::SRL:
8919     if (C % 8)
8920       return ~0;
8921 
8922     return uint32_t(0x0c0c0c0c03020100ull >> C);
8923   }
8924 
8925   return ~0;
8926 }
8927 
8928 SDValue SITargetLowering::performAndCombine(SDNode *N,
8929                                             DAGCombinerInfo &DCI) const {
8930   if (DCI.isBeforeLegalize())
8931     return SDValue();
8932 
8933   SelectionDAG &DAG = DCI.DAG;
8934   EVT VT = N->getValueType(0);
8935   SDValue LHS = N->getOperand(0);
8936   SDValue RHS = N->getOperand(1);
8937 
8938 
8939   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8940   if (VT == MVT::i64 && CRHS) {
8941     if (SDValue Split
8942         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8943       return Split;
8944   }
8945 
8946   if (CRHS && VT == MVT::i32) {
8947     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8948     // nb = number of trailing zeroes in mask
8949     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8950     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8951     uint64_t Mask = CRHS->getZExtValue();
8952     unsigned Bits = countPopulation(Mask);
8953     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8954         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8955       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8956         unsigned Shift = CShift->getZExtValue();
8957         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8958         unsigned Offset = NB + Shift;
8959         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8960           SDLoc SL(N);
8961           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8962                                     LHS->getOperand(0),
8963                                     DAG.getConstant(Offset, SL, MVT::i32),
8964                                     DAG.getConstant(Bits, SL, MVT::i32));
8965           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8966           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8967                                     DAG.getValueType(NarrowVT));
8968           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8969                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8970           return Shl;
8971         }
8972       }
8973     }
8974 
8975     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8976     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8977         isa<ConstantSDNode>(LHS.getOperand(2))) {
8978       uint32_t Sel = getConstantPermuteMask(Mask);
8979       if (!Sel)
8980         return SDValue();
8981 
8982       // Select 0xc for all zero bytes
8983       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8984       SDLoc DL(N);
8985       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8986                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8987     }
8988   }
8989 
8990   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8991   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8992   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8993     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8994     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8995 
8996     SDValue X = LHS.getOperand(0);
8997     SDValue Y = RHS.getOperand(0);
8998     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8999       return SDValue();
9000 
9001     if (LCC == ISD::SETO) {
9002       if (X != LHS.getOperand(1))
9003         return SDValue();
9004 
9005       if (RCC == ISD::SETUNE) {
9006         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9007         if (!C1 || !C1->isInfinity() || C1->isNegative())
9008           return SDValue();
9009 
9010         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9011                               SIInstrFlags::N_SUBNORMAL |
9012                               SIInstrFlags::N_ZERO |
9013                               SIInstrFlags::P_ZERO |
9014                               SIInstrFlags::P_SUBNORMAL |
9015                               SIInstrFlags::P_NORMAL;
9016 
9017         static_assert(((~(SIInstrFlags::S_NAN |
9018                           SIInstrFlags::Q_NAN |
9019                           SIInstrFlags::N_INFINITY |
9020                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9021                       "mask not equal");
9022 
9023         SDLoc DL(N);
9024         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9025                            X, DAG.getConstant(Mask, DL, MVT::i32));
9026       }
9027     }
9028   }
9029 
9030   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9031     std::swap(LHS, RHS);
9032 
9033   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9034       RHS.hasOneUse()) {
9035     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9036     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9037     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9038     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9039     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9040         (RHS.getOperand(0) == LHS.getOperand(0) &&
9041          LHS.getOperand(0) == LHS.getOperand(1))) {
9042       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9043       unsigned NewMask = LCC == ISD::SETO ?
9044         Mask->getZExtValue() & ~OrdMask :
9045         Mask->getZExtValue() & OrdMask;
9046 
9047       SDLoc DL(N);
9048       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9049                          DAG.getConstant(NewMask, DL, MVT::i32));
9050     }
9051   }
9052 
9053   if (VT == MVT::i32 &&
9054       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9055     // and x, (sext cc from i1) => select cc, x, 0
9056     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9057       std::swap(LHS, RHS);
9058     if (isBoolSGPR(RHS.getOperand(0)))
9059       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9060                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9061   }
9062 
9063   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9064   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9065   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9066       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9067     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9068     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9069     if (LHSMask != ~0u && RHSMask != ~0u) {
9070       // Canonicalize the expression in an attempt to have fewer unique masks
9071       // and therefore fewer registers used to hold the masks.
9072       if (LHSMask > RHSMask) {
9073         std::swap(LHSMask, RHSMask);
9074         std::swap(LHS, RHS);
9075       }
9076 
9077       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9078       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9079       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9080       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9081 
9082       // Check of we need to combine values from two sources within a byte.
9083       if (!(LHSUsedLanes & RHSUsedLanes) &&
9084           // If we select high and lower word keep it for SDWA.
9085           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9086           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9087         // Each byte in each mask is either selector mask 0-3, or has higher
9088         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9089         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9090         // mask which is not 0xff wins. By anding both masks we have a correct
9091         // result except that 0x0c shall be corrected to give 0x0c only.
9092         uint32_t Mask = LHSMask & RHSMask;
9093         for (unsigned I = 0; I < 32; I += 8) {
9094           uint32_t ByteSel = 0xff << I;
9095           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9096             Mask &= (0x0c << I) & 0xffffffff;
9097         }
9098 
9099         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9100         // or 0x0c.
9101         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9102         SDLoc DL(N);
9103 
9104         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9105                            LHS.getOperand(0), RHS.getOperand(0),
9106                            DAG.getConstant(Sel, DL, MVT::i32));
9107       }
9108     }
9109   }
9110 
9111   return SDValue();
9112 }
9113 
9114 SDValue SITargetLowering::performOrCombine(SDNode *N,
9115                                            DAGCombinerInfo &DCI) const {
9116   SelectionDAG &DAG = DCI.DAG;
9117   SDValue LHS = N->getOperand(0);
9118   SDValue RHS = N->getOperand(1);
9119 
9120   EVT VT = N->getValueType(0);
9121   if (VT == MVT::i1) {
9122     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9123     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9124         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9125       SDValue Src = LHS.getOperand(0);
9126       if (Src != RHS.getOperand(0))
9127         return SDValue();
9128 
9129       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9130       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9131       if (!CLHS || !CRHS)
9132         return SDValue();
9133 
9134       // Only 10 bits are used.
9135       static const uint32_t MaxMask = 0x3ff;
9136 
9137       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9138       SDLoc DL(N);
9139       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9140                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9141     }
9142 
9143     return SDValue();
9144   }
9145 
9146   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9147   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9148       LHS.getOpcode() == AMDGPUISD::PERM &&
9149       isa<ConstantSDNode>(LHS.getOperand(2))) {
9150     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9151     if (!Sel)
9152       return SDValue();
9153 
9154     Sel |= LHS.getConstantOperandVal(2);
9155     SDLoc DL(N);
9156     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9157                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9158   }
9159 
9160   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9161   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9162   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9163       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9164     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9165     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9166     if (LHSMask != ~0u && RHSMask != ~0u) {
9167       // Canonicalize the expression in an attempt to have fewer unique masks
9168       // and therefore fewer registers used to hold the masks.
9169       if (LHSMask > RHSMask) {
9170         std::swap(LHSMask, RHSMask);
9171         std::swap(LHS, RHS);
9172       }
9173 
9174       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9175       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9176       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9177       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9178 
9179       // Check of we need to combine values from two sources within a byte.
9180       if (!(LHSUsedLanes & RHSUsedLanes) &&
9181           // If we select high and lower word keep it for SDWA.
9182           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9183           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9184         // Kill zero bytes selected by other mask. Zero value is 0xc.
9185         LHSMask &= ~RHSUsedLanes;
9186         RHSMask &= ~LHSUsedLanes;
9187         // Add 4 to each active LHS lane
9188         LHSMask |= LHSUsedLanes & 0x04040404;
9189         // Combine masks
9190         uint32_t Sel = LHSMask | RHSMask;
9191         SDLoc DL(N);
9192 
9193         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9194                            LHS.getOperand(0), RHS.getOperand(0),
9195                            DAG.getConstant(Sel, DL, MVT::i32));
9196       }
9197     }
9198   }
9199 
9200   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9201     return SDValue();
9202 
9203   // TODO: This could be a generic combine with a predicate for extracting the
9204   // high half of an integer being free.
9205 
9206   // (or i64:x, (zero_extend i32:y)) ->
9207   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9208   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9209       RHS.getOpcode() != ISD::ZERO_EXTEND)
9210     std::swap(LHS, RHS);
9211 
9212   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9213     SDValue ExtSrc = RHS.getOperand(0);
9214     EVT SrcVT = ExtSrc.getValueType();
9215     if (SrcVT == MVT::i32) {
9216       SDLoc SL(N);
9217       SDValue LowLHS, HiBits;
9218       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9219       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9220 
9221       DCI.AddToWorklist(LowOr.getNode());
9222       DCI.AddToWorklist(HiBits.getNode());
9223 
9224       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9225                                 LowOr, HiBits);
9226       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9227     }
9228   }
9229 
9230   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9231   if (CRHS) {
9232     if (SDValue Split
9233           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9234       return Split;
9235   }
9236 
9237   return SDValue();
9238 }
9239 
9240 SDValue SITargetLowering::performXorCombine(SDNode *N,
9241                                             DAGCombinerInfo &DCI) const {
9242   EVT VT = N->getValueType(0);
9243   if (VT != MVT::i64)
9244     return SDValue();
9245 
9246   SDValue LHS = N->getOperand(0);
9247   SDValue RHS = N->getOperand(1);
9248 
9249   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9250   if (CRHS) {
9251     if (SDValue Split
9252           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9253       return Split;
9254   }
9255 
9256   return SDValue();
9257 }
9258 
9259 // Instructions that will be lowered with a final instruction that zeros the
9260 // high result bits.
9261 // XXX - probably only need to list legal operations.
9262 static bool fp16SrcZerosHighBits(unsigned Opc) {
9263   switch (Opc) {
9264   case ISD::FADD:
9265   case ISD::FSUB:
9266   case ISD::FMUL:
9267   case ISD::FDIV:
9268   case ISD::FREM:
9269   case ISD::FMA:
9270   case ISD::FMAD:
9271   case ISD::FCANONICALIZE:
9272   case ISD::FP_ROUND:
9273   case ISD::UINT_TO_FP:
9274   case ISD::SINT_TO_FP:
9275   case ISD::FABS:
9276     // Fabs is lowered to a bit operation, but it's an and which will clear the
9277     // high bits anyway.
9278   case ISD::FSQRT:
9279   case ISD::FSIN:
9280   case ISD::FCOS:
9281   case ISD::FPOWI:
9282   case ISD::FPOW:
9283   case ISD::FLOG:
9284   case ISD::FLOG2:
9285   case ISD::FLOG10:
9286   case ISD::FEXP:
9287   case ISD::FEXP2:
9288   case ISD::FCEIL:
9289   case ISD::FTRUNC:
9290   case ISD::FRINT:
9291   case ISD::FNEARBYINT:
9292   case ISD::FROUND:
9293   case ISD::FFLOOR:
9294   case ISD::FMINNUM:
9295   case ISD::FMAXNUM:
9296   case AMDGPUISD::FRACT:
9297   case AMDGPUISD::CLAMP:
9298   case AMDGPUISD::COS_HW:
9299   case AMDGPUISD::SIN_HW:
9300   case AMDGPUISD::FMIN3:
9301   case AMDGPUISD::FMAX3:
9302   case AMDGPUISD::FMED3:
9303   case AMDGPUISD::FMAD_FTZ:
9304   case AMDGPUISD::RCP:
9305   case AMDGPUISD::RSQ:
9306   case AMDGPUISD::RCP_IFLAG:
9307   case AMDGPUISD::LDEXP:
9308     return true;
9309   default:
9310     // fcopysign, select and others may be lowered to 32-bit bit operations
9311     // which don't zero the high bits.
9312     return false;
9313   }
9314 }
9315 
9316 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9317                                                    DAGCombinerInfo &DCI) const {
9318   if (!Subtarget->has16BitInsts() ||
9319       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9320     return SDValue();
9321 
9322   EVT VT = N->getValueType(0);
9323   if (VT != MVT::i32)
9324     return SDValue();
9325 
9326   SDValue Src = N->getOperand(0);
9327   if (Src.getValueType() != MVT::i16)
9328     return SDValue();
9329 
9330   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9331   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9332   if (Src.getOpcode() == ISD::BITCAST) {
9333     SDValue BCSrc = Src.getOperand(0);
9334     if (BCSrc.getValueType() == MVT::f16 &&
9335         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9336       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9337   }
9338 
9339   return SDValue();
9340 }
9341 
9342 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9343                                                         DAGCombinerInfo &DCI)
9344                                                         const {
9345   SDValue Src = N->getOperand(0);
9346   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9347 
9348   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9349       VTSign->getVT() == MVT::i8) ||
9350       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9351       VTSign->getVT() == MVT::i16)) &&
9352       Src.hasOneUse()) {
9353     auto *M = cast<MemSDNode>(Src);
9354     SDValue Ops[] = {
9355       Src.getOperand(0), // Chain
9356       Src.getOperand(1), // rsrc
9357       Src.getOperand(2), // vindex
9358       Src.getOperand(3), // voffset
9359       Src.getOperand(4), // soffset
9360       Src.getOperand(5), // offset
9361       Src.getOperand(6),
9362       Src.getOperand(7)
9363     };
9364     // replace with BUFFER_LOAD_BYTE/SHORT
9365     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9366                                          Src.getOperand(0).getValueType());
9367     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9368                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9369     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9370                                                           ResList,
9371                                                           Ops, M->getMemoryVT(),
9372                                                           M->getMemOperand());
9373     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9374                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9375   }
9376   return SDValue();
9377 }
9378 
9379 SDValue SITargetLowering::performClassCombine(SDNode *N,
9380                                               DAGCombinerInfo &DCI) const {
9381   SelectionDAG &DAG = DCI.DAG;
9382   SDValue Mask = N->getOperand(1);
9383 
9384   // fp_class x, 0 -> false
9385   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9386     if (CMask->isNullValue())
9387       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9388   }
9389 
9390   if (N->getOperand(0).isUndef())
9391     return DAG.getUNDEF(MVT::i1);
9392 
9393   return SDValue();
9394 }
9395 
9396 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9397                                             DAGCombinerInfo &DCI) const {
9398   EVT VT = N->getValueType(0);
9399   SDValue N0 = N->getOperand(0);
9400 
9401   if (N0.isUndef())
9402     return N0;
9403 
9404   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9405                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9406     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9407                            N->getFlags());
9408   }
9409 
9410   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9411     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9412                            N0.getOperand(0), N->getFlags());
9413   }
9414 
9415   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9416 }
9417 
9418 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9419                                        unsigned MaxDepth) const {
9420   unsigned Opcode = Op.getOpcode();
9421   if (Opcode == ISD::FCANONICALIZE)
9422     return true;
9423 
9424   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9425     auto F = CFP->getValueAPF();
9426     if (F.isNaN() && F.isSignaling())
9427       return false;
9428     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9429   }
9430 
9431   // If source is a result of another standard FP operation it is already in
9432   // canonical form.
9433   if (MaxDepth == 0)
9434     return false;
9435 
9436   switch (Opcode) {
9437   // These will flush denorms if required.
9438   case ISD::FADD:
9439   case ISD::FSUB:
9440   case ISD::FMUL:
9441   case ISD::FCEIL:
9442   case ISD::FFLOOR:
9443   case ISD::FMA:
9444   case ISD::FMAD:
9445   case ISD::FSQRT:
9446   case ISD::FDIV:
9447   case ISD::FREM:
9448   case ISD::FP_ROUND:
9449   case ISD::FP_EXTEND:
9450   case AMDGPUISD::FMUL_LEGACY:
9451   case AMDGPUISD::FMAD_FTZ:
9452   case AMDGPUISD::RCP:
9453   case AMDGPUISD::RSQ:
9454   case AMDGPUISD::RSQ_CLAMP:
9455   case AMDGPUISD::RCP_LEGACY:
9456   case AMDGPUISD::RCP_IFLAG:
9457   case AMDGPUISD::DIV_SCALE:
9458   case AMDGPUISD::DIV_FMAS:
9459   case AMDGPUISD::DIV_FIXUP:
9460   case AMDGPUISD::FRACT:
9461   case AMDGPUISD::LDEXP:
9462   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9463   case AMDGPUISD::CVT_F32_UBYTE0:
9464   case AMDGPUISD::CVT_F32_UBYTE1:
9465   case AMDGPUISD::CVT_F32_UBYTE2:
9466   case AMDGPUISD::CVT_F32_UBYTE3:
9467     return true;
9468 
9469   // It can/will be lowered or combined as a bit operation.
9470   // Need to check their input recursively to handle.
9471   case ISD::FNEG:
9472   case ISD::FABS:
9473   case ISD::FCOPYSIGN:
9474     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9475 
9476   case ISD::FSIN:
9477   case ISD::FCOS:
9478   case ISD::FSINCOS:
9479     return Op.getValueType().getScalarType() != MVT::f16;
9480 
9481   case ISD::FMINNUM:
9482   case ISD::FMAXNUM:
9483   case ISD::FMINNUM_IEEE:
9484   case ISD::FMAXNUM_IEEE:
9485   case AMDGPUISD::CLAMP:
9486   case AMDGPUISD::FMED3:
9487   case AMDGPUISD::FMAX3:
9488   case AMDGPUISD::FMIN3: {
9489     // FIXME: Shouldn't treat the generic operations different based these.
9490     // However, we aren't really required to flush the result from
9491     // minnum/maxnum..
9492 
9493     // snans will be quieted, so we only need to worry about denormals.
9494     if (Subtarget->supportsMinMaxDenormModes() ||
9495         denormalsEnabledForType(DAG, Op.getValueType()))
9496       return true;
9497 
9498     // Flushing may be required.
9499     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9500     // targets need to check their input recursively.
9501 
9502     // FIXME: Does this apply with clamp? It's implemented with max.
9503     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9504       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9505         return false;
9506     }
9507 
9508     return true;
9509   }
9510   case ISD::SELECT: {
9511     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9512            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9513   }
9514   case ISD::BUILD_VECTOR: {
9515     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9516       SDValue SrcOp = Op.getOperand(i);
9517       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9518         return false;
9519     }
9520 
9521     return true;
9522   }
9523   case ISD::EXTRACT_VECTOR_ELT:
9524   case ISD::EXTRACT_SUBVECTOR: {
9525     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9526   }
9527   case ISD::INSERT_VECTOR_ELT: {
9528     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9529            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9530   }
9531   case ISD::UNDEF:
9532     // Could be anything.
9533     return false;
9534 
9535   case ISD::BITCAST: {
9536     // Hack round the mess we make when legalizing extract_vector_elt
9537     SDValue Src = Op.getOperand(0);
9538     if (Src.getValueType() == MVT::i16 &&
9539         Src.getOpcode() == ISD::TRUNCATE) {
9540       SDValue TruncSrc = Src.getOperand(0);
9541       if (TruncSrc.getValueType() == MVT::i32 &&
9542           TruncSrc.getOpcode() == ISD::BITCAST &&
9543           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9544         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9545       }
9546     }
9547 
9548     return false;
9549   }
9550   case ISD::INTRINSIC_WO_CHAIN: {
9551     unsigned IntrinsicID
9552       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9553     // TODO: Handle more intrinsics
9554     switch (IntrinsicID) {
9555     case Intrinsic::amdgcn_cvt_pkrtz:
9556     case Intrinsic::amdgcn_cubeid:
9557     case Intrinsic::amdgcn_frexp_mant:
9558     case Intrinsic::amdgcn_fdot2:
9559     case Intrinsic::amdgcn_rcp:
9560     case Intrinsic::amdgcn_rsq:
9561     case Intrinsic::amdgcn_rsq_clamp:
9562     case Intrinsic::amdgcn_rcp_legacy:
9563     case Intrinsic::amdgcn_rsq_legacy:
9564     case Intrinsic::amdgcn_trig_preop:
9565       return true;
9566     default:
9567       break;
9568     }
9569 
9570     LLVM_FALLTHROUGH;
9571   }
9572   default:
9573     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9574            DAG.isKnownNeverSNaN(Op);
9575   }
9576 
9577   llvm_unreachable("invalid operation");
9578 }
9579 
9580 // Constant fold canonicalize.
9581 SDValue SITargetLowering::getCanonicalConstantFP(
9582   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9583   // Flush denormals to 0 if not enabled.
9584   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9585     return DAG.getConstantFP(0.0, SL, VT);
9586 
9587   if (C.isNaN()) {
9588     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9589     if (C.isSignaling()) {
9590       // Quiet a signaling NaN.
9591       // FIXME: Is this supposed to preserve payload bits?
9592       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9593     }
9594 
9595     // Make sure it is the canonical NaN bitpattern.
9596     //
9597     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9598     // immediate?
9599     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9600       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9601   }
9602 
9603   // Already canonical.
9604   return DAG.getConstantFP(C, SL, VT);
9605 }
9606 
9607 static bool vectorEltWillFoldAway(SDValue Op) {
9608   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9609 }
9610 
9611 SDValue SITargetLowering::performFCanonicalizeCombine(
9612   SDNode *N,
9613   DAGCombinerInfo &DCI) const {
9614   SelectionDAG &DAG = DCI.DAG;
9615   SDValue N0 = N->getOperand(0);
9616   EVT VT = N->getValueType(0);
9617 
9618   // fcanonicalize undef -> qnan
9619   if (N0.isUndef()) {
9620     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9621     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9622   }
9623 
9624   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9625     EVT VT = N->getValueType(0);
9626     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9627   }
9628 
9629   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9630   //                                                   (fcanonicalize k)
9631   //
9632   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9633 
9634   // TODO: This could be better with wider vectors that will be split to v2f16,
9635   // and to consider uses since there aren't that many packed operations.
9636   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9637       isTypeLegal(MVT::v2f16)) {
9638     SDLoc SL(N);
9639     SDValue NewElts[2];
9640     SDValue Lo = N0.getOperand(0);
9641     SDValue Hi = N0.getOperand(1);
9642     EVT EltVT = Lo.getValueType();
9643 
9644     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9645       for (unsigned I = 0; I != 2; ++I) {
9646         SDValue Op = N0.getOperand(I);
9647         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9648           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9649                                               CFP->getValueAPF());
9650         } else if (Op.isUndef()) {
9651           // Handled below based on what the other operand is.
9652           NewElts[I] = Op;
9653         } else {
9654           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9655         }
9656       }
9657 
9658       // If one half is undef, and one is constant, perfer a splat vector rather
9659       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9660       // cheaper to use and may be free with a packed operation.
9661       if (NewElts[0].isUndef()) {
9662         if (isa<ConstantFPSDNode>(NewElts[1]))
9663           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9664             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9665       }
9666 
9667       if (NewElts[1].isUndef()) {
9668         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9669           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9670       }
9671 
9672       return DAG.getBuildVector(VT, SL, NewElts);
9673     }
9674   }
9675 
9676   unsigned SrcOpc = N0.getOpcode();
9677 
9678   // If it's free to do so, push canonicalizes further up the source, which may
9679   // find a canonical source.
9680   //
9681   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9682   // sNaNs.
9683   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9684     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9685     if (CRHS && N0.hasOneUse()) {
9686       SDLoc SL(N);
9687       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9688                                    N0.getOperand(0));
9689       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9690       DCI.AddToWorklist(Canon0.getNode());
9691 
9692       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9693     }
9694   }
9695 
9696   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9697 }
9698 
9699 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9700   switch (Opc) {
9701   case ISD::FMAXNUM:
9702   case ISD::FMAXNUM_IEEE:
9703     return AMDGPUISD::FMAX3;
9704   case ISD::SMAX:
9705     return AMDGPUISD::SMAX3;
9706   case ISD::UMAX:
9707     return AMDGPUISD::UMAX3;
9708   case ISD::FMINNUM:
9709   case ISD::FMINNUM_IEEE:
9710     return AMDGPUISD::FMIN3;
9711   case ISD::SMIN:
9712     return AMDGPUISD::SMIN3;
9713   case ISD::UMIN:
9714     return AMDGPUISD::UMIN3;
9715   default:
9716     llvm_unreachable("Not a min/max opcode");
9717   }
9718 }
9719 
9720 SDValue SITargetLowering::performIntMed3ImmCombine(
9721   SelectionDAG &DAG, const SDLoc &SL,
9722   SDValue Op0, SDValue Op1, bool Signed) const {
9723   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9724   if (!K1)
9725     return SDValue();
9726 
9727   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9728   if (!K0)
9729     return SDValue();
9730 
9731   if (Signed) {
9732     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9733       return SDValue();
9734   } else {
9735     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9736       return SDValue();
9737   }
9738 
9739   EVT VT = K0->getValueType(0);
9740   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9741   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9742     return DAG.getNode(Med3Opc, SL, VT,
9743                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9744   }
9745 
9746   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9747   MVT NVT = MVT::i32;
9748   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9749 
9750   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9751   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9752   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9753 
9754   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9755   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9756 }
9757 
9758 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9759   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9760     return C;
9761 
9762   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9763     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9764       return C;
9765   }
9766 
9767   return nullptr;
9768 }
9769 
9770 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9771                                                   const SDLoc &SL,
9772                                                   SDValue Op0,
9773                                                   SDValue Op1) const {
9774   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9775   if (!K1)
9776     return SDValue();
9777 
9778   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9779   if (!K0)
9780     return SDValue();
9781 
9782   // Ordered >= (although NaN inputs should have folded away by now).
9783   if (K0->getValueAPF() > K1->getValueAPF())
9784     return SDValue();
9785 
9786   const MachineFunction &MF = DAG.getMachineFunction();
9787   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9788 
9789   // TODO: Check IEEE bit enabled?
9790   EVT VT = Op0.getValueType();
9791   if (Info->getMode().DX10Clamp) {
9792     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9793     // hardware fmed3 behavior converting to a min.
9794     // FIXME: Should this be allowing -0.0?
9795     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9796       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9797   }
9798 
9799   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9800   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9801     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9802     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9803     // then give the other result, which is different from med3 with a NaN
9804     // input.
9805     SDValue Var = Op0.getOperand(0);
9806     if (!DAG.isKnownNeverSNaN(Var))
9807       return SDValue();
9808 
9809     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9810 
9811     if ((!K0->hasOneUse() ||
9812          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9813         (!K1->hasOneUse() ||
9814          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9815       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9816                          Var, SDValue(K0, 0), SDValue(K1, 0));
9817     }
9818   }
9819 
9820   return SDValue();
9821 }
9822 
9823 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9824                                                DAGCombinerInfo &DCI) const {
9825   SelectionDAG &DAG = DCI.DAG;
9826 
9827   EVT VT = N->getValueType(0);
9828   unsigned Opc = N->getOpcode();
9829   SDValue Op0 = N->getOperand(0);
9830   SDValue Op1 = N->getOperand(1);
9831 
9832   // Only do this if the inner op has one use since this will just increases
9833   // register pressure for no benefit.
9834 
9835   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9836       !VT.isVector() &&
9837       (VT == MVT::i32 || VT == MVT::f32 ||
9838        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9839     // max(max(a, b), c) -> max3(a, b, c)
9840     // min(min(a, b), c) -> min3(a, b, c)
9841     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9842       SDLoc DL(N);
9843       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9844                          DL,
9845                          N->getValueType(0),
9846                          Op0.getOperand(0),
9847                          Op0.getOperand(1),
9848                          Op1);
9849     }
9850 
9851     // Try commuted.
9852     // max(a, max(b, c)) -> max3(a, b, c)
9853     // min(a, min(b, c)) -> min3(a, b, c)
9854     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9855       SDLoc DL(N);
9856       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9857                          DL,
9858                          N->getValueType(0),
9859                          Op0,
9860                          Op1.getOperand(0),
9861                          Op1.getOperand(1));
9862     }
9863   }
9864 
9865   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9866   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9867     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9868       return Med3;
9869   }
9870 
9871   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9872     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9873       return Med3;
9874   }
9875 
9876   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9877   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9878        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9879        (Opc == AMDGPUISD::FMIN_LEGACY &&
9880         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9881       (VT == MVT::f32 || VT == MVT::f64 ||
9882        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9883        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9884       Op0.hasOneUse()) {
9885     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9886       return Res;
9887   }
9888 
9889   return SDValue();
9890 }
9891 
9892 static bool isClampZeroToOne(SDValue A, SDValue B) {
9893   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9894     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9895       // FIXME: Should this be allowing -0.0?
9896       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9897              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9898     }
9899   }
9900 
9901   return false;
9902 }
9903 
9904 // FIXME: Should only worry about snans for version with chain.
9905 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9906                                               DAGCombinerInfo &DCI) const {
9907   EVT VT = N->getValueType(0);
9908   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9909   // NaNs. With a NaN input, the order of the operands may change the result.
9910 
9911   SelectionDAG &DAG = DCI.DAG;
9912   SDLoc SL(N);
9913 
9914   SDValue Src0 = N->getOperand(0);
9915   SDValue Src1 = N->getOperand(1);
9916   SDValue Src2 = N->getOperand(2);
9917 
9918   if (isClampZeroToOne(Src0, Src1)) {
9919     // const_a, const_b, x -> clamp is safe in all cases including signaling
9920     // nans.
9921     // FIXME: Should this be allowing -0.0?
9922     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9923   }
9924 
9925   const MachineFunction &MF = DAG.getMachineFunction();
9926   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9927 
9928   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9929   // handling no dx10-clamp?
9930   if (Info->getMode().DX10Clamp) {
9931     // If NaNs is clamped to 0, we are free to reorder the inputs.
9932 
9933     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9934       std::swap(Src0, Src1);
9935 
9936     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9937       std::swap(Src1, Src2);
9938 
9939     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9940       std::swap(Src0, Src1);
9941 
9942     if (isClampZeroToOne(Src1, Src2))
9943       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9944   }
9945 
9946   return SDValue();
9947 }
9948 
9949 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9950                                                  DAGCombinerInfo &DCI) const {
9951   SDValue Src0 = N->getOperand(0);
9952   SDValue Src1 = N->getOperand(1);
9953   if (Src0.isUndef() && Src1.isUndef())
9954     return DCI.DAG.getUNDEF(N->getValueType(0));
9955   return SDValue();
9956 }
9957 
9958 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9959 // expanded into a set of cmp/select instructions.
9960 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9961                                                 unsigned NumElem,
9962                                                 bool IsDivergentIdx) {
9963   if (UseDivergentRegisterIndexing)
9964     return false;
9965 
9966   unsigned VecSize = EltSize * NumElem;
9967 
9968   // Sub-dword vectors of size 2 dword or less have better implementation.
9969   if (VecSize <= 64 && EltSize < 32)
9970     return false;
9971 
9972   // Always expand the rest of sub-dword instructions, otherwise it will be
9973   // lowered via memory.
9974   if (EltSize < 32)
9975     return true;
9976 
9977   // Always do this if var-idx is divergent, otherwise it will become a loop.
9978   if (IsDivergentIdx)
9979     return true;
9980 
9981   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9982   unsigned NumInsts = NumElem /* Number of compares */ +
9983                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9984   return NumInsts <= 16;
9985 }
9986 
9987 static bool shouldExpandVectorDynExt(SDNode *N) {
9988   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9989   if (isa<ConstantSDNode>(Idx))
9990     return false;
9991 
9992   SDValue Vec = N->getOperand(0);
9993   EVT VecVT = Vec.getValueType();
9994   EVT EltVT = VecVT.getVectorElementType();
9995   unsigned EltSize = EltVT.getSizeInBits();
9996   unsigned NumElem = VecVT.getVectorNumElements();
9997 
9998   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9999                                                     Idx->isDivergent());
10000 }
10001 
10002 SDValue SITargetLowering::performExtractVectorEltCombine(
10003   SDNode *N, DAGCombinerInfo &DCI) const {
10004   SDValue Vec = N->getOperand(0);
10005   SelectionDAG &DAG = DCI.DAG;
10006 
10007   EVT VecVT = Vec.getValueType();
10008   EVT EltVT = VecVT.getVectorElementType();
10009 
10010   if ((Vec.getOpcode() == ISD::FNEG ||
10011        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10012     SDLoc SL(N);
10013     EVT EltVT = N->getValueType(0);
10014     SDValue Idx = N->getOperand(1);
10015     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10016                               Vec.getOperand(0), Idx);
10017     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10018   }
10019 
10020   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10021   //    =>
10022   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10023   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10024   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10025   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10026     SDLoc SL(N);
10027     EVT EltVT = N->getValueType(0);
10028     SDValue Idx = N->getOperand(1);
10029     unsigned Opc = Vec.getOpcode();
10030 
10031     switch(Opc) {
10032     default:
10033       break;
10034       // TODO: Support other binary operations.
10035     case ISD::FADD:
10036     case ISD::FSUB:
10037     case ISD::FMUL:
10038     case ISD::ADD:
10039     case ISD::UMIN:
10040     case ISD::UMAX:
10041     case ISD::SMIN:
10042     case ISD::SMAX:
10043     case ISD::FMAXNUM:
10044     case ISD::FMINNUM:
10045     case ISD::FMAXNUM_IEEE:
10046     case ISD::FMINNUM_IEEE: {
10047       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10048                                  Vec.getOperand(0), Idx);
10049       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10050                                  Vec.getOperand(1), Idx);
10051 
10052       DCI.AddToWorklist(Elt0.getNode());
10053       DCI.AddToWorklist(Elt1.getNode());
10054       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10055     }
10056     }
10057   }
10058 
10059   unsigned VecSize = VecVT.getSizeInBits();
10060   unsigned EltSize = EltVT.getSizeInBits();
10061 
10062   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10063   if (::shouldExpandVectorDynExt(N)) {
10064     SDLoc SL(N);
10065     SDValue Idx = N->getOperand(1);
10066     SDValue V;
10067     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10068       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10069       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10070       if (I == 0)
10071         V = Elt;
10072       else
10073         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10074     }
10075     return V;
10076   }
10077 
10078   if (!DCI.isBeforeLegalize())
10079     return SDValue();
10080 
10081   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10082   // elements. This exposes more load reduction opportunities by replacing
10083   // multiple small extract_vector_elements with a single 32-bit extract.
10084   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10085   if (isa<MemSDNode>(Vec) &&
10086       EltSize <= 16 &&
10087       EltVT.isByteSized() &&
10088       VecSize > 32 &&
10089       VecSize % 32 == 0 &&
10090       Idx) {
10091     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10092 
10093     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10094     unsigned EltIdx = BitIndex / 32;
10095     unsigned LeftoverBitIdx = BitIndex % 32;
10096     SDLoc SL(N);
10097 
10098     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10099     DCI.AddToWorklist(Cast.getNode());
10100 
10101     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10102                               DAG.getConstant(EltIdx, SL, MVT::i32));
10103     DCI.AddToWorklist(Elt.getNode());
10104     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10105                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10106     DCI.AddToWorklist(Srl.getNode());
10107 
10108     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10109     DCI.AddToWorklist(Trunc.getNode());
10110     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10111   }
10112 
10113   return SDValue();
10114 }
10115 
10116 SDValue
10117 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10118                                                 DAGCombinerInfo &DCI) const {
10119   SDValue Vec = N->getOperand(0);
10120   SDValue Idx = N->getOperand(2);
10121   EVT VecVT = Vec.getValueType();
10122   EVT EltVT = VecVT.getVectorElementType();
10123 
10124   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10125   // => BUILD_VECTOR n x select (e, const-idx)
10126   if (!::shouldExpandVectorDynExt(N))
10127     return SDValue();
10128 
10129   SelectionDAG &DAG = DCI.DAG;
10130   SDLoc SL(N);
10131   SDValue Ins = N->getOperand(1);
10132   EVT IdxVT = Idx.getValueType();
10133 
10134   SmallVector<SDValue, 16> Ops;
10135   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10136     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10137     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10138     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10139     Ops.push_back(V);
10140   }
10141 
10142   return DAG.getBuildVector(VecVT, SL, Ops);
10143 }
10144 
10145 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10146                                           const SDNode *N0,
10147                                           const SDNode *N1) const {
10148   EVT VT = N0->getValueType(0);
10149 
10150   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10151   // support denormals ever.
10152   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10153        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10154         getSubtarget()->hasMadF16())) &&
10155        isOperationLegal(ISD::FMAD, VT))
10156     return ISD::FMAD;
10157 
10158   const TargetOptions &Options = DAG.getTarget().Options;
10159   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10160        (N0->getFlags().hasAllowContract() &&
10161         N1->getFlags().hasAllowContract())) &&
10162       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10163     return ISD::FMA;
10164   }
10165 
10166   return 0;
10167 }
10168 
10169 // For a reassociatable opcode perform:
10170 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10171 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10172                                                SelectionDAG &DAG) const {
10173   EVT VT = N->getValueType(0);
10174   if (VT != MVT::i32 && VT != MVT::i64)
10175     return SDValue();
10176 
10177   unsigned Opc = N->getOpcode();
10178   SDValue Op0 = N->getOperand(0);
10179   SDValue Op1 = N->getOperand(1);
10180 
10181   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10182     return SDValue();
10183 
10184   if (Op0->isDivergent())
10185     std::swap(Op0, Op1);
10186 
10187   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10188     return SDValue();
10189 
10190   SDValue Op2 = Op1.getOperand(1);
10191   Op1 = Op1.getOperand(0);
10192   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10193     return SDValue();
10194 
10195   if (Op1->isDivergent())
10196     std::swap(Op1, Op2);
10197 
10198   // If either operand is constant this will conflict with
10199   // DAGCombiner::ReassociateOps().
10200   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10201       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10202     return SDValue();
10203 
10204   SDLoc SL(N);
10205   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10206   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10207 }
10208 
10209 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10210                            EVT VT,
10211                            SDValue N0, SDValue N1, SDValue N2,
10212                            bool Signed) {
10213   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10214   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10215   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10216   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10217 }
10218 
10219 SDValue SITargetLowering::performAddCombine(SDNode *N,
10220                                             DAGCombinerInfo &DCI) const {
10221   SelectionDAG &DAG = DCI.DAG;
10222   EVT VT = N->getValueType(0);
10223   SDLoc SL(N);
10224   SDValue LHS = N->getOperand(0);
10225   SDValue RHS = N->getOperand(1);
10226 
10227   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10228       && Subtarget->hasMad64_32() &&
10229       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10230       VT.getScalarSizeInBits() <= 64) {
10231     if (LHS.getOpcode() != ISD::MUL)
10232       std::swap(LHS, RHS);
10233 
10234     SDValue MulLHS = LHS.getOperand(0);
10235     SDValue MulRHS = LHS.getOperand(1);
10236     SDValue AddRHS = RHS;
10237 
10238     // TODO: Maybe restrict if SGPR inputs.
10239     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10240         numBitsUnsigned(MulRHS, DAG) <= 32) {
10241       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10242       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10243       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10244       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10245     }
10246 
10247     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10248       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10249       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10250       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10251       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10252     }
10253 
10254     return SDValue();
10255   }
10256 
10257   if (SDValue V = reassociateScalarOps(N, DAG)) {
10258     return V;
10259   }
10260 
10261   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10262     return SDValue();
10263 
10264   // add x, zext (setcc) => addcarry x, 0, setcc
10265   // add x, sext (setcc) => subcarry x, 0, setcc
10266   unsigned Opc = LHS.getOpcode();
10267   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10268       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10269     std::swap(RHS, LHS);
10270 
10271   Opc = RHS.getOpcode();
10272   switch (Opc) {
10273   default: break;
10274   case ISD::ZERO_EXTEND:
10275   case ISD::SIGN_EXTEND:
10276   case ISD::ANY_EXTEND: {
10277     auto Cond = RHS.getOperand(0);
10278     // If this won't be a real VOPC output, we would still need to insert an
10279     // extra instruction anyway.
10280     if (!isBoolSGPR(Cond))
10281       break;
10282     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10283     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10284     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10285     return DAG.getNode(Opc, SL, VTList, Args);
10286   }
10287   case ISD::ADDCARRY: {
10288     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10289     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10290     if (!C || C->getZExtValue() != 0) break;
10291     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10292     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10293   }
10294   }
10295   return SDValue();
10296 }
10297 
10298 SDValue SITargetLowering::performSubCombine(SDNode *N,
10299                                             DAGCombinerInfo &DCI) const {
10300   SelectionDAG &DAG = DCI.DAG;
10301   EVT VT = N->getValueType(0);
10302 
10303   if (VT != MVT::i32)
10304     return SDValue();
10305 
10306   SDLoc SL(N);
10307   SDValue LHS = N->getOperand(0);
10308   SDValue RHS = N->getOperand(1);
10309 
10310   // sub x, zext (setcc) => subcarry x, 0, setcc
10311   // sub x, sext (setcc) => addcarry x, 0, setcc
10312   unsigned Opc = RHS.getOpcode();
10313   switch (Opc) {
10314   default: break;
10315   case ISD::ZERO_EXTEND:
10316   case ISD::SIGN_EXTEND:
10317   case ISD::ANY_EXTEND: {
10318     auto Cond = RHS.getOperand(0);
10319     // If this won't be a real VOPC output, we would still need to insert an
10320     // extra instruction anyway.
10321     if (!isBoolSGPR(Cond))
10322       break;
10323     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10324     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10325     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10326     return DAG.getNode(Opc, SL, VTList, Args);
10327   }
10328   }
10329 
10330   if (LHS.getOpcode() == ISD::SUBCARRY) {
10331     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10332     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10333     if (!C || !C->isNullValue())
10334       return SDValue();
10335     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10336     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10337   }
10338   return SDValue();
10339 }
10340 
10341 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10342   DAGCombinerInfo &DCI) const {
10343 
10344   if (N->getValueType(0) != MVT::i32)
10345     return SDValue();
10346 
10347   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348   if (!C || C->getZExtValue() != 0)
10349     return SDValue();
10350 
10351   SelectionDAG &DAG = DCI.DAG;
10352   SDValue LHS = N->getOperand(0);
10353 
10354   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10355   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10356   unsigned LHSOpc = LHS.getOpcode();
10357   unsigned Opc = N->getOpcode();
10358   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10359       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10360     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10361     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10362   }
10363   return SDValue();
10364 }
10365 
10366 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10367                                              DAGCombinerInfo &DCI) const {
10368   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10369     return SDValue();
10370 
10371   SelectionDAG &DAG = DCI.DAG;
10372   EVT VT = N->getValueType(0);
10373 
10374   SDLoc SL(N);
10375   SDValue LHS = N->getOperand(0);
10376   SDValue RHS = N->getOperand(1);
10377 
10378   // These should really be instruction patterns, but writing patterns with
10379   // source modiifiers is a pain.
10380 
10381   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10382   if (LHS.getOpcode() == ISD::FADD) {
10383     SDValue A = LHS.getOperand(0);
10384     if (A == LHS.getOperand(1)) {
10385       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10386       if (FusedOp != 0) {
10387         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10388         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10389       }
10390     }
10391   }
10392 
10393   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10394   if (RHS.getOpcode() == ISD::FADD) {
10395     SDValue A = RHS.getOperand(0);
10396     if (A == RHS.getOperand(1)) {
10397       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10398       if (FusedOp != 0) {
10399         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10400         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10401       }
10402     }
10403   }
10404 
10405   return SDValue();
10406 }
10407 
10408 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10409                                              DAGCombinerInfo &DCI) const {
10410   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10411     return SDValue();
10412 
10413   SelectionDAG &DAG = DCI.DAG;
10414   SDLoc SL(N);
10415   EVT VT = N->getValueType(0);
10416   assert(!VT.isVector());
10417 
10418   // Try to get the fneg to fold into the source modifier. This undoes generic
10419   // DAG combines and folds them into the mad.
10420   //
10421   // Only do this if we are not trying to support denormals. v_mad_f32 does
10422   // not support denormals ever.
10423   SDValue LHS = N->getOperand(0);
10424   SDValue RHS = N->getOperand(1);
10425   if (LHS.getOpcode() == ISD::FADD) {
10426     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10427     SDValue A = LHS.getOperand(0);
10428     if (A == LHS.getOperand(1)) {
10429       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10430       if (FusedOp != 0){
10431         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10432         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10433 
10434         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10435       }
10436     }
10437   }
10438 
10439   if (RHS.getOpcode() == ISD::FADD) {
10440     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10441 
10442     SDValue A = RHS.getOperand(0);
10443     if (A == RHS.getOperand(1)) {
10444       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10445       if (FusedOp != 0){
10446         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10447         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10448       }
10449     }
10450   }
10451 
10452   return SDValue();
10453 }
10454 
10455 SDValue SITargetLowering::performFMACombine(SDNode *N,
10456                                             DAGCombinerInfo &DCI) const {
10457   SelectionDAG &DAG = DCI.DAG;
10458   EVT VT = N->getValueType(0);
10459   SDLoc SL(N);
10460 
10461   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10462     return SDValue();
10463 
10464   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10465   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10466   SDValue Op1 = N->getOperand(0);
10467   SDValue Op2 = N->getOperand(1);
10468   SDValue FMA = N->getOperand(2);
10469 
10470   if (FMA.getOpcode() != ISD::FMA ||
10471       Op1.getOpcode() != ISD::FP_EXTEND ||
10472       Op2.getOpcode() != ISD::FP_EXTEND)
10473     return SDValue();
10474 
10475   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10476   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10477   // is sufficient to allow generaing fdot2.
10478   const TargetOptions &Options = DAG.getTarget().Options;
10479   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10480       (N->getFlags().hasAllowContract() &&
10481        FMA->getFlags().hasAllowContract())) {
10482     Op1 = Op1.getOperand(0);
10483     Op2 = Op2.getOperand(0);
10484     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10485         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10486       return SDValue();
10487 
10488     SDValue Vec1 = Op1.getOperand(0);
10489     SDValue Idx1 = Op1.getOperand(1);
10490     SDValue Vec2 = Op2.getOperand(0);
10491 
10492     SDValue FMAOp1 = FMA.getOperand(0);
10493     SDValue FMAOp2 = FMA.getOperand(1);
10494     SDValue FMAAcc = FMA.getOperand(2);
10495 
10496     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10497         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10498       return SDValue();
10499 
10500     FMAOp1 = FMAOp1.getOperand(0);
10501     FMAOp2 = FMAOp2.getOperand(0);
10502     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10503         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10504       return SDValue();
10505 
10506     SDValue Vec3 = FMAOp1.getOperand(0);
10507     SDValue Vec4 = FMAOp2.getOperand(0);
10508     SDValue Idx2 = FMAOp1.getOperand(1);
10509 
10510     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10511         // Idx1 and Idx2 cannot be the same.
10512         Idx1 == Idx2)
10513       return SDValue();
10514 
10515     if (Vec1 == Vec2 || Vec3 == Vec4)
10516       return SDValue();
10517 
10518     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10519       return SDValue();
10520 
10521     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10522         (Vec1 == Vec4 && Vec2 == Vec3)) {
10523       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10524                          DAG.getTargetConstant(0, SL, MVT::i1));
10525     }
10526   }
10527   return SDValue();
10528 }
10529 
10530 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10531                                               DAGCombinerInfo &DCI) const {
10532   SelectionDAG &DAG = DCI.DAG;
10533   SDLoc SL(N);
10534 
10535   SDValue LHS = N->getOperand(0);
10536   SDValue RHS = N->getOperand(1);
10537   EVT VT = LHS.getValueType();
10538   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10539 
10540   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10541   if (!CRHS) {
10542     CRHS = dyn_cast<ConstantSDNode>(LHS);
10543     if (CRHS) {
10544       std::swap(LHS, RHS);
10545       CC = getSetCCSwappedOperands(CC);
10546     }
10547   }
10548 
10549   if (CRHS) {
10550     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10551         isBoolSGPR(LHS.getOperand(0))) {
10552       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10553       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10554       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10555       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10556       if ((CRHS->isAllOnesValue() &&
10557            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10558           (CRHS->isNullValue() &&
10559            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10560         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10561                            DAG.getConstant(-1, SL, MVT::i1));
10562       if ((CRHS->isAllOnesValue() &&
10563            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10564           (CRHS->isNullValue() &&
10565            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10566         return LHS.getOperand(0);
10567     }
10568 
10569     uint64_t CRHSVal = CRHS->getZExtValue();
10570     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10571         LHS.getOpcode() == ISD::SELECT &&
10572         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10573         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10574         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10575         isBoolSGPR(LHS.getOperand(0))) {
10576       // Given CT != FT:
10577       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10578       // setcc (select cc, CT, CF), CF, ne => cc
10579       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10580       // setcc (select cc, CT, CF), CT, eq => cc
10581       uint64_t CT = LHS.getConstantOperandVal(1);
10582       uint64_t CF = LHS.getConstantOperandVal(2);
10583 
10584       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10585           (CT == CRHSVal && CC == ISD::SETNE))
10586         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10587                            DAG.getConstant(-1, SL, MVT::i1));
10588       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10589           (CT == CRHSVal && CC == ISD::SETEQ))
10590         return LHS.getOperand(0);
10591     }
10592   }
10593 
10594   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10595                                            VT != MVT::f16))
10596     return SDValue();
10597 
10598   // Match isinf/isfinite pattern
10599   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10600   // (fcmp one (fabs x), inf) -> (fp_class x,
10601   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10602   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10603     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10604     if (!CRHS)
10605       return SDValue();
10606 
10607     const APFloat &APF = CRHS->getValueAPF();
10608     if (APF.isInfinity() && !APF.isNegative()) {
10609       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10610                                  SIInstrFlags::N_INFINITY;
10611       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10612                                     SIInstrFlags::P_ZERO |
10613                                     SIInstrFlags::N_NORMAL |
10614                                     SIInstrFlags::P_NORMAL |
10615                                     SIInstrFlags::N_SUBNORMAL |
10616                                     SIInstrFlags::P_SUBNORMAL;
10617       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10618       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10619                          DAG.getConstant(Mask, SL, MVT::i32));
10620     }
10621   }
10622 
10623   return SDValue();
10624 }
10625 
10626 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10627                                                      DAGCombinerInfo &DCI) const {
10628   SelectionDAG &DAG = DCI.DAG;
10629   SDLoc SL(N);
10630   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10631 
10632   SDValue Src = N->getOperand(0);
10633   SDValue Shift = N->getOperand(0);
10634 
10635   // TODO: Extend type shouldn't matter (assuming legal types).
10636   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10637     Shift = Shift.getOperand(0);
10638 
10639   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10640     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10641     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10642     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10643     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10644     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10645     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10646       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10647                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10648 
10649       unsigned ShiftOffset = 8 * Offset;
10650       if (Shift.getOpcode() == ISD::SHL)
10651         ShiftOffset -= C->getZExtValue();
10652       else
10653         ShiftOffset += C->getZExtValue();
10654 
10655       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10656         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10657                            MVT::f32, Shift);
10658       }
10659     }
10660   }
10661 
10662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10663   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10664   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10665     // We simplified Src. If this node is not dead, visit it again so it is
10666     // folded properly.
10667     if (N->getOpcode() != ISD::DELETED_NODE)
10668       DCI.AddToWorklist(N);
10669     return SDValue(N, 0);
10670   }
10671 
10672   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10673   if (SDValue DemandedSrc =
10674           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10675     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10676 
10677   return SDValue();
10678 }
10679 
10680 SDValue SITargetLowering::performClampCombine(SDNode *N,
10681                                               DAGCombinerInfo &DCI) const {
10682   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10683   if (!CSrc)
10684     return SDValue();
10685 
10686   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10687   const APFloat &F = CSrc->getValueAPF();
10688   APFloat Zero = APFloat::getZero(F.getSemantics());
10689   if (F < Zero ||
10690       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10691     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10692   }
10693 
10694   APFloat One(F.getSemantics(), "1.0");
10695   if (F > One)
10696     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10697 
10698   return SDValue(CSrc, 0);
10699 }
10700 
10701 
10702 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10703                                             DAGCombinerInfo &DCI) const {
10704   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10705     return SDValue();
10706   switch (N->getOpcode()) {
10707   case ISD::ADD:
10708     return performAddCombine(N, DCI);
10709   case ISD::SUB:
10710     return performSubCombine(N, DCI);
10711   case ISD::ADDCARRY:
10712   case ISD::SUBCARRY:
10713     return performAddCarrySubCarryCombine(N, DCI);
10714   case ISD::FADD:
10715     return performFAddCombine(N, DCI);
10716   case ISD::FSUB:
10717     return performFSubCombine(N, DCI);
10718   case ISD::SETCC:
10719     return performSetCCCombine(N, DCI);
10720   case ISD::FMAXNUM:
10721   case ISD::FMINNUM:
10722   case ISD::FMAXNUM_IEEE:
10723   case ISD::FMINNUM_IEEE:
10724   case ISD::SMAX:
10725   case ISD::SMIN:
10726   case ISD::UMAX:
10727   case ISD::UMIN:
10728   case AMDGPUISD::FMIN_LEGACY:
10729   case AMDGPUISD::FMAX_LEGACY:
10730     return performMinMaxCombine(N, DCI);
10731   case ISD::FMA:
10732     return performFMACombine(N, DCI);
10733   case ISD::AND:
10734     return performAndCombine(N, DCI);
10735   case ISD::OR:
10736     return performOrCombine(N, DCI);
10737   case ISD::XOR:
10738     return performXorCombine(N, DCI);
10739   case ISD::ZERO_EXTEND:
10740     return performZeroExtendCombine(N, DCI);
10741   case ISD::SIGN_EXTEND_INREG:
10742     return performSignExtendInRegCombine(N , DCI);
10743   case AMDGPUISD::FP_CLASS:
10744     return performClassCombine(N, DCI);
10745   case ISD::FCANONICALIZE:
10746     return performFCanonicalizeCombine(N, DCI);
10747   case AMDGPUISD::RCP:
10748     return performRcpCombine(N, DCI);
10749   case AMDGPUISD::FRACT:
10750   case AMDGPUISD::RSQ:
10751   case AMDGPUISD::RCP_LEGACY:
10752   case AMDGPUISD::RCP_IFLAG:
10753   case AMDGPUISD::RSQ_CLAMP:
10754   case AMDGPUISD::LDEXP: {
10755     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10756     SDValue Src = N->getOperand(0);
10757     if (Src.isUndef())
10758       return Src;
10759     break;
10760   }
10761   case ISD::SINT_TO_FP:
10762   case ISD::UINT_TO_FP:
10763     return performUCharToFloatCombine(N, DCI);
10764   case AMDGPUISD::CVT_F32_UBYTE0:
10765   case AMDGPUISD::CVT_F32_UBYTE1:
10766   case AMDGPUISD::CVT_F32_UBYTE2:
10767   case AMDGPUISD::CVT_F32_UBYTE3:
10768     return performCvtF32UByteNCombine(N, DCI);
10769   case AMDGPUISD::FMED3:
10770     return performFMed3Combine(N, DCI);
10771   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10772     return performCvtPkRTZCombine(N, DCI);
10773   case AMDGPUISD::CLAMP:
10774     return performClampCombine(N, DCI);
10775   case ISD::SCALAR_TO_VECTOR: {
10776     SelectionDAG &DAG = DCI.DAG;
10777     EVT VT = N->getValueType(0);
10778 
10779     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10780     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10781       SDLoc SL(N);
10782       SDValue Src = N->getOperand(0);
10783       EVT EltVT = Src.getValueType();
10784       if (EltVT == MVT::f16)
10785         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10786 
10787       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10788       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10789     }
10790 
10791     break;
10792   }
10793   case ISD::EXTRACT_VECTOR_ELT:
10794     return performExtractVectorEltCombine(N, DCI);
10795   case ISD::INSERT_VECTOR_ELT:
10796     return performInsertVectorEltCombine(N, DCI);
10797   case ISD::LOAD: {
10798     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10799       return Widended;
10800     LLVM_FALLTHROUGH;
10801   }
10802   default: {
10803     if (!DCI.isBeforeLegalize()) {
10804       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10805         return performMemSDNodeCombine(MemNode, DCI);
10806     }
10807 
10808     break;
10809   }
10810   }
10811 
10812   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10813 }
10814 
10815 /// Helper function for adjustWritemask
10816 static unsigned SubIdx2Lane(unsigned Idx) {
10817   switch (Idx) {
10818   default: return ~0u;
10819   case AMDGPU::sub0: return 0;
10820   case AMDGPU::sub1: return 1;
10821   case AMDGPU::sub2: return 2;
10822   case AMDGPU::sub3: return 3;
10823   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10824   }
10825 }
10826 
10827 /// Adjust the writemask of MIMG instructions
10828 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10829                                           SelectionDAG &DAG) const {
10830   unsigned Opcode = Node->getMachineOpcode();
10831 
10832   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10833   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10834   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10835     return Node; // not implemented for D16
10836 
10837   SDNode *Users[5] = { nullptr };
10838   unsigned Lane = 0;
10839   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10840   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10841   unsigned NewDmask = 0;
10842   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10843   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10844   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10845                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10846   unsigned TFCLane = 0;
10847   bool HasChain = Node->getNumValues() > 1;
10848 
10849   if (OldDmask == 0) {
10850     // These are folded out, but on the chance it happens don't assert.
10851     return Node;
10852   }
10853 
10854   unsigned OldBitsSet = countPopulation(OldDmask);
10855   // Work out which is the TFE/LWE lane if that is enabled.
10856   if (UsesTFC) {
10857     TFCLane = OldBitsSet;
10858   }
10859 
10860   // Try to figure out the used register components
10861   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10862        I != E; ++I) {
10863 
10864     // Don't look at users of the chain.
10865     if (I.getUse().getResNo() != 0)
10866       continue;
10867 
10868     // Abort if we can't understand the usage
10869     if (!I->isMachineOpcode() ||
10870         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10871       return Node;
10872 
10873     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10874     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10875     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10876     // set, etc.
10877     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10878     if (Lane == ~0u)
10879       return Node;
10880 
10881     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10882     if (UsesTFC && Lane == TFCLane) {
10883       Users[Lane] = *I;
10884     } else {
10885       // Set which texture component corresponds to the lane.
10886       unsigned Comp;
10887       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10888         Comp = countTrailingZeros(Dmask);
10889         Dmask &= ~(1 << Comp);
10890       }
10891 
10892       // Abort if we have more than one user per component.
10893       if (Users[Lane])
10894         return Node;
10895 
10896       Users[Lane] = *I;
10897       NewDmask |= 1 << Comp;
10898     }
10899   }
10900 
10901   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10902   bool NoChannels = !NewDmask;
10903   if (NoChannels) {
10904     if (!UsesTFC) {
10905       // No uses of the result and not using TFC. Then do nothing.
10906       return Node;
10907     }
10908     // If the original dmask has one channel - then nothing to do
10909     if (OldBitsSet == 1)
10910       return Node;
10911     // Use an arbitrary dmask - required for the instruction to work
10912     NewDmask = 1;
10913   }
10914   // Abort if there's no change
10915   if (NewDmask == OldDmask)
10916     return Node;
10917 
10918   unsigned BitsSet = countPopulation(NewDmask);
10919 
10920   // Check for TFE or LWE - increase the number of channels by one to account
10921   // for the extra return value
10922   // This will need adjustment for D16 if this is also included in
10923   // adjustWriteMask (this function) but at present D16 are excluded.
10924   unsigned NewChannels = BitsSet + UsesTFC;
10925 
10926   int NewOpcode =
10927       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10928   assert(NewOpcode != -1 &&
10929          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10930          "failed to find equivalent MIMG op");
10931 
10932   // Adjust the writemask in the node
10933   SmallVector<SDValue, 12> Ops;
10934   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10935   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10936   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10937 
10938   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10939 
10940   MVT ResultVT = NewChannels == 1 ?
10941     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10942                            NewChannels == 5 ? 8 : NewChannels);
10943   SDVTList NewVTList = HasChain ?
10944     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10945 
10946 
10947   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10948                                               NewVTList, Ops);
10949 
10950   if (HasChain) {
10951     // Update chain.
10952     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10953     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10954   }
10955 
10956   if (NewChannels == 1) {
10957     assert(Node->hasNUsesOfValue(1, 0));
10958     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10959                                       SDLoc(Node), Users[Lane]->getValueType(0),
10960                                       SDValue(NewNode, 0));
10961     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10962     return nullptr;
10963   }
10964 
10965   // Update the users of the node with the new indices
10966   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10967     SDNode *User = Users[i];
10968     if (!User) {
10969       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10970       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10971       if (i || !NoChannels)
10972         continue;
10973     } else {
10974       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10975       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10976     }
10977 
10978     switch (Idx) {
10979     default: break;
10980     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10981     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10982     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10983     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10984     }
10985   }
10986 
10987   DAG.RemoveDeadNode(Node);
10988   return nullptr;
10989 }
10990 
10991 static bool isFrameIndexOp(SDValue Op) {
10992   if (Op.getOpcode() == ISD::AssertZext)
10993     Op = Op.getOperand(0);
10994 
10995   return isa<FrameIndexSDNode>(Op);
10996 }
10997 
10998 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10999 /// with frame index operands.
11000 /// LLVM assumes that inputs are to these instructions are registers.
11001 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11002                                                         SelectionDAG &DAG) const {
11003   if (Node->getOpcode() == ISD::CopyToReg) {
11004     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11005     SDValue SrcVal = Node->getOperand(2);
11006 
11007     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11008     // to try understanding copies to physical registers.
11009     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11010       SDLoc SL(Node);
11011       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11012       SDValue VReg = DAG.getRegister(
11013         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11014 
11015       SDNode *Glued = Node->getGluedNode();
11016       SDValue ToVReg
11017         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11018                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11019       SDValue ToResultReg
11020         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11021                            VReg, ToVReg.getValue(1));
11022       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11023       DAG.RemoveDeadNode(Node);
11024       return ToResultReg.getNode();
11025     }
11026   }
11027 
11028   SmallVector<SDValue, 8> Ops;
11029   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11030     if (!isFrameIndexOp(Node->getOperand(i))) {
11031       Ops.push_back(Node->getOperand(i));
11032       continue;
11033     }
11034 
11035     SDLoc DL(Node);
11036     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11037                                      Node->getOperand(i).getValueType(),
11038                                      Node->getOperand(i)), 0));
11039   }
11040 
11041   return DAG.UpdateNodeOperands(Node, Ops);
11042 }
11043 
11044 /// Fold the instructions after selecting them.
11045 /// Returns null if users were already updated.
11046 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11047                                           SelectionDAG &DAG) const {
11048   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11049   unsigned Opcode = Node->getMachineOpcode();
11050 
11051   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11052       !TII->isGather4(Opcode) &&
11053       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11054     return adjustWritemask(Node, DAG);
11055   }
11056 
11057   if (Opcode == AMDGPU::INSERT_SUBREG ||
11058       Opcode == AMDGPU::REG_SEQUENCE) {
11059     legalizeTargetIndependentNode(Node, DAG);
11060     return Node;
11061   }
11062 
11063   switch (Opcode) {
11064   case AMDGPU::V_DIV_SCALE_F32_e64:
11065   case AMDGPU::V_DIV_SCALE_F64_e64: {
11066     // Satisfy the operand register constraint when one of the inputs is
11067     // undefined. Ordinarily each undef value will have its own implicit_def of
11068     // a vreg, so force these to use a single register.
11069     SDValue Src0 = Node->getOperand(1);
11070     SDValue Src1 = Node->getOperand(3);
11071     SDValue Src2 = Node->getOperand(5);
11072 
11073     if ((Src0.isMachineOpcode() &&
11074          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11075         (Src0 == Src1 || Src0 == Src2))
11076       break;
11077 
11078     MVT VT = Src0.getValueType().getSimpleVT();
11079     const TargetRegisterClass *RC =
11080         getRegClassFor(VT, Src0.getNode()->isDivergent());
11081 
11082     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11083     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11084 
11085     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11086                                       UndefReg, Src0, SDValue());
11087 
11088     // src0 must be the same register as src1 or src2, even if the value is
11089     // undefined, so make sure we don't violate this constraint.
11090     if (Src0.isMachineOpcode() &&
11091         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11092       if (Src1.isMachineOpcode() &&
11093           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11094         Src0 = Src1;
11095       else if (Src2.isMachineOpcode() &&
11096                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11097         Src0 = Src2;
11098       else {
11099         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11100         Src0 = UndefReg;
11101         Src1 = UndefReg;
11102       }
11103     } else
11104       break;
11105 
11106     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11107     Ops[1] = Src0;
11108     Ops[3] = Src1;
11109     Ops[5] = Src2;
11110     Ops.push_back(ImpDef.getValue(1));
11111     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11112   }
11113   default:
11114     break;
11115   }
11116 
11117   return Node;
11118 }
11119 
11120 /// Assign the register class depending on the number of
11121 /// bits set in the writemask
11122 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11123                                                      SDNode *Node) const {
11124   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11125 
11126   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11127 
11128   if (TII->isVOP3(MI.getOpcode())) {
11129     // Make sure constant bus requirements are respected.
11130     TII->legalizeOperandsVOP3(MRI, MI);
11131 
11132     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11133     // This saves a chain-copy of registers and better ballance register
11134     // use between vgpr and agpr as agpr tuples tend to be big.
11135     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11136       unsigned Opc = MI.getOpcode();
11137       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11138       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11139                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11140         if (I == -1)
11141           break;
11142         MachineOperand &Op = MI.getOperand(I);
11143         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11144              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11145             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11146           continue;
11147         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11148         if (!Src || !Src->isCopy() ||
11149             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11150           continue;
11151         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11152         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11153         // All uses of agpr64 and agpr32 can also accept vgpr except for
11154         // v_accvgpr_read, but we do not produce agpr reads during selection,
11155         // so no use checks are needed.
11156         MRI.setRegClass(Op.getReg(), NewRC);
11157       }
11158     }
11159 
11160     return;
11161   }
11162 
11163   // Replace unused atomics with the no return version.
11164   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11165   if (NoRetAtomicOp != -1) {
11166     if (!Node->hasAnyUseOfValue(0)) {
11167       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11168                                                AMDGPU::OpName::glc1);
11169       if (Glc1Idx != -1)
11170         MI.RemoveOperand(Glc1Idx);
11171       MI.RemoveOperand(0);
11172       MI.setDesc(TII->get(NoRetAtomicOp));
11173       return;
11174     }
11175 
11176     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11177     // instruction, because the return type of these instructions is a vec2 of
11178     // the memory type, so it can be tied to the input operand.
11179     // This means these instructions always have a use, so we need to add a
11180     // special case to check if the atomic has only one extract_subreg use,
11181     // which itself has no uses.
11182     if ((Node->hasNUsesOfValue(1, 0) &&
11183          Node->use_begin()->isMachineOpcode() &&
11184          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11185          !Node->use_begin()->hasAnyUseOfValue(0))) {
11186       Register Def = MI.getOperand(0).getReg();
11187 
11188       // Change this into a noret atomic.
11189       MI.setDesc(TII->get(NoRetAtomicOp));
11190       MI.RemoveOperand(0);
11191 
11192       // If we only remove the def operand from the atomic instruction, the
11193       // extract_subreg will be left with a use of a vreg without a def.
11194       // So we need to insert an implicit_def to avoid machine verifier
11195       // errors.
11196       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11197               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11198     }
11199     return;
11200   }
11201 }
11202 
11203 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11204                               uint64_t Val) {
11205   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11206   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11207 }
11208 
11209 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11210                                                 const SDLoc &DL,
11211                                                 SDValue Ptr) const {
11212   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11213 
11214   // Build the half of the subregister with the constants before building the
11215   // full 128-bit register. If we are building multiple resource descriptors,
11216   // this will allow CSEing of the 2-component register.
11217   const SDValue Ops0[] = {
11218     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11219     buildSMovImm32(DAG, DL, 0),
11220     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11221     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11222     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11223   };
11224 
11225   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11226                                                 MVT::v2i32, Ops0), 0);
11227 
11228   // Combine the constants and the pointer.
11229   const SDValue Ops1[] = {
11230     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11231     Ptr,
11232     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11233     SubRegHi,
11234     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11235   };
11236 
11237   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11238 }
11239 
11240 /// Return a resource descriptor with the 'Add TID' bit enabled
11241 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11242 ///        of the resource descriptor) to create an offset, which is added to
11243 ///        the resource pointer.
11244 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11245                                            SDValue Ptr, uint32_t RsrcDword1,
11246                                            uint64_t RsrcDword2And3) const {
11247   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11248   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11249   if (RsrcDword1) {
11250     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11251                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11252                     0);
11253   }
11254 
11255   SDValue DataLo = buildSMovImm32(DAG, DL,
11256                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11257   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11258 
11259   const SDValue Ops[] = {
11260     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11261     PtrLo,
11262     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11263     PtrHi,
11264     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11265     DataLo,
11266     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11267     DataHi,
11268     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11269   };
11270 
11271   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11272 }
11273 
11274 //===----------------------------------------------------------------------===//
11275 //                         SI Inline Assembly Support
11276 //===----------------------------------------------------------------------===//
11277 
11278 std::pair<unsigned, const TargetRegisterClass *>
11279 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11280                                                StringRef Constraint,
11281                                                MVT VT) const {
11282   const TargetRegisterClass *RC = nullptr;
11283   if (Constraint.size() == 1) {
11284     const unsigned BitWidth = VT.getSizeInBits();
11285     switch (Constraint[0]) {
11286     default:
11287       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11288     case 's':
11289     case 'r':
11290       switch (BitWidth) {
11291       case 16:
11292         RC = &AMDGPU::SReg_32RegClass;
11293         break;
11294       case 64:
11295         RC = &AMDGPU::SGPR_64RegClass;
11296         break;
11297       default:
11298         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11299         if (!RC)
11300           return std::make_pair(0U, nullptr);
11301         break;
11302       }
11303       break;
11304     case 'v':
11305       switch (BitWidth) {
11306       case 16:
11307         RC = &AMDGPU::VGPR_32RegClass;
11308         break;
11309       default:
11310         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11311         if (!RC)
11312           return std::make_pair(0U, nullptr);
11313         break;
11314       }
11315       break;
11316     case 'a':
11317       if (!Subtarget->hasMAIInsts())
11318         break;
11319       switch (BitWidth) {
11320       case 16:
11321         RC = &AMDGPU::AGPR_32RegClass;
11322         break;
11323       default:
11324         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11325         if (!RC)
11326           return std::make_pair(0U, nullptr);
11327         break;
11328       }
11329       break;
11330     }
11331     // We actually support i128, i16 and f16 as inline parameters
11332     // even if they are not reported as legal
11333     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11334                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11335       return std::make_pair(0U, RC);
11336   }
11337 
11338   if (Constraint.size() > 1) {
11339     if (Constraint[1] == 'v') {
11340       RC = &AMDGPU::VGPR_32RegClass;
11341     } else if (Constraint[1] == 's') {
11342       RC = &AMDGPU::SGPR_32RegClass;
11343     } else if (Constraint[1] == 'a') {
11344       RC = &AMDGPU::AGPR_32RegClass;
11345     }
11346 
11347     if (RC) {
11348       uint32_t Idx;
11349       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11350       if (!Failed && Idx < RC->getNumRegs())
11351         return std::make_pair(RC->getRegister(Idx), RC);
11352     }
11353   }
11354 
11355   // FIXME: Returns VS_32 for physical SGPR constraints
11356   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11357 }
11358 
11359 static bool isImmConstraint(StringRef Constraint) {
11360   if (Constraint.size() == 1) {
11361     switch (Constraint[0]) {
11362     default: break;
11363     case 'I':
11364     case 'J':
11365     case 'A':
11366     case 'B':
11367     case 'C':
11368       return true;
11369     }
11370   } else if (Constraint == "DA" ||
11371              Constraint == "DB") {
11372     return true;
11373   }
11374   return false;
11375 }
11376 
11377 SITargetLowering::ConstraintType
11378 SITargetLowering::getConstraintType(StringRef Constraint) const {
11379   if (Constraint.size() == 1) {
11380     switch (Constraint[0]) {
11381     default: break;
11382     case 's':
11383     case 'v':
11384     case 'a':
11385       return C_RegisterClass;
11386     }
11387   }
11388   if (isImmConstraint(Constraint)) {
11389     return C_Other;
11390   }
11391   return TargetLowering::getConstraintType(Constraint);
11392 }
11393 
11394 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11395   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11396     Val = Val & maskTrailingOnes<uint64_t>(Size);
11397   }
11398   return Val;
11399 }
11400 
11401 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11402                                                     std::string &Constraint,
11403                                                     std::vector<SDValue> &Ops,
11404                                                     SelectionDAG &DAG) const {
11405   if (isImmConstraint(Constraint)) {
11406     uint64_t Val;
11407     if (getAsmOperandConstVal(Op, Val) &&
11408         checkAsmConstraintVal(Op, Constraint, Val)) {
11409       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11410       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11411     }
11412   } else {
11413     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11414   }
11415 }
11416 
11417 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11418   unsigned Size = Op.getScalarValueSizeInBits();
11419   if (Size > 64)
11420     return false;
11421 
11422   if (Size == 16 && !Subtarget->has16BitInsts())
11423     return false;
11424 
11425   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11426     Val = C->getSExtValue();
11427     return true;
11428   }
11429   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11430     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11431     return true;
11432   }
11433   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11434     if (Size != 16 || Op.getNumOperands() != 2)
11435       return false;
11436     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11437       return false;
11438     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11439       Val = C->getSExtValue();
11440       return true;
11441     }
11442     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11443       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11444       return true;
11445     }
11446   }
11447 
11448   return false;
11449 }
11450 
11451 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11452                                              const std::string &Constraint,
11453                                              uint64_t Val) const {
11454   if (Constraint.size() == 1) {
11455     switch (Constraint[0]) {
11456     case 'I':
11457       return AMDGPU::isInlinableIntLiteral(Val);
11458     case 'J':
11459       return isInt<16>(Val);
11460     case 'A':
11461       return checkAsmConstraintValA(Op, Val);
11462     case 'B':
11463       return isInt<32>(Val);
11464     case 'C':
11465       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11466              AMDGPU::isInlinableIntLiteral(Val);
11467     default:
11468       break;
11469     }
11470   } else if (Constraint.size() == 2) {
11471     if (Constraint == "DA") {
11472       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11473       int64_t LoBits = static_cast<int32_t>(Val);
11474       return checkAsmConstraintValA(Op, HiBits, 32) &&
11475              checkAsmConstraintValA(Op, LoBits, 32);
11476     }
11477     if (Constraint == "DB") {
11478       return true;
11479     }
11480   }
11481   llvm_unreachable("Invalid asm constraint");
11482 }
11483 
11484 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11485                                               uint64_t Val,
11486                                               unsigned MaxSize) const {
11487   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11488   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11489   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11490       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11491       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11492     return true;
11493   }
11494   return false;
11495 }
11496 
11497 // Figure out which registers should be reserved for stack access. Only after
11498 // the function is legalized do we know all of the non-spill stack objects or if
11499 // calls are present.
11500 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11501   MachineRegisterInfo &MRI = MF.getRegInfo();
11502   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11503   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11504   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11505 
11506   if (Info->isEntryFunction()) {
11507     // Callable functions have fixed registers used for stack access.
11508     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11509   }
11510 
11511   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11512                              Info->getStackPtrOffsetReg()));
11513   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11514     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11515 
11516   // We need to worry about replacing the default register with itself in case
11517   // of MIR testcases missing the MFI.
11518   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11519     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11520 
11521   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11522     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11523 
11524   Info->limitOccupancy(MF);
11525 
11526   if (ST.isWave32() && !MF.empty()) {
11527     const SIInstrInfo *TII = ST.getInstrInfo();
11528     for (auto &MBB : MF) {
11529       for (auto &MI : MBB) {
11530         TII->fixImplicitOperands(MI);
11531       }
11532     }
11533   }
11534 
11535   TargetLoweringBase::finalizeLowering(MF);
11536 
11537   // Allocate a VGPR for future SGPR Spill if
11538   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11539   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11540   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11541       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11542     Info->reserveVGPRforSGPRSpills(MF);
11543 }
11544 
11545 void SITargetLowering::computeKnownBitsForFrameIndex(
11546   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11547   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11548 
11549   // Set the high bits to zero based on the maximum allowed scratch size per
11550   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11551   // calculation won't overflow, so assume the sign bit is never set.
11552   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11553 }
11554 
11555 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11556                                    KnownBits &Known, unsigned Dim) {
11557   unsigned MaxValue =
11558       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11559   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11560 }
11561 
11562 void SITargetLowering::computeKnownBitsForTargetInstr(
11563     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11564     const MachineRegisterInfo &MRI, unsigned Depth) const {
11565   const MachineInstr *MI = MRI.getVRegDef(R);
11566   switch (MI->getOpcode()) {
11567   case AMDGPU::G_INTRINSIC: {
11568     switch (MI->getIntrinsicID()) {
11569     case Intrinsic::amdgcn_workitem_id_x:
11570       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11571       break;
11572     case Intrinsic::amdgcn_workitem_id_y:
11573       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11574       break;
11575     case Intrinsic::amdgcn_workitem_id_z:
11576       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11577       break;
11578     case Intrinsic::amdgcn_mbcnt_lo:
11579     case Intrinsic::amdgcn_mbcnt_hi: {
11580       // These return at most the wavefront size - 1.
11581       unsigned Size = MRI.getType(R).getSizeInBits();
11582       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11583       break;
11584     }
11585     case Intrinsic::amdgcn_groupstaticsize: {
11586       // We can report everything over the maximum size as 0. We can't report
11587       // based on the actual size because we don't know if it's accurate or not
11588       // at any given point.
11589       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11590       break;
11591     }
11592     }
11593     break;
11594   }
11595   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11596     Known.Zero.setHighBits(24);
11597     break;
11598   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11599     Known.Zero.setHighBits(16);
11600     break;
11601   }
11602 }
11603 
11604 Align SITargetLowering::computeKnownAlignForTargetInstr(
11605   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11606   unsigned Depth) const {
11607   const MachineInstr *MI = MRI.getVRegDef(R);
11608   switch (MI->getOpcode()) {
11609   case AMDGPU::G_INTRINSIC:
11610   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11611     // FIXME: Can this move to generic code? What about the case where the call
11612     // site specifies a lower alignment?
11613     Intrinsic::ID IID = MI->getIntrinsicID();
11614     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11615     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11616     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11617       return *RetAlign;
11618     return Align(1);
11619   }
11620   default:
11621     return Align(1);
11622   }
11623 }
11624 
11625 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11626   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11627   const Align CacheLineAlign = Align(64);
11628 
11629   // Pre-GFX10 target did not benefit from loop alignment
11630   if (!ML || DisableLoopAlignment ||
11631       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11632       getSubtarget()->hasInstFwdPrefetchBug())
11633     return PrefAlign;
11634 
11635   // On GFX10 I$ is 4 x 64 bytes cache lines.
11636   // By default prefetcher keeps one cache line behind and reads two ahead.
11637   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11638   // behind and one ahead.
11639   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11640   // If loop fits 64 bytes it always spans no more than two cache lines and
11641   // does not need an alignment.
11642   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11643   // Else if loop is less or equal 192 bytes we need two lines behind.
11644 
11645   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11646   const MachineBasicBlock *Header = ML->getHeader();
11647   if (Header->getAlignment() != PrefAlign)
11648     return Header->getAlignment(); // Already processed.
11649 
11650   unsigned LoopSize = 0;
11651   for (const MachineBasicBlock *MBB : ML->blocks()) {
11652     // If inner loop block is aligned assume in average half of the alignment
11653     // size to be added as nops.
11654     if (MBB != Header)
11655       LoopSize += MBB->getAlignment().value() / 2;
11656 
11657     for (const MachineInstr &MI : *MBB) {
11658       LoopSize += TII->getInstSizeInBytes(MI);
11659       if (LoopSize > 192)
11660         return PrefAlign;
11661     }
11662   }
11663 
11664   if (LoopSize <= 64)
11665     return PrefAlign;
11666 
11667   if (LoopSize <= 128)
11668     return CacheLineAlign;
11669 
11670   // If any of parent loops is surrounded by prefetch instructions do not
11671   // insert new for inner loop, which would reset parent's settings.
11672   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11673     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11674       auto I = Exit->getFirstNonDebugInstr();
11675       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11676         return CacheLineAlign;
11677     }
11678   }
11679 
11680   MachineBasicBlock *Pre = ML->getLoopPreheader();
11681   MachineBasicBlock *Exit = ML->getExitBlock();
11682 
11683   if (Pre && Exit) {
11684     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11685             TII->get(AMDGPU::S_INST_PREFETCH))
11686       .addImm(1); // prefetch 2 lines behind PC
11687 
11688     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11689             TII->get(AMDGPU::S_INST_PREFETCH))
11690       .addImm(2); // prefetch 1 line behind PC
11691   }
11692 
11693   return CacheLineAlign;
11694 }
11695 
11696 LLVM_ATTRIBUTE_UNUSED
11697 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11698   assert(N->getOpcode() == ISD::CopyFromReg);
11699   do {
11700     // Follow the chain until we find an INLINEASM node.
11701     N = N->getOperand(0).getNode();
11702     if (N->getOpcode() == ISD::INLINEASM ||
11703         N->getOpcode() == ISD::INLINEASM_BR)
11704       return true;
11705   } while (N->getOpcode() == ISD::CopyFromReg);
11706   return false;
11707 }
11708 
11709 bool SITargetLowering::isSDNodeSourceOfDivergence(
11710     const SDNode *N, FunctionLoweringInfo *FLI,
11711     LegacyDivergenceAnalysis *KDA) const {
11712   switch (N->getOpcode()) {
11713   case ISD::CopyFromReg: {
11714     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11715     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11716     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11717     Register Reg = R->getReg();
11718 
11719     // FIXME: Why does this need to consider isLiveIn?
11720     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11721       return !TRI->isSGPRReg(MRI, Reg);
11722 
11723     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11724       return KDA->isDivergent(V);
11725 
11726     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11727     return !TRI->isSGPRReg(MRI, Reg);
11728   }
11729   case ISD::LOAD: {
11730     const LoadSDNode *L = cast<LoadSDNode>(N);
11731     unsigned AS = L->getAddressSpace();
11732     // A flat load may access private memory.
11733     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11734   }
11735   case ISD::CALLSEQ_END:
11736     return true;
11737   case ISD::INTRINSIC_WO_CHAIN:
11738     return AMDGPU::isIntrinsicSourceOfDivergence(
11739         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11740   case ISD::INTRINSIC_W_CHAIN:
11741     return AMDGPU::isIntrinsicSourceOfDivergence(
11742         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11743   }
11744   return false;
11745 }
11746 
11747 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11748                                                EVT VT) const {
11749   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11750   case MVT::f32:
11751     return hasFP32Denormals(DAG.getMachineFunction());
11752   case MVT::f64:
11753   case MVT::f16:
11754     return hasFP64FP16Denormals(DAG.getMachineFunction());
11755   default:
11756     return false;
11757   }
11758 }
11759 
11760 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11761                                                     const SelectionDAG &DAG,
11762                                                     bool SNaN,
11763                                                     unsigned Depth) const {
11764   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11765     const MachineFunction &MF = DAG.getMachineFunction();
11766     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11767 
11768     if (Info->getMode().DX10Clamp)
11769       return true; // Clamped to 0.
11770     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11771   }
11772 
11773   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11774                                                             SNaN, Depth);
11775 }
11776 
11777 // Global FP atomic instructions have a hardcoded FP mode and do not support
11778 // FP32 denormals, and only support v2f16 denormals.
11779 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11780   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11781   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11782   if (&Flt == &APFloat::IEEEsingle())
11783     return DenormMode == DenormalMode::getPreserveSign();
11784   return DenormMode == DenormalMode::getIEEE();
11785 }
11786 
11787 TargetLowering::AtomicExpansionKind
11788 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11789   switch (RMW->getOperation()) {
11790   case AtomicRMWInst::FAdd: {
11791     Type *Ty = RMW->getType();
11792 
11793     // We don't have a way to support 16-bit atomics now, so just leave them
11794     // as-is.
11795     if (Ty->isHalfTy())
11796       return AtomicExpansionKind::None;
11797 
11798     if (!Ty->isFloatTy())
11799       return AtomicExpansionKind::CmpXChg;
11800 
11801     // TODO: Do have these for flat. Older targets also had them for buffers.
11802     unsigned AS = RMW->getPointerAddressSpace();
11803 
11804     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11805       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11806         return AtomicExpansionKind::CmpXChg;
11807 
11808       return RMW->use_empty() ? AtomicExpansionKind::None :
11809                                 AtomicExpansionKind::CmpXChg;
11810     }
11811 
11812     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11813     // to round-to-nearest-even.
11814     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11815       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11816   }
11817   default:
11818     break;
11819   }
11820 
11821   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11822 }
11823 
11824 const TargetRegisterClass *
11825 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11826   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11827   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11828   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11829     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11830                                                : &AMDGPU::SReg_32RegClass;
11831   if (!TRI->isSGPRClass(RC) && !isDivergent)
11832     return TRI->getEquivalentSGPRClass(RC);
11833   else if (TRI->isSGPRClass(RC) && isDivergent)
11834     return TRI->getEquivalentVGPRClass(RC);
11835 
11836   return RC;
11837 }
11838 
11839 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11840 // uniform values (as produced by the mask results of control flow intrinsics)
11841 // used outside of divergent blocks. The phi users need to also be treated as
11842 // always uniform.
11843 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11844                       unsigned WaveSize) {
11845   // FIXME: We asssume we never cast the mask results of a control flow
11846   // intrinsic.
11847   // Early exit if the type won't be consistent as a compile time hack.
11848   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11849   if (!IT || IT->getBitWidth() != WaveSize)
11850     return false;
11851 
11852   if (!isa<Instruction>(V))
11853     return false;
11854   if (!Visited.insert(V).second)
11855     return false;
11856   bool Result = false;
11857   for (auto U : V->users()) {
11858     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11859       if (V == U->getOperand(1)) {
11860         switch (Intrinsic->getIntrinsicID()) {
11861         default:
11862           Result = false;
11863           break;
11864         case Intrinsic::amdgcn_if_break:
11865         case Intrinsic::amdgcn_if:
11866         case Intrinsic::amdgcn_else:
11867           Result = true;
11868           break;
11869         }
11870       }
11871       if (V == U->getOperand(0)) {
11872         switch (Intrinsic->getIntrinsicID()) {
11873         default:
11874           Result = false;
11875           break;
11876         case Intrinsic::amdgcn_end_cf:
11877         case Intrinsic::amdgcn_loop:
11878           Result = true;
11879           break;
11880         }
11881       }
11882     } else {
11883       Result = hasCFUser(U, Visited, WaveSize);
11884     }
11885     if (Result)
11886       break;
11887   }
11888   return Result;
11889 }
11890 
11891 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11892                                                const Value *V) const {
11893   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11894     if (CI->isInlineAsm()) {
11895       // FIXME: This cannot give a correct answer. This should only trigger in
11896       // the case where inline asm returns mixed SGPR and VGPR results, used
11897       // outside the defining block. We don't have a specific result to
11898       // consider, so this assumes if any value is SGPR, the overall register
11899       // also needs to be SGPR.
11900       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11901       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11902           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11903       for (auto &TC : TargetConstraints) {
11904         if (TC.Type == InlineAsm::isOutput) {
11905           ComputeConstraintToUse(TC, SDValue());
11906           unsigned AssignedReg;
11907           const TargetRegisterClass *RC;
11908           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11909               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11910           if (RC) {
11911             MachineRegisterInfo &MRI = MF.getRegInfo();
11912             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11913               return true;
11914             else if (SIRI->isSGPRClass(RC))
11915               return true;
11916           }
11917         }
11918       }
11919     }
11920   }
11921   SmallPtrSet<const Value *, 16> Visited;
11922   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11923 }
11924 
11925 std::pair<int, MVT>
11926 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11927                                           Type *Ty) const {
11928   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11929   auto Size = DL.getTypeSizeInBits(Ty);
11930   // Maximum load or store can handle 8 dwords for scalar and 4 for
11931   // vector ALU. Let's assume anything above 8 dwords is expensive
11932   // even if legal.
11933   if (Size <= 256)
11934     return Cost;
11935 
11936   Cost.first = (Size + 255) / 256;
11937   return Cost;
11938 }
11939