1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/BinaryFormat/ELF.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/IntrinsicInst.h"
29 #include "llvm/IR/IntrinsicsAMDGPU.h"
30 #include "llvm/IR/IntrinsicsR600.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/KnownBits.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "si-lower"
37 
38 STATISTIC(NumTailCalls, "Number of tail calls");
39 
40 static cl::opt<bool> DisableLoopAlignment(
41   "amdgpu-disable-loop-alignment",
42   cl::desc("Do not align and prefetch loops"),
43   cl::init(false));
44 
45 static cl::opt<bool> VGPRReserveforSGPRSpill(
46     "amdgpu-reserve-vgpr-for-sgpr-spill",
47     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
48 
49 static cl::opt<bool> UseDivergentRegisterIndexing(
50   "amdgpu-use-divergent-register-indexing",
51   cl::Hidden,
52   cl::desc("Use indirect register addressing for divergent indexes"),
53   cl::init(false));
54 
55 static bool hasFP32Denormals(const MachineFunction &MF) {
56   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
57   return Info->getMode().allFP32Denormals();
58 }
59 
60 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
61   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
62   return Info->getMode().allFP64FP16Denormals();
63 }
64 
65 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
66   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
67   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
68     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
69       return AMDGPU::SGPR0 + Reg;
70     }
71   }
72   llvm_unreachable("Cannot allocate sgpr");
73 }
74 
75 SITargetLowering::SITargetLowering(const TargetMachine &TM,
76                                    const GCNSubtarget &STI)
77     : AMDGPUTargetLowering(TM, STI),
78       Subtarget(&STI) {
79   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
80   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
81 
82   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
83   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
84 
85   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
86 
87   const SIRegisterInfo *TRI = STI.getRegisterInfo();
88   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
89 
90   addRegisterClass(MVT::f64, V64RegClass);
91   addRegisterClass(MVT::v2f32, V64RegClass);
92 
93   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
94   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
95 
96   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
97   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
98 
99   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
100   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
101 
102   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
103   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
104 
105   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
106   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
107 
108   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
109   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
110 
111   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
112   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
113 
114   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
115   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
116 
117   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
118   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
119 
120   if (Subtarget->has16BitInsts()) {
121     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
122     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
123 
124     // Unless there are also VOP3P operations, not operations are really legal.
125     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
126     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
127     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
128     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
129   }
130 
131   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
132   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
133 
134   computeRegisterProperties(Subtarget->getRegisterInfo());
135 
136   // The boolean content concept here is too inflexible. Compares only ever
137   // really produce a 1-bit result. Any copy/extend from these will turn into a
138   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
139   // it's what most targets use.
140   setBooleanContents(ZeroOrOneBooleanContent);
141   setBooleanVectorContents(ZeroOrOneBooleanContent);
142 
143   // We need to custom lower vector stores from local memory
144   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
145   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
146   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
147   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
148   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
149   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
150   setOperationAction(ISD::LOAD, MVT::i1, Custom);
151   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
152 
153   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
154   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
155   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
156   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
157   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
158   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
159   setOperationAction(ISD::STORE, MVT::i1, Custom);
160   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
161 
162   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
163   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
164   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
173   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
174   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
175   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
176   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
177   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
178 
179   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
180   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
181   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
183   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
184 
185   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
186   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
187 
188   setOperationAction(ISD::SELECT, MVT::i1, Promote);
189   setOperationAction(ISD::SELECT, MVT::i64, Custom);
190   setOperationAction(ISD::SELECT, MVT::f64, Promote);
191   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
192 
193   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
194   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
196   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
197   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
198 
199   setOperationAction(ISD::SETCC, MVT::i1, Promote);
200   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
201   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
202   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
203 
204   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
205   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
206   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
207   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
208   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
209   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
210   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
211   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
212 
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
221 
222   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
223   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
225   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
227   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
228 
229   setOperationAction(ISD::UADDO, MVT::i32, Legal);
230   setOperationAction(ISD::USUBO, MVT::i32, Legal);
231 
232   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
233   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
234 
235   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
236   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
237   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
238 
239 #if 0
240   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
241   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
242 #endif
243 
244   // We only support LOAD/STORE and vector manipulation ops for vectors
245   // with > 4 elements.
246   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
247                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
248                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
249                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
250     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
251       switch (Op) {
252       case ISD::LOAD:
253       case ISD::STORE:
254       case ISD::BUILD_VECTOR:
255       case ISD::BITCAST:
256       case ISD::EXTRACT_VECTOR_ELT:
257       case ISD::INSERT_VECTOR_ELT:
258       case ISD::INSERT_SUBVECTOR:
259       case ISD::EXTRACT_SUBVECTOR:
260       case ISD::SCALAR_TO_VECTOR:
261         break;
262       case ISD::CONCAT_VECTORS:
263         setOperationAction(Op, VT, Custom);
264         break;
265       default:
266         setOperationAction(Op, VT, Expand);
267         break;
268       }
269     }
270   }
271 
272   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
273 
274   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
275   // is expanded to avoid having two separate loops in case the index is a VGPR.
276 
277   // Most operations are naturally 32-bit vector operations. We only support
278   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
279   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
280     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
281     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
284     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
285 
286     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
287     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
288 
289     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
290     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
291   }
292 
293   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
305   }
306 
307   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
308     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
310 
311     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
312     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
313 
314     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
315     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
316 
317     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
319   }
320 
321   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
322     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
323     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
324 
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
326     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
327 
328     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
330 
331     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
333   }
334 
335   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
336   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
337   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
338   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
339 
340   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
341   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
342 
343   // Avoid stack access for these.
344   // TODO: Generalize to more vector types.
345   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
346   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
347   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
348   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
349 
350   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
351   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
352   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
353   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
354   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
355   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
356 
357   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
358   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
359   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
360   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
361 
362   // Deal with vec3 vector operations when widened to vec4.
363   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
364   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
365   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
366   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
367 
368   // Deal with vec5 vector operations when widened to vec8.
369   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
370   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
371   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
372   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
373 
374   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
375   // and output demarshalling
376   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
377   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
378 
379   // We can't return success/failure, only the old value,
380   // let LLVM add the comparison
381   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
382   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
383 
384   if (Subtarget->hasFlatAddressSpace()) {
385     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
386     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
387   }
388 
389   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
390   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
391 
392   // FIXME: This should be narrowed to i32, but that only happens if i64 is
393   // illegal.
394   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
395   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
396   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
397 
398   // On SI this is s_memtime and s_memrealtime on VI.
399   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
400   setOperationAction(ISD::TRAP, MVT::Other, Custom);
401   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
402 
403   if (Subtarget->has16BitInsts()) {
404     setOperationAction(ISD::FPOW, MVT::f16, Promote);
405     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
406     setOperationAction(ISD::FLOG, MVT::f16, Custom);
407     setOperationAction(ISD::FEXP, MVT::f16, Custom);
408     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
409   }
410 
411   if (Subtarget->hasMadMacF32Insts())
412     setOperationAction(ISD::FMAD, MVT::f32, Legal);
413 
414   if (!Subtarget->hasBFI()) {
415     // fcopysign can be done in a single instruction with BFI.
416     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
417     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
418   }
419 
420   if (!Subtarget->hasBCNT(32))
421     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
422 
423   if (!Subtarget->hasBCNT(64))
424     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
425 
426   if (Subtarget->hasFFBH())
427     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
428 
429   if (Subtarget->hasFFBL())
430     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
431 
432   // We only really have 32-bit BFE instructions (and 16-bit on VI).
433   //
434   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
435   // effort to match them now. We want this to be false for i64 cases when the
436   // extraction isn't restricted to the upper or lower half. Ideally we would
437   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
438   // span the midpoint are probably relatively rare, so don't worry about them
439   // for now.
440   if (Subtarget->hasBFE())
441     setHasExtractBitsInsn(true);
442 
443   // Clamp modifier on add/sub
444   if (Subtarget->hasIntClamp()) {
445     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
446     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
447   }
448 
449   if (Subtarget->hasAddNoCarry()) {
450     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
451     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
452     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
453     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
454   }
455 
456   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
457   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
458   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
459   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
460 
461 
462   // These are really only legal for ieee_mode functions. We should be avoiding
463   // them for functions that don't have ieee_mode enabled, so just say they are
464   // legal.
465   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
466   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
467   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
468   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
469 
470 
471   if (Subtarget->haveRoundOpsF64()) {
472     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
473     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
474     setOperationAction(ISD::FRINT, MVT::f64, Legal);
475   } else {
476     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
477     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
478     setOperationAction(ISD::FRINT, MVT::f64, Custom);
479     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
480   }
481 
482   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
483 
484   setOperationAction(ISD::FSIN, MVT::f32, Custom);
485   setOperationAction(ISD::FCOS, MVT::f32, Custom);
486   setOperationAction(ISD::FDIV, MVT::f32, Custom);
487   setOperationAction(ISD::FDIV, MVT::f64, Custom);
488 
489   if (Subtarget->has16BitInsts()) {
490     setOperationAction(ISD::Constant, MVT::i16, Legal);
491 
492     setOperationAction(ISD::SMIN, MVT::i16, Legal);
493     setOperationAction(ISD::SMAX, MVT::i16, Legal);
494 
495     setOperationAction(ISD::UMIN, MVT::i16, Legal);
496     setOperationAction(ISD::UMAX, MVT::i16, Legal);
497 
498     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
499     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
500 
501     setOperationAction(ISD::ROTR, MVT::i16, Expand);
502     setOperationAction(ISD::ROTL, MVT::i16, Expand);
503 
504     setOperationAction(ISD::SDIV, MVT::i16, Promote);
505     setOperationAction(ISD::UDIV, MVT::i16, Promote);
506     setOperationAction(ISD::SREM, MVT::i16, Promote);
507     setOperationAction(ISD::UREM, MVT::i16, Promote);
508     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
509     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
510 
511     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
512 
513     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
514     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
515     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
516     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
517     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
518 
519     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
520 
521     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
522 
523     setOperationAction(ISD::LOAD, MVT::i16, Custom);
524 
525     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
526 
527     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
528     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
529     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
530     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
531 
532     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
533     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
534 
535     // F16 - Constant Actions.
536     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
537 
538     // F16 - Load/Store Actions.
539     setOperationAction(ISD::LOAD, MVT::f16, Promote);
540     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
541     setOperationAction(ISD::STORE, MVT::f16, Promote);
542     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
543 
544     // F16 - VOP1 Actions.
545     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
546     setOperationAction(ISD::FCOS, MVT::f16, Custom);
547     setOperationAction(ISD::FSIN, MVT::f16, Custom);
548 
549     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
550     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
551 
552     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
553     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
554     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
555     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
556     setOperationAction(ISD::FROUND, MVT::f16, Custom);
557 
558     // F16 - VOP2 Actions.
559     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
560     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
561 
562     setOperationAction(ISD::FDIV, MVT::f16, Custom);
563 
564     // F16 - VOP3 Actions.
565     setOperationAction(ISD::FMA, MVT::f16, Legal);
566     if (STI.hasMadF16())
567       setOperationAction(ISD::FMAD, MVT::f16, Legal);
568 
569     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
570       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
571         switch (Op) {
572         case ISD::LOAD:
573         case ISD::STORE:
574         case ISD::BUILD_VECTOR:
575         case ISD::BITCAST:
576         case ISD::EXTRACT_VECTOR_ELT:
577         case ISD::INSERT_VECTOR_ELT:
578         case ISD::INSERT_SUBVECTOR:
579         case ISD::EXTRACT_SUBVECTOR:
580         case ISD::SCALAR_TO_VECTOR:
581           break;
582         case ISD::CONCAT_VECTORS:
583           setOperationAction(Op, VT, Custom);
584           break;
585         default:
586           setOperationAction(Op, VT, Expand);
587           break;
588         }
589       }
590     }
591 
592     // v_perm_b32 can handle either of these.
593     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
594     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
595     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
596 
597     // XXX - Do these do anything? Vector constants turn into build_vector.
598     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
599     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
600 
601     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
602     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
603 
604     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
605     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
606     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
607     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
608 
609     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
610     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
611     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
612     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
613 
614     setOperationAction(ISD::AND, MVT::v2i16, Promote);
615     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
616     setOperationAction(ISD::OR, MVT::v2i16, Promote);
617     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
618     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
619     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
620 
621     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
622     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
623     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
624     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
625 
626     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
627     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
628     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
629     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
630 
631     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
632     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
633     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
634     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
635 
636     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
637     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
638     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
639 
640     if (!Subtarget->hasVOP3PInsts()) {
641       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
642       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
643     }
644 
645     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
646     // This isn't really legal, but this avoids the legalizer unrolling it (and
647     // allows matching fneg (fabs x) patterns)
648     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
651     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
652     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
653     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
654 
655     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
656     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
657 
658     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
659     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
660   }
661 
662   if (Subtarget->hasVOP3PInsts()) {
663     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
664     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
665     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
666     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
667     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
668     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
669     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
670     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
671     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
672     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
673 
674     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
675     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
676     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
677     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
678 
679     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
680     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
681     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
682 
683     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
684     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
685 
686     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
687 
688     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
689     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
690 
691     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
692     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
693 
694     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
695     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
696     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
697     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
698     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
699     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
700 
701     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
702     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
703     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
704     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
705 
706     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
707     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
708     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
709     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
710 
711     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
712     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
713     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
714 
715     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
716     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
717 
718     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
719     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
720     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
721 
722     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
723     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
724     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
725 
726     if (Subtarget->hasPackedFP32Ops()) {
727       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
728       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
729       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
730       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
731 
732       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
733         setOperationAction(ISD::FADD, VT, Custom);
734         setOperationAction(ISD::FMUL, VT, Custom);
735         setOperationAction(ISD::FMA, VT, Custom);
736       }
737     }
738   }
739 
740   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
741   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
742 
743   if (Subtarget->has16BitInsts()) {
744     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
745     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
746     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
747     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
748   } else {
749     // Legalization hack.
750     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
751     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
752 
753     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
754     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
755   }
756 
757   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
758     setOperationAction(ISD::SELECT, VT, Custom);
759   }
760 
761   setOperationAction(ISD::SMULO, MVT::i64, Custom);
762   setOperationAction(ISD::UMULO, MVT::i64, Custom);
763 
764   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
765   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
766   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
767   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
768   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
771 
772   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
773   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
774   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
775   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
776   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
783 
784   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
785   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
786   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
794 
795   setTargetDAGCombine(ISD::ADD);
796   setTargetDAGCombine(ISD::ADDCARRY);
797   setTargetDAGCombine(ISD::SUB);
798   setTargetDAGCombine(ISD::SUBCARRY);
799   setTargetDAGCombine(ISD::FADD);
800   setTargetDAGCombine(ISD::FSUB);
801   setTargetDAGCombine(ISD::FMINNUM);
802   setTargetDAGCombine(ISD::FMAXNUM);
803   setTargetDAGCombine(ISD::FMINNUM_IEEE);
804   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
805   setTargetDAGCombine(ISD::FMA);
806   setTargetDAGCombine(ISD::SMIN);
807   setTargetDAGCombine(ISD::SMAX);
808   setTargetDAGCombine(ISD::UMIN);
809   setTargetDAGCombine(ISD::UMAX);
810   setTargetDAGCombine(ISD::SETCC);
811   setTargetDAGCombine(ISD::AND);
812   setTargetDAGCombine(ISD::OR);
813   setTargetDAGCombine(ISD::XOR);
814   setTargetDAGCombine(ISD::SINT_TO_FP);
815   setTargetDAGCombine(ISD::UINT_TO_FP);
816   setTargetDAGCombine(ISD::FCANONICALIZE);
817   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
818   setTargetDAGCombine(ISD::ZERO_EXTEND);
819   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
820   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
821   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
822 
823   // All memory operations. Some folding on the pointer operand is done to help
824   // matching the constant offsets in the addressing modes.
825   setTargetDAGCombine(ISD::LOAD);
826   setTargetDAGCombine(ISD::STORE);
827   setTargetDAGCombine(ISD::ATOMIC_LOAD);
828   setTargetDAGCombine(ISD::ATOMIC_STORE);
829   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
830   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
831   setTargetDAGCombine(ISD::ATOMIC_SWAP);
832   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
833   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
843   setTargetDAGCombine(ISD::INTRINSIC_VOID);
844   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
845 
846   // FIXME: In other contexts we pretend this is a per-function property.
847   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
848 
849   setSchedulingPreference(Sched::RegPressure);
850 }
851 
852 const GCNSubtarget *SITargetLowering::getSubtarget() const {
853   return Subtarget;
854 }
855 
856 //===----------------------------------------------------------------------===//
857 // TargetLowering queries
858 //===----------------------------------------------------------------------===//
859 
860 // v_mad_mix* support a conversion from f16 to f32.
861 //
862 // There is only one special case when denormals are enabled we don't currently,
863 // where this is OK to use.
864 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
865                                        EVT DestVT, EVT SrcVT) const {
866   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
867           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
868     DestVT.getScalarType() == MVT::f32 &&
869     SrcVT.getScalarType() == MVT::f16 &&
870     // TODO: This probably only requires no input flushing?
871     !hasFP32Denormals(DAG.getMachineFunction());
872 }
873 
874 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
875   // SI has some legal vector types, but no legal vector operations. Say no
876   // shuffles are legal in order to prefer scalarizing some vector operations.
877   return false;
878 }
879 
880 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
881                                                     CallingConv::ID CC,
882                                                     EVT VT) const {
883   if (CC == CallingConv::AMDGPU_KERNEL)
884     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
885 
886   if (VT.isVector()) {
887     EVT ScalarVT = VT.getScalarType();
888     unsigned Size = ScalarVT.getSizeInBits();
889     if (Size == 16) {
890       if (Subtarget->has16BitInsts())
891         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
892       return VT.isInteger() ? MVT::i32 : MVT::f32;
893     }
894 
895     if (Size < 16)
896       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
897     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
898   }
899 
900   if (VT.getSizeInBits() > 32)
901     return MVT::i32;
902 
903   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
904 }
905 
906 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
907                                                          CallingConv::ID CC,
908                                                          EVT VT) const {
909   if (CC == CallingConv::AMDGPU_KERNEL)
910     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
911 
912   if (VT.isVector()) {
913     unsigned NumElts = VT.getVectorNumElements();
914     EVT ScalarVT = VT.getScalarType();
915     unsigned Size = ScalarVT.getSizeInBits();
916 
917     // FIXME: Should probably promote 8-bit vectors to i16.
918     if (Size == 16 && Subtarget->has16BitInsts())
919       return (NumElts + 1) / 2;
920 
921     if (Size <= 32)
922       return NumElts;
923 
924     if (Size > 32)
925       return NumElts * ((Size + 31) / 32);
926   } else if (VT.getSizeInBits() > 32)
927     return (VT.getSizeInBits() + 31) / 32;
928 
929   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
930 }
931 
932 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
933   LLVMContext &Context, CallingConv::ID CC,
934   EVT VT, EVT &IntermediateVT,
935   unsigned &NumIntermediates, MVT &RegisterVT) const {
936   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
937     unsigned NumElts = VT.getVectorNumElements();
938     EVT ScalarVT = VT.getScalarType();
939     unsigned Size = ScalarVT.getSizeInBits();
940     // FIXME: We should fix the ABI to be the same on targets without 16-bit
941     // support, but unless we can properly handle 3-vectors, it will be still be
942     // inconsistent.
943     if (Size == 16 && Subtarget->has16BitInsts()) {
944       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
945       IntermediateVT = RegisterVT;
946       NumIntermediates = (NumElts + 1) / 2;
947       return NumIntermediates;
948     }
949 
950     if (Size == 32) {
951       RegisterVT = ScalarVT.getSimpleVT();
952       IntermediateVT = RegisterVT;
953       NumIntermediates = NumElts;
954       return NumIntermediates;
955     }
956 
957     if (Size < 16 && Subtarget->has16BitInsts()) {
958       // FIXME: Should probably form v2i16 pieces
959       RegisterVT = MVT::i16;
960       IntermediateVT = ScalarVT;
961       NumIntermediates = NumElts;
962       return NumIntermediates;
963     }
964 
965 
966     if (Size != 16 && Size <= 32) {
967       RegisterVT = MVT::i32;
968       IntermediateVT = ScalarVT;
969       NumIntermediates = NumElts;
970       return NumIntermediates;
971     }
972 
973     if (Size > 32) {
974       RegisterVT = MVT::i32;
975       IntermediateVT = RegisterVT;
976       NumIntermediates = NumElts * ((Size + 31) / 32);
977       return NumIntermediates;
978     }
979   }
980 
981   return TargetLowering::getVectorTypeBreakdownForCallingConv(
982     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
983 }
984 
985 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
986   assert(DMaskLanes != 0);
987 
988   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
989     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
990     return EVT::getVectorVT(Ty->getContext(),
991                             EVT::getEVT(VT->getElementType()),
992                             NumElts);
993   }
994 
995   return EVT::getEVT(Ty);
996 }
997 
998 // Peek through TFE struct returns to only use the data size.
999 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1000   auto *ST = dyn_cast<StructType>(Ty);
1001   if (!ST)
1002     return memVTFromImageData(Ty, DMaskLanes);
1003 
1004   // Some intrinsics return an aggregate type - special case to work out the
1005   // correct memVT.
1006   //
1007   // Only limited forms of aggregate type currently expected.
1008   if (ST->getNumContainedTypes() != 2 ||
1009       !ST->getContainedType(1)->isIntegerTy(32))
1010     return EVT();
1011   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1012 }
1013 
1014 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1015                                           const CallInst &CI,
1016                                           MachineFunction &MF,
1017                                           unsigned IntrID) const {
1018   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1019           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1020     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1021                                                   (Intrinsic::ID)IntrID);
1022     if (Attr.hasFnAttribute(Attribute::ReadNone))
1023       return false;
1024 
1025     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1026 
1027     if (RsrcIntr->IsImage) {
1028       Info.ptrVal =
1029           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1030       Info.align.reset();
1031     } else {
1032       Info.ptrVal =
1033           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1034     }
1035 
1036     Info.flags = MachineMemOperand::MODereferenceable;
1037     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1038       unsigned DMaskLanes = 4;
1039 
1040       if (RsrcIntr->IsImage) {
1041         const AMDGPU::ImageDimIntrinsicInfo *Intr
1042           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1043         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1044           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1045 
1046         if (!BaseOpcode->Gather4) {
1047           // If this isn't a gather, we may have excess loaded elements in the
1048           // IR type. Check the dmask for the real number of elements loaded.
1049           unsigned DMask
1050             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1051           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1052         }
1053 
1054         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1055       } else
1056         Info.memVT = EVT::getEVT(CI.getType());
1057 
1058       // FIXME: What does alignment mean for an image?
1059       Info.opc = ISD::INTRINSIC_W_CHAIN;
1060       Info.flags |= MachineMemOperand::MOLoad;
1061     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1062       Info.opc = ISD::INTRINSIC_VOID;
1063 
1064       Type *DataTy = CI.getArgOperand(0)->getType();
1065       if (RsrcIntr->IsImage) {
1066         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1067         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1068         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1069       } else
1070         Info.memVT = EVT::getEVT(DataTy);
1071 
1072       Info.flags |= MachineMemOperand::MOStore;
1073     } else {
1074       // Atomic
1075       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1076                                             ISD::INTRINSIC_W_CHAIN;
1077       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1078       Info.flags = MachineMemOperand::MOLoad |
1079                    MachineMemOperand::MOStore |
1080                    MachineMemOperand::MODereferenceable;
1081 
1082       // XXX - Should this be volatile without known ordering?
1083       Info.flags |= MachineMemOperand::MOVolatile;
1084     }
1085     return true;
1086   }
1087 
1088   switch (IntrID) {
1089   case Intrinsic::amdgcn_atomic_inc:
1090   case Intrinsic::amdgcn_atomic_dec:
1091   case Intrinsic::amdgcn_ds_ordered_add:
1092   case Intrinsic::amdgcn_ds_ordered_swap:
1093   case Intrinsic::amdgcn_ds_fadd:
1094   case Intrinsic::amdgcn_ds_fmin:
1095   case Intrinsic::amdgcn_ds_fmax: {
1096     Info.opc = ISD::INTRINSIC_W_CHAIN;
1097     Info.memVT = MVT::getVT(CI.getType());
1098     Info.ptrVal = CI.getOperand(0);
1099     Info.align.reset();
1100     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1101 
1102     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1103     if (!Vol->isZero())
1104       Info.flags |= MachineMemOperand::MOVolatile;
1105 
1106     return true;
1107   }
1108   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1109     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1110 
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1113     Info.ptrVal =
1114         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1115     Info.align.reset();
1116     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1117 
1118     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1119     if (!Vol || !Vol->isZero())
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121 
1122     return true;
1123   }
1124   case Intrinsic::amdgcn_ds_append:
1125   case Intrinsic::amdgcn_ds_consume: {
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 | MachineMemOperand::MOStore;
1131 
1132     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1133     if (!Vol->isZero())
1134       Info.flags |= MachineMemOperand::MOVolatile;
1135 
1136     return true;
1137   }
1138   case Intrinsic::amdgcn_global_atomic_csub: {
1139     Info.opc = ISD::INTRINSIC_W_CHAIN;
1140     Info.memVT = MVT::getVT(CI.getType());
1141     Info.ptrVal = CI.getOperand(0);
1142     Info.align.reset();
1143     Info.flags = MachineMemOperand::MOLoad |
1144                  MachineMemOperand::MOStore |
1145                  MachineMemOperand::MOVolatile;
1146     return true;
1147   }
1148   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1149     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1150     Info.opc = ISD::INTRINSIC_W_CHAIN;
1151     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1152     Info.ptrVal =
1153         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1154     Info.align.reset();
1155     Info.flags = MachineMemOperand::MOLoad |
1156                  MachineMemOperand::MODereferenceable;
1157     return true;
1158   }
1159   case Intrinsic::amdgcn_global_atomic_fadd:
1160   case Intrinsic::amdgcn_global_atomic_fmin:
1161   case Intrinsic::amdgcn_global_atomic_fmax:
1162   case Intrinsic::amdgcn_flat_atomic_fadd:
1163   case Intrinsic::amdgcn_flat_atomic_fmin:
1164   case Intrinsic::amdgcn_flat_atomic_fmax: {
1165     Info.opc = ISD::INTRINSIC_W_CHAIN;
1166     Info.memVT = MVT::getVT(CI.getType());
1167     Info.ptrVal = CI.getOperand(0);
1168     Info.align.reset();
1169     Info.flags = MachineMemOperand::MOLoad |
1170                  MachineMemOperand::MOStore |
1171                  MachineMemOperand::MODereferenceable |
1172                  MachineMemOperand::MOVolatile;
1173     return true;
1174   }
1175   case Intrinsic::amdgcn_ds_gws_init:
1176   case Intrinsic::amdgcn_ds_gws_barrier:
1177   case Intrinsic::amdgcn_ds_gws_sema_v:
1178   case Intrinsic::amdgcn_ds_gws_sema_br:
1179   case Intrinsic::amdgcn_ds_gws_sema_p:
1180   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1181     Info.opc = ISD::INTRINSIC_VOID;
1182 
1183     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1184     Info.ptrVal =
1185         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1186 
1187     // This is an abstract access, but we need to specify a type and size.
1188     Info.memVT = MVT::i32;
1189     Info.size = 4;
1190     Info.align = Align(4);
1191 
1192     Info.flags = MachineMemOperand::MOStore;
1193     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1194       Info.flags = MachineMemOperand::MOLoad;
1195     return true;
1196   }
1197   default:
1198     return false;
1199   }
1200 }
1201 
1202 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1203                                             SmallVectorImpl<Value*> &Ops,
1204                                             Type *&AccessTy) const {
1205   switch (II->getIntrinsicID()) {
1206   case Intrinsic::amdgcn_atomic_inc:
1207   case Intrinsic::amdgcn_atomic_dec:
1208   case Intrinsic::amdgcn_ds_ordered_add:
1209   case Intrinsic::amdgcn_ds_ordered_swap:
1210   case Intrinsic::amdgcn_ds_append:
1211   case Intrinsic::amdgcn_ds_consume:
1212   case Intrinsic::amdgcn_ds_fadd:
1213   case Intrinsic::amdgcn_ds_fmin:
1214   case Intrinsic::amdgcn_ds_fmax:
1215   case Intrinsic::amdgcn_global_atomic_fadd:
1216   case Intrinsic::amdgcn_flat_atomic_fadd:
1217   case Intrinsic::amdgcn_flat_atomic_fmin:
1218   case Intrinsic::amdgcn_flat_atomic_fmax:
1219   case Intrinsic::amdgcn_global_atomic_csub: {
1220     Value *Ptr = II->getArgOperand(0);
1221     AccessTy = II->getType();
1222     Ops.push_back(Ptr);
1223     return true;
1224   }
1225   default:
1226     return false;
1227   }
1228 }
1229 
1230 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1231   if (!Subtarget->hasFlatInstOffsets()) {
1232     // Flat instructions do not have offsets, and only have the register
1233     // address.
1234     return AM.BaseOffs == 0 && AM.Scale == 0;
1235   }
1236 
1237   return AM.Scale == 0 &&
1238          (AM.BaseOffs == 0 ||
1239           Subtarget->getInstrInfo()->isLegalFLATOffset(
1240               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1241 }
1242 
1243 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1244   if (Subtarget->hasFlatGlobalInsts())
1245     return AM.Scale == 0 &&
1246            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1247                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1248                                     SIInstrFlags::FlatGlobal));
1249 
1250   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1251       // Assume the we will use FLAT for all global memory accesses
1252       // on VI.
1253       // FIXME: This assumption is currently wrong.  On VI we still use
1254       // MUBUF instructions for the r + i addressing mode.  As currently
1255       // implemented, the MUBUF instructions only work on buffer < 4GB.
1256       // It may be possible to support > 4GB buffers with MUBUF instructions,
1257       // by setting the stride value in the resource descriptor which would
1258       // increase the size limit to (stride * 4GB).  However, this is risky,
1259       // because it has never been validated.
1260     return isLegalFlatAddressingMode(AM);
1261   }
1262 
1263   return isLegalMUBUFAddressingMode(AM);
1264 }
1265 
1266 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1267   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1268   // additionally can do r + r + i with addr64. 32-bit has more addressing
1269   // mode options. Depending on the resource constant, it can also do
1270   // (i64 r0) + (i32 r1) * (i14 i).
1271   //
1272   // Private arrays end up using a scratch buffer most of the time, so also
1273   // assume those use MUBUF instructions. Scratch loads / stores are currently
1274   // implemented as mubuf instructions with offen bit set, so slightly
1275   // different than the normal addr64.
1276   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1277     return false;
1278 
1279   // FIXME: Since we can split immediate into soffset and immediate offset,
1280   // would it make sense to allow any immediate?
1281 
1282   switch (AM.Scale) {
1283   case 0: // r + i or just i, depending on HasBaseReg.
1284     return true;
1285   case 1:
1286     return true; // We have r + r or r + i.
1287   case 2:
1288     if (AM.HasBaseReg) {
1289       // Reject 2 * r + r.
1290       return false;
1291     }
1292 
1293     // Allow 2 * r as r + r
1294     // Or  2 * r + i is allowed as r + r + i.
1295     return true;
1296   default: // Don't allow n * r
1297     return false;
1298   }
1299 }
1300 
1301 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1302                                              const AddrMode &AM, Type *Ty,
1303                                              unsigned AS, Instruction *I) const {
1304   // No global is ever allowed as a base.
1305   if (AM.BaseGV)
1306     return false;
1307 
1308   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1309     return isLegalGlobalAddressingMode(AM);
1310 
1311   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1312       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1313       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1314     // If the offset isn't a multiple of 4, it probably isn't going to be
1315     // correctly aligned.
1316     // FIXME: Can we get the real alignment here?
1317     if (AM.BaseOffs % 4 != 0)
1318       return isLegalMUBUFAddressingMode(AM);
1319 
1320     // There are no SMRD extloads, so if we have to do a small type access we
1321     // will use a MUBUF load.
1322     // FIXME?: We also need to do this if unaligned, but we don't know the
1323     // alignment here.
1324     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1325       return isLegalGlobalAddressingMode(AM);
1326 
1327     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1328       // SMRD instructions have an 8-bit, dword offset on SI.
1329       if (!isUInt<8>(AM.BaseOffs / 4))
1330         return false;
1331     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1332       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1333       // in 8-bits, it can use a smaller encoding.
1334       if (!isUInt<32>(AM.BaseOffs / 4))
1335         return false;
1336     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1337       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1338       if (!isUInt<20>(AM.BaseOffs))
1339         return false;
1340     } else
1341       llvm_unreachable("unhandled generation");
1342 
1343     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1344       return true;
1345 
1346     if (AM.Scale == 1 && AM.HasBaseReg)
1347       return true;
1348 
1349     return false;
1350 
1351   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1352     return isLegalMUBUFAddressingMode(AM);
1353   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1354              AS == AMDGPUAS::REGION_ADDRESS) {
1355     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1356     // field.
1357     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1358     // an 8-bit dword offset but we don't know the alignment here.
1359     if (!isUInt<16>(AM.BaseOffs))
1360       return false;
1361 
1362     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1363       return true;
1364 
1365     if (AM.Scale == 1 && AM.HasBaseReg)
1366       return true;
1367 
1368     return false;
1369   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1370              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1371     // For an unknown address space, this usually means that this is for some
1372     // reason being used for pure arithmetic, and not based on some addressing
1373     // computation. We don't have instructions that compute pointers with any
1374     // addressing modes, so treat them as having no offset like flat
1375     // instructions.
1376     return isLegalFlatAddressingMode(AM);
1377   }
1378 
1379   // Assume a user alias of global for unknown address spaces.
1380   return isLegalGlobalAddressingMode(AM);
1381 }
1382 
1383 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1384                                         const SelectionDAG &DAG) const {
1385   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1386     return (MemVT.getSizeInBits() <= 4 * 32);
1387   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1388     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1389     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1390   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1391     return (MemVT.getSizeInBits() <= 2 * 32);
1392   }
1393   return true;
1394 }
1395 
1396 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1397     unsigned Size, unsigned AddrSpace, Align Alignment,
1398     MachineMemOperand::Flags Flags, bool *IsFast) const {
1399   if (IsFast)
1400     *IsFast = false;
1401 
1402   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1403       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1404     // Check if alignment requirements for ds_read/write instructions are
1405     // disabled.
1406     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1407         !Subtarget->hasLDSMisalignedBug()) {
1408       if (IsFast)
1409         *IsFast = Alignment != Align(2);
1410       return true;
1411     }
1412 
1413     // Either, the alignment requirements are "enabled", or there is an
1414     // unaligned LDS access related hardware bug though alignment requirements
1415     // are "disabled". In either case, we need to check for proper alignment
1416     // requirements.
1417     //
1418     if (Size == 64) {
1419       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1420       // can do a 4 byte aligned, 8 byte access in a single operation using
1421       // ds_read2/write2_b32 with adjacent offsets.
1422       bool AlignedBy4 = Alignment >= Align(4);
1423       if (IsFast)
1424         *IsFast = AlignedBy4;
1425 
1426       return AlignedBy4;
1427     }
1428     if (Size == 96) {
1429       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1430       // gfx8 and older.
1431       bool AlignedBy16 = Alignment >= Align(16);
1432       if (IsFast)
1433         *IsFast = AlignedBy16;
1434 
1435       return AlignedBy16;
1436     }
1437     if (Size == 128) {
1438       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1439       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1440       // single operation using ds_read2/write2_b64.
1441       bool AlignedBy8 = Alignment >= Align(8);
1442       if (IsFast)
1443         *IsFast = AlignedBy8;
1444 
1445       return AlignedBy8;
1446     }
1447   }
1448 
1449   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1450     bool AlignedBy4 = Alignment >= Align(4);
1451     if (IsFast)
1452       *IsFast = AlignedBy4;
1453 
1454     return AlignedBy4 ||
1455            Subtarget->enableFlatScratch() ||
1456            Subtarget->hasUnalignedScratchAccess();
1457   }
1458 
1459   // FIXME: We have to be conservative here and assume that flat operations
1460   // will access scratch.  If we had access to the IR function, then we
1461   // could determine if any private memory was used in the function.
1462   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1463       !Subtarget->hasUnalignedScratchAccess()) {
1464     bool AlignedBy4 = Alignment >= Align(4);
1465     if (IsFast)
1466       *IsFast = AlignedBy4;
1467 
1468     return AlignedBy4;
1469   }
1470 
1471   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1472       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1473         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1474     // If we have an uniform constant load, it still requires using a slow
1475     // buffer instruction if unaligned.
1476     if (IsFast) {
1477       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1478       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1479       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1480                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1481         Alignment >= Align(4) : Alignment != Align(2);
1482     }
1483 
1484     return true;
1485   }
1486 
1487   // Smaller than dword value must be aligned.
1488   if (Size < 32)
1489     return false;
1490 
1491   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1492   // byte-address are ignored, thus forcing Dword alignment.
1493   // This applies to private, global, and constant memory.
1494   if (IsFast)
1495     *IsFast = true;
1496 
1497   return Size >= 32 && Alignment >= Align(4);
1498 }
1499 
1500 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1501     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1502     bool *IsFast) const {
1503   if (IsFast)
1504     *IsFast = false;
1505 
1506   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1507   // which isn't a simple VT.
1508   // Until MVT is extended to handle this, simply check for the size and
1509   // rely on the condition below: allow accesses if the size is a multiple of 4.
1510   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1511                            VT.getStoreSize() > 16)) {
1512     return false;
1513   }
1514 
1515   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1516                                             Alignment, Flags, IsFast);
1517 }
1518 
1519 EVT SITargetLowering::getOptimalMemOpType(
1520     const MemOp &Op, const AttributeList &FuncAttributes) const {
1521   // FIXME: Should account for address space here.
1522 
1523   // The default fallback uses the private pointer size as a guess for a type to
1524   // use. Make sure we switch these to 64-bit accesses.
1525 
1526   if (Op.size() >= 16 &&
1527       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1528     return MVT::v4i32;
1529 
1530   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1531     return MVT::v2i32;
1532 
1533   // Use the default.
1534   return MVT::Other;
1535 }
1536 
1537 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1538   const MemSDNode *MemNode = cast<MemSDNode>(N);
1539   const Value *Ptr = MemNode->getMemOperand()->getValue();
1540   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1541   return I && I->getMetadata("amdgpu.noclobber");
1542 }
1543 
1544 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1545   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1546          AS == AMDGPUAS::PRIVATE_ADDRESS;
1547 }
1548 
1549 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1550                                            unsigned DestAS) const {
1551   // Flat -> private/local is a simple truncate.
1552   // Flat -> global is no-op
1553   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1554     return true;
1555 
1556   const GCNTargetMachine &TM =
1557       static_cast<const GCNTargetMachine &>(getTargetMachine());
1558   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1559 }
1560 
1561 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1562   const MemSDNode *MemNode = cast<MemSDNode>(N);
1563 
1564   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1565 }
1566 
1567 TargetLoweringBase::LegalizeTypeAction
1568 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1569   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1570       VT.getScalarType().bitsLE(MVT::i16))
1571     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1572   return TargetLoweringBase::getPreferredVectorAction(VT);
1573 }
1574 
1575 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1576                                                          Type *Ty) const {
1577   // FIXME: Could be smarter if called for vector constants.
1578   return true;
1579 }
1580 
1581 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1582   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1583     switch (Op) {
1584     case ISD::LOAD:
1585     case ISD::STORE:
1586 
1587     // These operations are done with 32-bit instructions anyway.
1588     case ISD::AND:
1589     case ISD::OR:
1590     case ISD::XOR:
1591     case ISD::SELECT:
1592       // TODO: Extensions?
1593       return true;
1594     default:
1595       return false;
1596     }
1597   }
1598 
1599   // SimplifySetCC uses this function to determine whether or not it should
1600   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1601   if (VT == MVT::i1 && Op == ISD::SETCC)
1602     return false;
1603 
1604   return TargetLowering::isTypeDesirableForOp(Op, VT);
1605 }
1606 
1607 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1608                                                    const SDLoc &SL,
1609                                                    SDValue Chain,
1610                                                    uint64_t Offset) const {
1611   const DataLayout &DL = DAG.getDataLayout();
1612   MachineFunction &MF = DAG.getMachineFunction();
1613   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1614 
1615   const ArgDescriptor *InputPtrReg;
1616   const TargetRegisterClass *RC;
1617   LLT ArgTy;
1618 
1619   std::tie(InputPtrReg, RC, ArgTy) =
1620       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1621 
1622   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1623   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1624   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1625     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1626 
1627   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1628 }
1629 
1630 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1631                                             const SDLoc &SL) const {
1632   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1633                                                FIRST_IMPLICIT);
1634   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1635 }
1636 
1637 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1638                                          const SDLoc &SL, SDValue Val,
1639                                          bool Signed,
1640                                          const ISD::InputArg *Arg) const {
1641   // First, if it is a widened vector, narrow it.
1642   if (VT.isVector() &&
1643       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1644     EVT NarrowedVT =
1645         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1646                          VT.getVectorNumElements());
1647     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1648                       DAG.getConstant(0, SL, MVT::i32));
1649   }
1650 
1651   // Then convert the vector elements or scalar value.
1652   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1653       VT.bitsLT(MemVT)) {
1654     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1655     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1656   }
1657 
1658   if (MemVT.isFloatingPoint())
1659     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1660   else if (Signed)
1661     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1662   else
1663     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1664 
1665   return Val;
1666 }
1667 
1668 SDValue SITargetLowering::lowerKernargMemParameter(
1669     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1670     uint64_t Offset, Align Alignment, bool Signed,
1671     const ISD::InputArg *Arg) const {
1672   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1673 
1674   // Try to avoid using an extload by loading earlier than the argument address,
1675   // and extracting the relevant bits. The load should hopefully be merged with
1676   // the previous argument.
1677   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1678     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1679     int64_t AlignDownOffset = alignDown(Offset, 4);
1680     int64_t OffsetDiff = Offset - AlignDownOffset;
1681 
1682     EVT IntVT = MemVT.changeTypeToInteger();
1683 
1684     // TODO: If we passed in the base kernel offset we could have a better
1685     // alignment than 4, but we don't really need it.
1686     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1687     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1688                                MachineMemOperand::MODereferenceable |
1689                                    MachineMemOperand::MOInvariant);
1690 
1691     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1692     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1693 
1694     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1695     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1696     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1697 
1698 
1699     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1700   }
1701 
1702   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1703   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1704                              MachineMemOperand::MODereferenceable |
1705                                  MachineMemOperand::MOInvariant);
1706 
1707   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1708   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1709 }
1710 
1711 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1712                                               const SDLoc &SL, SDValue Chain,
1713                                               const ISD::InputArg &Arg) const {
1714   MachineFunction &MF = DAG.getMachineFunction();
1715   MachineFrameInfo &MFI = MF.getFrameInfo();
1716 
1717   if (Arg.Flags.isByVal()) {
1718     unsigned Size = Arg.Flags.getByValSize();
1719     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1720     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1721   }
1722 
1723   unsigned ArgOffset = VA.getLocMemOffset();
1724   unsigned ArgSize = VA.getValVT().getStoreSize();
1725 
1726   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1727 
1728   // Create load nodes to retrieve arguments from the stack.
1729   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1730   SDValue ArgValue;
1731 
1732   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1733   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1734   MVT MemVT = VA.getValVT();
1735 
1736   switch (VA.getLocInfo()) {
1737   default:
1738     break;
1739   case CCValAssign::BCvt:
1740     MemVT = VA.getLocVT();
1741     break;
1742   case CCValAssign::SExt:
1743     ExtType = ISD::SEXTLOAD;
1744     break;
1745   case CCValAssign::ZExt:
1746     ExtType = ISD::ZEXTLOAD;
1747     break;
1748   case CCValAssign::AExt:
1749     ExtType = ISD::EXTLOAD;
1750     break;
1751   }
1752 
1753   ArgValue = DAG.getExtLoad(
1754     ExtType, SL, VA.getLocVT(), Chain, FIN,
1755     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1756     MemVT);
1757   return ArgValue;
1758 }
1759 
1760 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1761   const SIMachineFunctionInfo &MFI,
1762   EVT VT,
1763   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1764   const ArgDescriptor *Reg;
1765   const TargetRegisterClass *RC;
1766   LLT Ty;
1767 
1768   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1769   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1770 }
1771 
1772 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1773                                CallingConv::ID CallConv,
1774                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1775                                FunctionType *FType,
1776                                SIMachineFunctionInfo *Info) {
1777   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1778     const ISD::InputArg *Arg = &Ins[I];
1779 
1780     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1781            "vector type argument should have been split");
1782 
1783     // First check if it's a PS input addr.
1784     if (CallConv == CallingConv::AMDGPU_PS &&
1785         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1786       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1787 
1788       // Inconveniently only the first part of the split is marked as isSplit,
1789       // so skip to the end. We only want to increment PSInputNum once for the
1790       // entire split argument.
1791       if (Arg->Flags.isSplit()) {
1792         while (!Arg->Flags.isSplitEnd()) {
1793           assert((!Arg->VT.isVector() ||
1794                   Arg->VT.getScalarSizeInBits() == 16) &&
1795                  "unexpected vector split in ps argument type");
1796           if (!SkipArg)
1797             Splits.push_back(*Arg);
1798           Arg = &Ins[++I];
1799         }
1800       }
1801 
1802       if (SkipArg) {
1803         // We can safely skip PS inputs.
1804         Skipped.set(Arg->getOrigArgIndex());
1805         ++PSInputNum;
1806         continue;
1807       }
1808 
1809       Info->markPSInputAllocated(PSInputNum);
1810       if (Arg->Used)
1811         Info->markPSInputEnabled(PSInputNum);
1812 
1813       ++PSInputNum;
1814     }
1815 
1816     Splits.push_back(*Arg);
1817   }
1818 }
1819 
1820 // Allocate special inputs passed in VGPRs.
1821 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1822                                                       MachineFunction &MF,
1823                                                       const SIRegisterInfo &TRI,
1824                                                       SIMachineFunctionInfo &Info) const {
1825   const LLT S32 = LLT::scalar(32);
1826   MachineRegisterInfo &MRI = MF.getRegInfo();
1827 
1828   if (Info.hasWorkItemIDX()) {
1829     Register Reg = AMDGPU::VGPR0;
1830     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1831 
1832     CCInfo.AllocateReg(Reg);
1833     unsigned Mask = (Subtarget->hasPackedTID() &&
1834                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1835     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1836   }
1837 
1838   if (Info.hasWorkItemIDY()) {
1839     assert(Info.hasWorkItemIDX());
1840     if (Subtarget->hasPackedTID()) {
1841       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1842                                                         0x3ff << 10));
1843     } else {
1844       unsigned Reg = AMDGPU::VGPR1;
1845       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1846 
1847       CCInfo.AllocateReg(Reg);
1848       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1849     }
1850   }
1851 
1852   if (Info.hasWorkItemIDZ()) {
1853     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1854     if (Subtarget->hasPackedTID()) {
1855       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1856                                                         0x3ff << 20));
1857     } else {
1858       unsigned Reg = AMDGPU::VGPR2;
1859       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1860 
1861       CCInfo.AllocateReg(Reg);
1862       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1863     }
1864   }
1865 }
1866 
1867 // Try to allocate a VGPR at the end of the argument list, or if no argument
1868 // VGPRs are left allocating a stack slot.
1869 // If \p Mask is is given it indicates bitfield position in the register.
1870 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1871 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1872                                          ArgDescriptor Arg = ArgDescriptor()) {
1873   if (Arg.isSet())
1874     return ArgDescriptor::createArg(Arg, Mask);
1875 
1876   ArrayRef<MCPhysReg> ArgVGPRs
1877     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1878   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1879   if (RegIdx == ArgVGPRs.size()) {
1880     // Spill to stack required.
1881     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1882 
1883     return ArgDescriptor::createStack(Offset, Mask);
1884   }
1885 
1886   unsigned Reg = ArgVGPRs[RegIdx];
1887   Reg = CCInfo.AllocateReg(Reg);
1888   assert(Reg != AMDGPU::NoRegister);
1889 
1890   MachineFunction &MF = CCInfo.getMachineFunction();
1891   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1892   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1893   return ArgDescriptor::createRegister(Reg, Mask);
1894 }
1895 
1896 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1897                                              const TargetRegisterClass *RC,
1898                                              unsigned NumArgRegs) {
1899   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1900   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1901   if (RegIdx == ArgSGPRs.size())
1902     report_fatal_error("ran out of SGPRs for arguments");
1903 
1904   unsigned Reg = ArgSGPRs[RegIdx];
1905   Reg = CCInfo.AllocateReg(Reg);
1906   assert(Reg != AMDGPU::NoRegister);
1907 
1908   MachineFunction &MF = CCInfo.getMachineFunction();
1909   MF.addLiveIn(Reg, RC);
1910   return ArgDescriptor::createRegister(Reg);
1911 }
1912 
1913 // If this has a fixed position, we still should allocate the register in the
1914 // CCInfo state. Technically we could get away with this for values passed
1915 // outside of the normal argument range.
1916 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1917                                        const TargetRegisterClass *RC,
1918                                        MCRegister Reg) {
1919   Reg = CCInfo.AllocateReg(Reg);
1920   assert(Reg != AMDGPU::NoRegister);
1921   MachineFunction &MF = CCInfo.getMachineFunction();
1922   MF.addLiveIn(Reg, RC);
1923 }
1924 
1925 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1926   if (Arg) {
1927     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1928                                Arg.getRegister());
1929   } else
1930     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1931 }
1932 
1933 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1934   if (Arg) {
1935     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1936                                Arg.getRegister());
1937   } else
1938     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1939 }
1940 
1941 /// Allocate implicit function VGPR arguments at the end of allocated user
1942 /// arguments.
1943 void SITargetLowering::allocateSpecialInputVGPRs(
1944   CCState &CCInfo, MachineFunction &MF,
1945   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1946   const unsigned Mask = 0x3ff;
1947   ArgDescriptor Arg;
1948 
1949   if (Info.hasWorkItemIDX()) {
1950     Arg = allocateVGPR32Input(CCInfo, Mask);
1951     Info.setWorkItemIDX(Arg);
1952   }
1953 
1954   if (Info.hasWorkItemIDY()) {
1955     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1956     Info.setWorkItemIDY(Arg);
1957   }
1958 
1959   if (Info.hasWorkItemIDZ())
1960     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1961 }
1962 
1963 /// Allocate implicit function VGPR arguments in fixed registers.
1964 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1965   CCState &CCInfo, MachineFunction &MF,
1966   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1967   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1968   if (!Reg)
1969     report_fatal_error("failed to allocated VGPR for implicit arguments");
1970 
1971   const unsigned Mask = 0x3ff;
1972   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1973   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1974   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1975 }
1976 
1977 void SITargetLowering::allocateSpecialInputSGPRs(
1978   CCState &CCInfo,
1979   MachineFunction &MF,
1980   const SIRegisterInfo &TRI,
1981   SIMachineFunctionInfo &Info) const {
1982   auto &ArgInfo = Info.getArgInfo();
1983 
1984   // TODO: Unify handling with private memory pointers.
1985 
1986   if (Info.hasDispatchPtr())
1987     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1988 
1989   if (Info.hasQueuePtr())
1990     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1991 
1992   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1993   // constant offset from the kernarg segment.
1994   if (Info.hasImplicitArgPtr())
1995     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1996 
1997   if (Info.hasDispatchID())
1998     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
1999 
2000   // flat_scratch_init is not applicable for non-kernel functions.
2001 
2002   if (Info.hasWorkGroupIDX())
2003     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2004 
2005   if (Info.hasWorkGroupIDY())
2006     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2007 
2008   if (Info.hasWorkGroupIDZ())
2009     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2010 }
2011 
2012 // Allocate special inputs passed in user SGPRs.
2013 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2014                                             MachineFunction &MF,
2015                                             const SIRegisterInfo &TRI,
2016                                             SIMachineFunctionInfo &Info) const {
2017   if (Info.hasImplicitBufferPtr()) {
2018     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2019     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2020     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2021   }
2022 
2023   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2024   if (Info.hasPrivateSegmentBuffer()) {
2025     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2026     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2027     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2028   }
2029 
2030   if (Info.hasDispatchPtr()) {
2031     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2032     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2033     CCInfo.AllocateReg(DispatchPtrReg);
2034   }
2035 
2036   if (Info.hasQueuePtr()) {
2037     Register QueuePtrReg = Info.addQueuePtr(TRI);
2038     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2039     CCInfo.AllocateReg(QueuePtrReg);
2040   }
2041 
2042   if (Info.hasKernargSegmentPtr()) {
2043     MachineRegisterInfo &MRI = MF.getRegInfo();
2044     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2045     CCInfo.AllocateReg(InputPtrReg);
2046 
2047     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2048     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2049   }
2050 
2051   if (Info.hasDispatchID()) {
2052     Register DispatchIDReg = Info.addDispatchID(TRI);
2053     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2054     CCInfo.AllocateReg(DispatchIDReg);
2055   }
2056 
2057   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2058     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2059     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2060     CCInfo.AllocateReg(FlatScratchInitReg);
2061   }
2062 
2063   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2064   // these from the dispatch pointer.
2065 }
2066 
2067 // Allocate special input registers that are initialized per-wave.
2068 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2069                                            MachineFunction &MF,
2070                                            SIMachineFunctionInfo &Info,
2071                                            CallingConv::ID CallConv,
2072                                            bool IsShader) const {
2073   if (Info.hasWorkGroupIDX()) {
2074     Register Reg = Info.addWorkGroupIDX();
2075     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2076     CCInfo.AllocateReg(Reg);
2077   }
2078 
2079   if (Info.hasWorkGroupIDY()) {
2080     Register Reg = Info.addWorkGroupIDY();
2081     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2082     CCInfo.AllocateReg(Reg);
2083   }
2084 
2085   if (Info.hasWorkGroupIDZ()) {
2086     Register Reg = Info.addWorkGroupIDZ();
2087     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2088     CCInfo.AllocateReg(Reg);
2089   }
2090 
2091   if (Info.hasWorkGroupInfo()) {
2092     Register Reg = Info.addWorkGroupInfo();
2093     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2094     CCInfo.AllocateReg(Reg);
2095   }
2096 
2097   if (Info.hasPrivateSegmentWaveByteOffset()) {
2098     // Scratch wave offset passed in system SGPR.
2099     unsigned PrivateSegmentWaveByteOffsetReg;
2100 
2101     if (IsShader) {
2102       PrivateSegmentWaveByteOffsetReg =
2103         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2104 
2105       // This is true if the scratch wave byte offset doesn't have a fixed
2106       // location.
2107       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2108         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2109         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2110       }
2111     } else
2112       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2113 
2114     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2115     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2116   }
2117 }
2118 
2119 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2120                                      MachineFunction &MF,
2121                                      const SIRegisterInfo &TRI,
2122                                      SIMachineFunctionInfo &Info) {
2123   // Now that we've figured out where the scratch register inputs are, see if
2124   // should reserve the arguments and use them directly.
2125   MachineFrameInfo &MFI = MF.getFrameInfo();
2126   bool HasStackObjects = MFI.hasStackObjects();
2127   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2128 
2129   // Record that we know we have non-spill stack objects so we don't need to
2130   // check all stack objects later.
2131   if (HasStackObjects)
2132     Info.setHasNonSpillStackObjects(true);
2133 
2134   // Everything live out of a block is spilled with fast regalloc, so it's
2135   // almost certain that spilling will be required.
2136   if (TM.getOptLevel() == CodeGenOpt::None)
2137     HasStackObjects = true;
2138 
2139   // For now assume stack access is needed in any callee functions, so we need
2140   // the scratch registers to pass in.
2141   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2142 
2143   if (!ST.enableFlatScratch()) {
2144     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2145       // If we have stack objects, we unquestionably need the private buffer
2146       // resource. For the Code Object V2 ABI, this will be the first 4 user
2147       // SGPR inputs. We can reserve those and use them directly.
2148 
2149       Register PrivateSegmentBufferReg =
2150           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2151       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2152     } else {
2153       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2154       // We tentatively reserve the last registers (skipping the last registers
2155       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2156       // we'll replace these with the ones immediately after those which were
2157       // really allocated. In the prologue copies will be inserted from the
2158       // argument to these reserved registers.
2159 
2160       // Without HSA, relocations are used for the scratch pointer and the
2161       // buffer resource setup is always inserted in the prologue. Scratch wave
2162       // offset is still in an input SGPR.
2163       Info.setScratchRSrcReg(ReservedBufferReg);
2164     }
2165   }
2166 
2167   MachineRegisterInfo &MRI = MF.getRegInfo();
2168 
2169   // For entry functions we have to set up the stack pointer if we use it,
2170   // whereas non-entry functions get this "for free". This means there is no
2171   // intrinsic advantage to using S32 over S34 in cases where we do not have
2172   // calls but do need a frame pointer (i.e. if we are requested to have one
2173   // because frame pointer elimination is disabled). To keep things simple we
2174   // only ever use S32 as the call ABI stack pointer, and so using it does not
2175   // imply we need a separate frame pointer.
2176   //
2177   // Try to use s32 as the SP, but move it if it would interfere with input
2178   // arguments. This won't work with calls though.
2179   //
2180   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2181   // registers.
2182   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2183     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2184   } else {
2185     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2186 
2187     if (MFI.hasCalls())
2188       report_fatal_error("call in graphics shader with too many input SGPRs");
2189 
2190     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2191       if (!MRI.isLiveIn(Reg)) {
2192         Info.setStackPtrOffsetReg(Reg);
2193         break;
2194       }
2195     }
2196 
2197     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2198       report_fatal_error("failed to find register for SP");
2199   }
2200 
2201   // hasFP should be accurate for entry functions even before the frame is
2202   // finalized, because it does not rely on the known stack size, only
2203   // properties like whether variable sized objects are present.
2204   if (ST.getFrameLowering()->hasFP(MF)) {
2205     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2206   }
2207 }
2208 
2209 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2210   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2211   return !Info->isEntryFunction();
2212 }
2213 
2214 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2215 
2216 }
2217 
2218 void SITargetLowering::insertCopiesSplitCSR(
2219   MachineBasicBlock *Entry,
2220   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2221   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2222 
2223   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2224   if (!IStart)
2225     return;
2226 
2227   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2228   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2229   MachineBasicBlock::iterator MBBI = Entry->begin();
2230   for (const MCPhysReg *I = IStart; *I; ++I) {
2231     const TargetRegisterClass *RC = nullptr;
2232     if (AMDGPU::SReg_64RegClass.contains(*I))
2233       RC = &AMDGPU::SGPR_64RegClass;
2234     else if (AMDGPU::SReg_32RegClass.contains(*I))
2235       RC = &AMDGPU::SGPR_32RegClass;
2236     else
2237       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2238 
2239     Register NewVR = MRI->createVirtualRegister(RC);
2240     // Create copy from CSR to a virtual register.
2241     Entry->addLiveIn(*I);
2242     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2243       .addReg(*I);
2244 
2245     // Insert the copy-back instructions right before the terminator.
2246     for (auto *Exit : Exits)
2247       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2248               TII->get(TargetOpcode::COPY), *I)
2249         .addReg(NewVR);
2250   }
2251 }
2252 
2253 SDValue SITargetLowering::LowerFormalArguments(
2254     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2255     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2256     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2257   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2258 
2259   MachineFunction &MF = DAG.getMachineFunction();
2260   const Function &Fn = MF.getFunction();
2261   FunctionType *FType = MF.getFunction().getFunctionType();
2262   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2263 
2264   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2265     DiagnosticInfoUnsupported NoGraphicsHSA(
2266         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2267     DAG.getContext()->diagnose(NoGraphicsHSA);
2268     return DAG.getEntryNode();
2269   }
2270 
2271   Info->allocateModuleLDSGlobal(Fn.getParent());
2272 
2273   SmallVector<ISD::InputArg, 16> Splits;
2274   SmallVector<CCValAssign, 16> ArgLocs;
2275   BitVector Skipped(Ins.size());
2276   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2277                  *DAG.getContext());
2278 
2279   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2280   bool IsKernel = AMDGPU::isKernel(CallConv);
2281   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2282 
2283   if (IsGraphics) {
2284     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2285            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2286            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2287            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2288            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2289            !Info->hasWorkItemIDZ());
2290   }
2291 
2292   if (CallConv == CallingConv::AMDGPU_PS) {
2293     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2294 
2295     // At least one interpolation mode must be enabled or else the GPU will
2296     // hang.
2297     //
2298     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2299     // set PSInputAddr, the user wants to enable some bits after the compilation
2300     // based on run-time states. Since we can't know what the final PSInputEna
2301     // will look like, so we shouldn't do anything here and the user should take
2302     // responsibility for the correct programming.
2303     //
2304     // Otherwise, the following restrictions apply:
2305     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2306     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2307     //   enabled too.
2308     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2309         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2310       CCInfo.AllocateReg(AMDGPU::VGPR0);
2311       CCInfo.AllocateReg(AMDGPU::VGPR1);
2312       Info->markPSInputAllocated(0);
2313       Info->markPSInputEnabled(0);
2314     }
2315     if (Subtarget->isAmdPalOS()) {
2316       // For isAmdPalOS, the user does not enable some bits after compilation
2317       // based on run-time states; the register values being generated here are
2318       // the final ones set in hardware. Therefore we need to apply the
2319       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2320       // a bit is set in PSInputAddr but not PSInputEnable is where the
2321       // frontend set up an input arg for a particular interpolation mode, but
2322       // nothing uses that input arg. Really we should have an earlier pass
2323       // that removes such an arg.)
2324       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2325       if ((PsInputBits & 0x7F) == 0 ||
2326           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2327         Info->markPSInputEnabled(
2328             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2329     }
2330   } else if (IsKernel) {
2331     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2332   } else {
2333     Splits.append(Ins.begin(), Ins.end());
2334   }
2335 
2336   if (IsEntryFunc) {
2337     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2338     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2339   } else {
2340     // For the fixed ABI, pass workitem IDs in the last argument register.
2341     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2342       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2343   }
2344 
2345   if (IsKernel) {
2346     analyzeFormalArgumentsCompute(CCInfo, Ins);
2347   } else {
2348     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2349     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2350   }
2351 
2352   SmallVector<SDValue, 16> Chains;
2353 
2354   // FIXME: This is the minimum kernel argument alignment. We should improve
2355   // this to the maximum alignment of the arguments.
2356   //
2357   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2358   // kern arg offset.
2359   const Align KernelArgBaseAlign = Align(16);
2360 
2361   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2362     const ISD::InputArg &Arg = Ins[i];
2363     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2364       InVals.push_back(DAG.getUNDEF(Arg.VT));
2365       continue;
2366     }
2367 
2368     CCValAssign &VA = ArgLocs[ArgIdx++];
2369     MVT VT = VA.getLocVT();
2370 
2371     if (IsEntryFunc && VA.isMemLoc()) {
2372       VT = Ins[i].VT;
2373       EVT MemVT = VA.getLocVT();
2374 
2375       const uint64_t Offset = VA.getLocMemOffset();
2376       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2377 
2378       if (Arg.Flags.isByRef()) {
2379         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2380 
2381         const GCNTargetMachine &TM =
2382             static_cast<const GCNTargetMachine &>(getTargetMachine());
2383         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2384                                     Arg.Flags.getPointerAddrSpace())) {
2385           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2386                                      Arg.Flags.getPointerAddrSpace());
2387         }
2388 
2389         InVals.push_back(Ptr);
2390         continue;
2391       }
2392 
2393       SDValue Arg = lowerKernargMemParameter(
2394         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2395       Chains.push_back(Arg.getValue(1));
2396 
2397       auto *ParamTy =
2398         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2399       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2400           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2401                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2402         // On SI local pointers are just offsets into LDS, so they are always
2403         // less than 16-bits.  On CI and newer they could potentially be
2404         // real pointers, so we can't guarantee their size.
2405         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2406                           DAG.getValueType(MVT::i16));
2407       }
2408 
2409       InVals.push_back(Arg);
2410       continue;
2411     } else if (!IsEntryFunc && VA.isMemLoc()) {
2412       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2413       InVals.push_back(Val);
2414       if (!Arg.Flags.isByVal())
2415         Chains.push_back(Val.getValue(1));
2416       continue;
2417     }
2418 
2419     assert(VA.isRegLoc() && "Parameter must be in a register!");
2420 
2421     Register Reg = VA.getLocReg();
2422     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2423     EVT ValVT = VA.getValVT();
2424 
2425     Reg = MF.addLiveIn(Reg, RC);
2426     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2427 
2428     if (Arg.Flags.isSRet()) {
2429       // The return object should be reasonably addressable.
2430 
2431       // FIXME: This helps when the return is a real sret. If it is a
2432       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2433       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2434       unsigned NumBits
2435         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2436       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2437         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2438     }
2439 
2440     // If this is an 8 or 16-bit value, it is really passed promoted
2441     // to 32 bits. Insert an assert[sz]ext to capture this, then
2442     // truncate to the right size.
2443     switch (VA.getLocInfo()) {
2444     case CCValAssign::Full:
2445       break;
2446     case CCValAssign::BCvt:
2447       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2448       break;
2449     case CCValAssign::SExt:
2450       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2451                         DAG.getValueType(ValVT));
2452       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2453       break;
2454     case CCValAssign::ZExt:
2455       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2456                         DAG.getValueType(ValVT));
2457       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2458       break;
2459     case CCValAssign::AExt:
2460       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2461       break;
2462     default:
2463       llvm_unreachable("Unknown loc info!");
2464     }
2465 
2466     InVals.push_back(Val);
2467   }
2468 
2469   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2470     // Special inputs come after user arguments.
2471     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2472   }
2473 
2474   // Start adding system SGPRs.
2475   if (IsEntryFunc) {
2476     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2477   } else {
2478     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2479     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2480   }
2481 
2482   auto &ArgUsageInfo =
2483     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2484   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2485 
2486   unsigned StackArgSize = CCInfo.getNextStackOffset();
2487   Info->setBytesInStackArgArea(StackArgSize);
2488 
2489   return Chains.empty() ? Chain :
2490     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2491 }
2492 
2493 // TODO: If return values can't fit in registers, we should return as many as
2494 // possible in registers before passing on stack.
2495 bool SITargetLowering::CanLowerReturn(
2496   CallingConv::ID CallConv,
2497   MachineFunction &MF, bool IsVarArg,
2498   const SmallVectorImpl<ISD::OutputArg> &Outs,
2499   LLVMContext &Context) const {
2500   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2501   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2502   // for shaders. Vector types should be explicitly handled by CC.
2503   if (AMDGPU::isEntryFunctionCC(CallConv))
2504     return true;
2505 
2506   SmallVector<CCValAssign, 16> RVLocs;
2507   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2508   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2509 }
2510 
2511 SDValue
2512 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2513                               bool isVarArg,
2514                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2515                               const SmallVectorImpl<SDValue> &OutVals,
2516                               const SDLoc &DL, SelectionDAG &DAG) const {
2517   MachineFunction &MF = DAG.getMachineFunction();
2518   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2519 
2520   if (AMDGPU::isKernel(CallConv)) {
2521     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2522                                              OutVals, DL, DAG);
2523   }
2524 
2525   bool IsShader = AMDGPU::isShader(CallConv);
2526 
2527   Info->setIfReturnsVoid(Outs.empty());
2528   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2529 
2530   // CCValAssign - represent the assignment of the return value to a location.
2531   SmallVector<CCValAssign, 48> RVLocs;
2532   SmallVector<ISD::OutputArg, 48> Splits;
2533 
2534   // CCState - Info about the registers and stack slots.
2535   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2536                  *DAG.getContext());
2537 
2538   // Analyze outgoing return values.
2539   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2540 
2541   SDValue Flag;
2542   SmallVector<SDValue, 48> RetOps;
2543   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2544 
2545   // Add return address for callable functions.
2546   if (!Info->isEntryFunction()) {
2547     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2548     SDValue ReturnAddrReg = CreateLiveInRegister(
2549       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2550 
2551     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2552         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2553         MVT::i64);
2554     Chain =
2555         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2556     Flag = Chain.getValue(1);
2557     RetOps.push_back(ReturnAddrVirtualReg);
2558   }
2559 
2560   // Copy the result values into the output registers.
2561   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2562        ++I, ++RealRVLocIdx) {
2563     CCValAssign &VA = RVLocs[I];
2564     assert(VA.isRegLoc() && "Can only return in registers!");
2565     // TODO: Partially return in registers if return values don't fit.
2566     SDValue Arg = OutVals[RealRVLocIdx];
2567 
2568     // Copied from other backends.
2569     switch (VA.getLocInfo()) {
2570     case CCValAssign::Full:
2571       break;
2572     case CCValAssign::BCvt:
2573       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2574       break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2583       break;
2584     default:
2585       llvm_unreachable("Unknown loc info!");
2586     }
2587 
2588     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2589     Flag = Chain.getValue(1);
2590     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2591   }
2592 
2593   // FIXME: Does sret work properly?
2594   if (!Info->isEntryFunction()) {
2595     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2596     const MCPhysReg *I =
2597       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2598     if (I) {
2599       for (; *I; ++I) {
2600         if (AMDGPU::SReg_64RegClass.contains(*I))
2601           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2602         else if (AMDGPU::SReg_32RegClass.contains(*I))
2603           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2604         else
2605           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2606       }
2607     }
2608   }
2609 
2610   // Update chain and glue.
2611   RetOps[0] = Chain;
2612   if (Flag.getNode())
2613     RetOps.push_back(Flag);
2614 
2615   unsigned Opc = AMDGPUISD::ENDPGM;
2616   if (!IsWaveEnd)
2617     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2618   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2619 }
2620 
2621 SDValue SITargetLowering::LowerCallResult(
2622     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2623     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2624     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2625     SDValue ThisVal) const {
2626   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2627 
2628   // Assign locations to each value returned by this call.
2629   SmallVector<CCValAssign, 16> RVLocs;
2630   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2631                  *DAG.getContext());
2632   CCInfo.AnalyzeCallResult(Ins, RetCC);
2633 
2634   // Copy all of the result registers out of their specified physreg.
2635   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2636     CCValAssign VA = RVLocs[i];
2637     SDValue Val;
2638 
2639     if (VA.isRegLoc()) {
2640       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2641       Chain = Val.getValue(1);
2642       InFlag = Val.getValue(2);
2643     } else if (VA.isMemLoc()) {
2644       report_fatal_error("TODO: return values in memory");
2645     } else
2646       llvm_unreachable("unknown argument location type");
2647 
2648     switch (VA.getLocInfo()) {
2649     case CCValAssign::Full:
2650       break;
2651     case CCValAssign::BCvt:
2652       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2653       break;
2654     case CCValAssign::ZExt:
2655       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2656                         DAG.getValueType(VA.getValVT()));
2657       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2658       break;
2659     case CCValAssign::SExt:
2660       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2661                         DAG.getValueType(VA.getValVT()));
2662       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2663       break;
2664     case CCValAssign::AExt:
2665       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2666       break;
2667     default:
2668       llvm_unreachable("Unknown loc info!");
2669     }
2670 
2671     InVals.push_back(Val);
2672   }
2673 
2674   return Chain;
2675 }
2676 
2677 // Add code to pass special inputs required depending on used features separate
2678 // from the explicit user arguments present in the IR.
2679 void SITargetLowering::passSpecialInputs(
2680     CallLoweringInfo &CLI,
2681     CCState &CCInfo,
2682     const SIMachineFunctionInfo &Info,
2683     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2684     SmallVectorImpl<SDValue> &MemOpChains,
2685     SDValue Chain) const {
2686   // If we don't have a call site, this was a call inserted by
2687   // legalization. These can never use special inputs.
2688   if (!CLI.CB)
2689     return;
2690 
2691   SelectionDAG &DAG = CLI.DAG;
2692   const SDLoc &DL = CLI.DL;
2693 
2694   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2695   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2696 
2697   const AMDGPUFunctionArgInfo *CalleeArgInfo
2698     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2699   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2700     auto &ArgUsageInfo =
2701       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2702     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2703   }
2704 
2705   // TODO: Unify with private memory register handling. This is complicated by
2706   // the fact that at least in kernels, the input argument is not necessarily
2707   // in the same location as the input.
2708   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2709     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2710     AMDGPUFunctionArgInfo::QUEUE_PTR,
2711     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2712     AMDGPUFunctionArgInfo::DISPATCH_ID,
2713     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2714     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2715     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2716   };
2717 
2718   for (auto InputID : InputRegs) {
2719     const ArgDescriptor *OutgoingArg;
2720     const TargetRegisterClass *ArgRC;
2721     LLT ArgTy;
2722 
2723     std::tie(OutgoingArg, ArgRC, ArgTy) =
2724         CalleeArgInfo->getPreloadedValue(InputID);
2725     if (!OutgoingArg)
2726       continue;
2727 
2728     const ArgDescriptor *IncomingArg;
2729     const TargetRegisterClass *IncomingArgRC;
2730     LLT Ty;
2731     std::tie(IncomingArg, IncomingArgRC, Ty) =
2732         CallerArgInfo.getPreloadedValue(InputID);
2733     assert(IncomingArgRC == ArgRC);
2734 
2735     // All special arguments are ints for now.
2736     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2737     SDValue InputReg;
2738 
2739     if (IncomingArg) {
2740       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2741     } else {
2742       // The implicit arg ptr is special because it doesn't have a corresponding
2743       // input for kernels, and is computed from the kernarg segment pointer.
2744       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2745       InputReg = getImplicitArgPtr(DAG, DL);
2746     }
2747 
2748     if (OutgoingArg->isRegister()) {
2749       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2750       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2751         report_fatal_error("failed to allocate implicit input argument");
2752     } else {
2753       unsigned SpecialArgOffset =
2754           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2755       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2756                                               SpecialArgOffset);
2757       MemOpChains.push_back(ArgStore);
2758     }
2759   }
2760 
2761   // Pack workitem IDs into a single register or pass it as is if already
2762   // packed.
2763   const ArgDescriptor *OutgoingArg;
2764   const TargetRegisterClass *ArgRC;
2765   LLT Ty;
2766 
2767   std::tie(OutgoingArg, ArgRC, Ty) =
2768       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2769   if (!OutgoingArg)
2770     std::tie(OutgoingArg, ArgRC, Ty) =
2771         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2772   if (!OutgoingArg)
2773     std::tie(OutgoingArg, ArgRC, Ty) =
2774         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2775   if (!OutgoingArg)
2776     return;
2777 
2778   const ArgDescriptor *IncomingArgX = std::get<0>(
2779       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2780   const ArgDescriptor *IncomingArgY = std::get<0>(
2781       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2782   const ArgDescriptor *IncomingArgZ = std::get<0>(
2783       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2784 
2785   SDValue InputReg;
2786   SDLoc SL;
2787 
2788   // If incoming ids are not packed we need to pack them.
2789   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2790     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2791 
2792   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2793     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2794     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2795                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2796     InputReg = InputReg.getNode() ?
2797                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2798   }
2799 
2800   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2801     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2802     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2803                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2804     InputReg = InputReg.getNode() ?
2805                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2806   }
2807 
2808   if (!InputReg.getNode()) {
2809     // Workitem ids are already packed, any of present incoming arguments
2810     // will carry all required fields.
2811     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2812       IncomingArgX ? *IncomingArgX :
2813       IncomingArgY ? *IncomingArgY :
2814                      *IncomingArgZ, ~0u);
2815     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2816   }
2817 
2818   if (OutgoingArg->isRegister()) {
2819     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2820     CCInfo.AllocateReg(OutgoingArg->getRegister());
2821   } else {
2822     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2823     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2824                                             SpecialArgOffset);
2825     MemOpChains.push_back(ArgStore);
2826   }
2827 }
2828 
2829 static bool canGuaranteeTCO(CallingConv::ID CC) {
2830   return CC == CallingConv::Fast;
2831 }
2832 
2833 /// Return true if we might ever do TCO for calls with this calling convention.
2834 static bool mayTailCallThisCC(CallingConv::ID CC) {
2835   switch (CC) {
2836   case CallingConv::C:
2837   case CallingConv::AMDGPU_Gfx:
2838     return true;
2839   default:
2840     return canGuaranteeTCO(CC);
2841   }
2842 }
2843 
2844 bool SITargetLowering::isEligibleForTailCallOptimization(
2845     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2846     const SmallVectorImpl<ISD::OutputArg> &Outs,
2847     const SmallVectorImpl<SDValue> &OutVals,
2848     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2849   if (!mayTailCallThisCC(CalleeCC))
2850     return false;
2851 
2852   // For a divergent call target, we need to do a waterfall loop over the
2853   // possible callees which precludes us from using a simple jump.
2854   if (Callee->isDivergent())
2855     return false;
2856 
2857   MachineFunction &MF = DAG.getMachineFunction();
2858   const Function &CallerF = MF.getFunction();
2859   CallingConv::ID CallerCC = CallerF.getCallingConv();
2860   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2861   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2862 
2863   // Kernels aren't callable, and don't have a live in return address so it
2864   // doesn't make sense to do a tail call with entry functions.
2865   if (!CallerPreserved)
2866     return false;
2867 
2868   bool CCMatch = CallerCC == CalleeCC;
2869 
2870   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2871     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2872       return true;
2873     return false;
2874   }
2875 
2876   // TODO: Can we handle var args?
2877   if (IsVarArg)
2878     return false;
2879 
2880   for (const Argument &Arg : CallerF.args()) {
2881     if (Arg.hasByValAttr())
2882       return false;
2883   }
2884 
2885   LLVMContext &Ctx = *DAG.getContext();
2886 
2887   // Check that the call results are passed in the same way.
2888   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2889                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2890                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2891     return false;
2892 
2893   // The callee has to preserve all registers the caller needs to preserve.
2894   if (!CCMatch) {
2895     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2896     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2897       return false;
2898   }
2899 
2900   // Nothing more to check if the callee is taking no arguments.
2901   if (Outs.empty())
2902     return true;
2903 
2904   SmallVector<CCValAssign, 16> ArgLocs;
2905   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2906 
2907   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2908 
2909   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2910   // If the stack arguments for this call do not fit into our own save area then
2911   // the call cannot be made tail.
2912   // TODO: Is this really necessary?
2913   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2914     return false;
2915 
2916   const MachineRegisterInfo &MRI = MF.getRegInfo();
2917   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2918 }
2919 
2920 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2921   if (!CI->isTailCall())
2922     return false;
2923 
2924   const Function *ParentFn = CI->getParent()->getParent();
2925   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2926     return false;
2927   return true;
2928 }
2929 
2930 // The wave scratch offset register is used as the global base pointer.
2931 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2932                                     SmallVectorImpl<SDValue> &InVals) const {
2933   SelectionDAG &DAG = CLI.DAG;
2934   const SDLoc &DL = CLI.DL;
2935   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2936   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2937   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2938   SDValue Chain = CLI.Chain;
2939   SDValue Callee = CLI.Callee;
2940   bool &IsTailCall = CLI.IsTailCall;
2941   CallingConv::ID CallConv = CLI.CallConv;
2942   bool IsVarArg = CLI.IsVarArg;
2943   bool IsSibCall = false;
2944   bool IsThisReturn = false;
2945   MachineFunction &MF = DAG.getMachineFunction();
2946 
2947   if (Callee.isUndef() || isNullConstant(Callee)) {
2948     if (!CLI.IsTailCall) {
2949       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2950         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2951     }
2952 
2953     return Chain;
2954   }
2955 
2956   if (IsVarArg) {
2957     return lowerUnhandledCall(CLI, InVals,
2958                               "unsupported call to variadic function ");
2959   }
2960 
2961   if (!CLI.CB)
2962     report_fatal_error("unsupported libcall legalization");
2963 
2964   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2965     return lowerUnhandledCall(CLI, InVals,
2966                               "unsupported required tail call to function ");
2967   }
2968 
2969   if (AMDGPU::isShader(CallConv)) {
2970     // Note the issue is with the CC of the called function, not of the call
2971     // itself.
2972     return lowerUnhandledCall(CLI, InVals,
2973                               "unsupported call to a shader function ");
2974   }
2975 
2976   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2977       CallConv != CallingConv::AMDGPU_Gfx) {
2978     // Only allow calls with specific calling conventions.
2979     return lowerUnhandledCall(CLI, InVals,
2980                               "unsupported calling convention for call from "
2981                               "graphics shader of function ");
2982   }
2983 
2984   if (IsTailCall) {
2985     IsTailCall = isEligibleForTailCallOptimization(
2986       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2987     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2988       report_fatal_error("failed to perform tail call elimination on a call "
2989                          "site marked musttail");
2990     }
2991 
2992     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2993 
2994     // A sibling call is one where we're under the usual C ABI and not planning
2995     // to change that but can still do a tail call:
2996     if (!TailCallOpt && IsTailCall)
2997       IsSibCall = true;
2998 
2999     if (IsTailCall)
3000       ++NumTailCalls;
3001   }
3002 
3003   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3004   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3005   SmallVector<SDValue, 8> MemOpChains;
3006 
3007   // Analyze operands of the call, assigning locations to each operand.
3008   SmallVector<CCValAssign, 16> ArgLocs;
3009   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3010   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3011 
3012   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3013       CallConv != CallingConv::AMDGPU_Gfx) {
3014     // With a fixed ABI, allocate fixed registers before user arguments.
3015     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3016   }
3017 
3018   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3019 
3020   // Get a count of how many bytes are to be pushed on the stack.
3021   unsigned NumBytes = CCInfo.getNextStackOffset();
3022 
3023   if (IsSibCall) {
3024     // Since we're not changing the ABI to make this a tail call, the memory
3025     // operands are already available in the caller's incoming argument space.
3026     NumBytes = 0;
3027   }
3028 
3029   // FPDiff is the byte offset of the call's argument area from the callee's.
3030   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3031   // by this amount for a tail call. In a sibling call it must be 0 because the
3032   // caller will deallocate the entire stack and the callee still expects its
3033   // arguments to begin at SP+0. Completely unused for non-tail calls.
3034   int32_t FPDiff = 0;
3035   MachineFrameInfo &MFI = MF.getFrameInfo();
3036 
3037   // Adjust the stack pointer for the new arguments...
3038   // These operations are automatically eliminated by the prolog/epilog pass
3039   if (!IsSibCall) {
3040     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3041 
3042     if (!Subtarget->enableFlatScratch()) {
3043       SmallVector<SDValue, 4> CopyFromChains;
3044 
3045       // In the HSA case, this should be an identity copy.
3046       SDValue ScratchRSrcReg
3047         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3048       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3049       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3050       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3051     }
3052   }
3053 
3054   MVT PtrVT = MVT::i32;
3055 
3056   // Walk the register/memloc assignments, inserting copies/loads.
3057   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3058     CCValAssign &VA = ArgLocs[i];
3059     SDValue Arg = OutVals[i];
3060 
3061     // Promote the value if needed.
3062     switch (VA.getLocInfo()) {
3063     case CCValAssign::Full:
3064       break;
3065     case CCValAssign::BCvt:
3066       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3067       break;
3068     case CCValAssign::ZExt:
3069       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3070       break;
3071     case CCValAssign::SExt:
3072       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3073       break;
3074     case CCValAssign::AExt:
3075       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3076       break;
3077     case CCValAssign::FPExt:
3078       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3079       break;
3080     default:
3081       llvm_unreachable("Unknown loc info!");
3082     }
3083 
3084     if (VA.isRegLoc()) {
3085       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3086     } else {
3087       assert(VA.isMemLoc());
3088 
3089       SDValue DstAddr;
3090       MachinePointerInfo DstInfo;
3091 
3092       unsigned LocMemOffset = VA.getLocMemOffset();
3093       int32_t Offset = LocMemOffset;
3094 
3095       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3096       MaybeAlign Alignment;
3097 
3098       if (IsTailCall) {
3099         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3100         unsigned OpSize = Flags.isByVal() ?
3101           Flags.getByValSize() : VA.getValVT().getStoreSize();
3102 
3103         // FIXME: We can have better than the minimum byval required alignment.
3104         Alignment =
3105             Flags.isByVal()
3106                 ? Flags.getNonZeroByValAlign()
3107                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3108 
3109         Offset = Offset + FPDiff;
3110         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3111 
3112         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3113         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3114 
3115         // Make sure any stack arguments overlapping with where we're storing
3116         // are loaded before this eventual operation. Otherwise they'll be
3117         // clobbered.
3118 
3119         // FIXME: Why is this really necessary? This seems to just result in a
3120         // lot of code to copy the stack and write them back to the same
3121         // locations, which are supposed to be immutable?
3122         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3123       } else {
3124         // Stores to the argument stack area are relative to the stack pointer.
3125         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3126                                         MVT::i32);
3127         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3128         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3129         Alignment =
3130             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3131       }
3132 
3133       if (Outs[i].Flags.isByVal()) {
3134         SDValue SizeNode =
3135             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3136         SDValue Cpy =
3137             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3138                           Outs[i].Flags.getNonZeroByValAlign(),
3139                           /*isVol = */ false, /*AlwaysInline = */ true,
3140                           /*isTailCall = */ false, DstInfo,
3141                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3142 
3143         MemOpChains.push_back(Cpy);
3144       } else {
3145         SDValue Store =
3146             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3147         MemOpChains.push_back(Store);
3148       }
3149     }
3150   }
3151 
3152   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3153       CallConv != CallingConv::AMDGPU_Gfx) {
3154     // Copy special input registers after user input arguments.
3155     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3156   }
3157 
3158   if (!MemOpChains.empty())
3159     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3160 
3161   // Build a sequence of copy-to-reg nodes chained together with token chain
3162   // and flag operands which copy the outgoing args into the appropriate regs.
3163   SDValue InFlag;
3164   for (auto &RegToPass : RegsToPass) {
3165     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3166                              RegToPass.second, InFlag);
3167     InFlag = Chain.getValue(1);
3168   }
3169 
3170 
3171   SDValue PhysReturnAddrReg;
3172   if (IsTailCall) {
3173     // Since the return is being combined with the call, we need to pass on the
3174     // return address.
3175 
3176     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3177     SDValue ReturnAddrReg = CreateLiveInRegister(
3178       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3179 
3180     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3181                                         MVT::i64);
3182     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3183     InFlag = Chain.getValue(1);
3184   }
3185 
3186   // We don't usually want to end the call-sequence here because we would tidy
3187   // the frame up *after* the call, however in the ABI-changing tail-call case
3188   // we've carefully laid out the parameters so that when sp is reset they'll be
3189   // in the correct location.
3190   if (IsTailCall && !IsSibCall) {
3191     Chain = DAG.getCALLSEQ_END(Chain,
3192                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3193                                DAG.getTargetConstant(0, DL, MVT::i32),
3194                                InFlag, DL);
3195     InFlag = Chain.getValue(1);
3196   }
3197 
3198   std::vector<SDValue> Ops;
3199   Ops.push_back(Chain);
3200   Ops.push_back(Callee);
3201   // Add a redundant copy of the callee global which will not be legalized, as
3202   // we need direct access to the callee later.
3203   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3204     const GlobalValue *GV = GSD->getGlobal();
3205     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3206   } else {
3207     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3208   }
3209 
3210   if (IsTailCall) {
3211     // Each tail call may have to adjust the stack by a different amount, so
3212     // this information must travel along with the operation for eventual
3213     // consumption by emitEpilogue.
3214     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3215 
3216     Ops.push_back(PhysReturnAddrReg);
3217   }
3218 
3219   // Add argument registers to the end of the list so that they are known live
3220   // into the call.
3221   for (auto &RegToPass : RegsToPass) {
3222     Ops.push_back(DAG.getRegister(RegToPass.first,
3223                                   RegToPass.second.getValueType()));
3224   }
3225 
3226   // Add a register mask operand representing the call-preserved registers.
3227 
3228   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3229   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3230   assert(Mask && "Missing call preserved mask for calling convention");
3231   Ops.push_back(DAG.getRegisterMask(Mask));
3232 
3233   if (InFlag.getNode())
3234     Ops.push_back(InFlag);
3235 
3236   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3237 
3238   // If we're doing a tall call, use a TC_RETURN here rather than an
3239   // actual call instruction.
3240   if (IsTailCall) {
3241     MFI.setHasTailCall();
3242     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3243   }
3244 
3245   // Returns a chain and a flag for retval copy to use.
3246   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3247   Chain = Call.getValue(0);
3248   InFlag = Call.getValue(1);
3249 
3250   uint64_t CalleePopBytes = NumBytes;
3251   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3252                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3253                              InFlag, DL);
3254   if (!Ins.empty())
3255     InFlag = Chain.getValue(1);
3256 
3257   // Handle result values, copying them out of physregs into vregs that we
3258   // return.
3259   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3260                          InVals, IsThisReturn,
3261                          IsThisReturn ? OutVals[0] : SDValue());
3262 }
3263 
3264 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3265 // except for applying the wave size scale to the increment amount.
3266 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3267     SDValue Op, SelectionDAG &DAG) const {
3268   const MachineFunction &MF = DAG.getMachineFunction();
3269   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3270 
3271   SDLoc dl(Op);
3272   EVT VT = Op.getValueType();
3273   SDValue Tmp1 = Op;
3274   SDValue Tmp2 = Op.getValue(1);
3275   SDValue Tmp3 = Op.getOperand(2);
3276   SDValue Chain = Tmp1.getOperand(0);
3277 
3278   Register SPReg = Info->getStackPtrOffsetReg();
3279 
3280   // Chain the dynamic stack allocation so that it doesn't modify the stack
3281   // pointer when other instructions are using the stack.
3282   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3283 
3284   SDValue Size  = Tmp2.getOperand(1);
3285   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3286   Chain = SP.getValue(1);
3287   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3288   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3289   const TargetFrameLowering *TFL = ST.getFrameLowering();
3290   unsigned Opc =
3291     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3292     ISD::ADD : ISD::SUB;
3293 
3294   SDValue ScaledSize = DAG.getNode(
3295       ISD::SHL, dl, VT, Size,
3296       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3297 
3298   Align StackAlign = TFL->getStackAlign();
3299   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3300   if (Alignment && *Alignment > StackAlign) {
3301     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3302                        DAG.getConstant(-(uint64_t)Alignment->value()
3303                                            << ST.getWavefrontSizeLog2(),
3304                                        dl, VT));
3305   }
3306 
3307   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3308   Tmp2 = DAG.getCALLSEQ_END(
3309       Chain, DAG.getIntPtrConstant(0, dl, true),
3310       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3311 
3312   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3313 }
3314 
3315 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3316                                                   SelectionDAG &DAG) const {
3317   // We only handle constant sizes here to allow non-entry block, static sized
3318   // allocas. A truly dynamic value is more difficult to support because we
3319   // don't know if the size value is uniform or not. If the size isn't uniform,
3320   // we would need to do a wave reduction to get the maximum size to know how
3321   // much to increment the uniform stack pointer.
3322   SDValue Size = Op.getOperand(1);
3323   if (isa<ConstantSDNode>(Size))
3324       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3325 
3326   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3327 }
3328 
3329 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3330                                              const MachineFunction &MF) const {
3331   Register Reg = StringSwitch<Register>(RegName)
3332     .Case("m0", AMDGPU::M0)
3333     .Case("exec", AMDGPU::EXEC)
3334     .Case("exec_lo", AMDGPU::EXEC_LO)
3335     .Case("exec_hi", AMDGPU::EXEC_HI)
3336     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3337     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3338     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3339     .Default(Register());
3340 
3341   if (Reg == AMDGPU::NoRegister) {
3342     report_fatal_error(Twine("invalid register name \""
3343                              + StringRef(RegName)  + "\"."));
3344 
3345   }
3346 
3347   if (!Subtarget->hasFlatScrRegister() &&
3348        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3349     report_fatal_error(Twine("invalid register \""
3350                              + StringRef(RegName)  + "\" for subtarget."));
3351   }
3352 
3353   switch (Reg) {
3354   case AMDGPU::M0:
3355   case AMDGPU::EXEC_LO:
3356   case AMDGPU::EXEC_HI:
3357   case AMDGPU::FLAT_SCR_LO:
3358   case AMDGPU::FLAT_SCR_HI:
3359     if (VT.getSizeInBits() == 32)
3360       return Reg;
3361     break;
3362   case AMDGPU::EXEC:
3363   case AMDGPU::FLAT_SCR:
3364     if (VT.getSizeInBits() == 64)
3365       return Reg;
3366     break;
3367   default:
3368     llvm_unreachable("missing register type checking");
3369   }
3370 
3371   report_fatal_error(Twine("invalid type for register \""
3372                            + StringRef(RegName) + "\"."));
3373 }
3374 
3375 // If kill is not the last instruction, split the block so kill is always a
3376 // proper terminator.
3377 MachineBasicBlock *
3378 SITargetLowering::splitKillBlock(MachineInstr &MI,
3379                                  MachineBasicBlock *BB) const {
3380   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3381   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3382   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3383   return SplitBB;
3384 }
3385 
3386 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3387 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3388 // be the first instruction in the remainder block.
3389 //
3390 /// \returns { LoopBody, Remainder }
3391 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3392 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3393   MachineFunction *MF = MBB.getParent();
3394   MachineBasicBlock::iterator I(&MI);
3395 
3396   // To insert the loop we need to split the block. Move everything after this
3397   // point to a new block, and insert a new empty block between the two.
3398   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3399   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3400   MachineFunction::iterator MBBI(MBB);
3401   ++MBBI;
3402 
3403   MF->insert(MBBI, LoopBB);
3404   MF->insert(MBBI, RemainderBB);
3405 
3406   LoopBB->addSuccessor(LoopBB);
3407   LoopBB->addSuccessor(RemainderBB);
3408 
3409   // Move the rest of the block into a new block.
3410   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3411 
3412   if (InstInLoop) {
3413     auto Next = std::next(I);
3414 
3415     // Move instruction to loop body.
3416     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3417 
3418     // Move the rest of the block.
3419     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3420   } else {
3421     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3422   }
3423 
3424   MBB.addSuccessor(LoopBB);
3425 
3426   return std::make_pair(LoopBB, RemainderBB);
3427 }
3428 
3429 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3430 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3431   MachineBasicBlock *MBB = MI.getParent();
3432   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3433   auto I = MI.getIterator();
3434   auto E = std::next(I);
3435 
3436   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3437     .addImm(0);
3438 
3439   MIBundleBuilder Bundler(*MBB, I, E);
3440   finalizeBundle(*MBB, Bundler.begin());
3441 }
3442 
3443 MachineBasicBlock *
3444 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3445                                          MachineBasicBlock *BB) const {
3446   const DebugLoc &DL = MI.getDebugLoc();
3447 
3448   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3449 
3450   MachineBasicBlock *LoopBB;
3451   MachineBasicBlock *RemainderBB;
3452   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3453 
3454   // Apparently kill flags are only valid if the def is in the same block?
3455   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3456     Src->setIsKill(false);
3457 
3458   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3459 
3460   MachineBasicBlock::iterator I = LoopBB->end();
3461 
3462   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3463     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3464 
3465   // Clear TRAP_STS.MEM_VIOL
3466   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3467     .addImm(0)
3468     .addImm(EncodedReg);
3469 
3470   bundleInstWithWaitcnt(MI);
3471 
3472   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3473 
3474   // Load and check TRAP_STS.MEM_VIOL
3475   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3476     .addImm(EncodedReg);
3477 
3478   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3479   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3480     .addReg(Reg, RegState::Kill)
3481     .addImm(0);
3482   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3483     .addMBB(LoopBB);
3484 
3485   return RemainderBB;
3486 }
3487 
3488 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3489 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3490 // will only do one iteration. In the worst case, this will loop 64 times.
3491 //
3492 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3493 static MachineBasicBlock::iterator
3494 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3495                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3496                        const DebugLoc &DL, const MachineOperand &Idx,
3497                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3498                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3499                        Register &SGPRIdxReg) {
3500 
3501   MachineFunction *MF = OrigBB.getParent();
3502   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3503   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3504   MachineBasicBlock::iterator I = LoopBB.begin();
3505 
3506   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3507   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3508   Register NewExec = MRI.createVirtualRegister(BoolRC);
3509   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3510   Register CondReg = MRI.createVirtualRegister(BoolRC);
3511 
3512   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3513     .addReg(InitReg)
3514     .addMBB(&OrigBB)
3515     .addReg(ResultReg)
3516     .addMBB(&LoopBB);
3517 
3518   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3519     .addReg(InitSaveExecReg)
3520     .addMBB(&OrigBB)
3521     .addReg(NewExec)
3522     .addMBB(&LoopBB);
3523 
3524   // Read the next variant <- also loop target.
3525   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3526       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3527 
3528   // Compare the just read M0 value to all possible Idx values.
3529   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3530       .addReg(CurrentIdxReg)
3531       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3532 
3533   // Update EXEC, save the original EXEC value to VCC.
3534   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3535                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3536           NewExec)
3537     .addReg(CondReg, RegState::Kill);
3538 
3539   MRI.setSimpleHint(NewExec, CondReg);
3540 
3541   if (UseGPRIdxMode) {
3542     if (Offset == 0) {
3543       SGPRIdxReg = CurrentIdxReg;
3544     } else {
3545       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3546       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3547           .addReg(CurrentIdxReg, RegState::Kill)
3548           .addImm(Offset);
3549     }
3550   } else {
3551     // Move index from VCC into M0
3552     if (Offset == 0) {
3553       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3554         .addReg(CurrentIdxReg, RegState::Kill);
3555     } else {
3556       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3557         .addReg(CurrentIdxReg, RegState::Kill)
3558         .addImm(Offset);
3559     }
3560   }
3561 
3562   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3563   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3564   MachineInstr *InsertPt =
3565     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3566                                                   : AMDGPU::S_XOR_B64_term), Exec)
3567       .addReg(Exec)
3568       .addReg(NewExec);
3569 
3570   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3571   // s_cbranch_scc0?
3572 
3573   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3574   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3575     .addMBB(&LoopBB);
3576 
3577   return InsertPt->getIterator();
3578 }
3579 
3580 // This has slightly sub-optimal regalloc when the source vector is killed by
3581 // the read. The register allocator does not understand that the kill is
3582 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3583 // subregister from it, using 1 more VGPR than necessary. This was saved when
3584 // this was expanded after register allocation.
3585 static MachineBasicBlock::iterator
3586 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3587                unsigned InitResultReg, unsigned PhiReg, int Offset,
3588                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3589   MachineFunction *MF = MBB.getParent();
3590   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3591   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3592   MachineRegisterInfo &MRI = MF->getRegInfo();
3593   const DebugLoc &DL = MI.getDebugLoc();
3594   MachineBasicBlock::iterator I(&MI);
3595 
3596   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3597   Register DstReg = MI.getOperand(0).getReg();
3598   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3599   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3600   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3601   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3602 
3603   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3604 
3605   // Save the EXEC mask
3606   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3607     .addReg(Exec);
3608 
3609   MachineBasicBlock *LoopBB;
3610   MachineBasicBlock *RemainderBB;
3611   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3612 
3613   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3614 
3615   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3616                                       InitResultReg, DstReg, PhiReg, TmpExec,
3617                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3618 
3619   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3620   MachineFunction::iterator MBBI(LoopBB);
3621   ++MBBI;
3622   MF->insert(MBBI, LandingPad);
3623   LoopBB->removeSuccessor(RemainderBB);
3624   LandingPad->addSuccessor(RemainderBB);
3625   LoopBB->addSuccessor(LandingPad);
3626   MachineBasicBlock::iterator First = LandingPad->begin();
3627   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3628     .addReg(SaveExec);
3629 
3630   return InsPt;
3631 }
3632 
3633 // Returns subreg index, offset
3634 static std::pair<unsigned, int>
3635 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3636                             const TargetRegisterClass *SuperRC,
3637                             unsigned VecReg,
3638                             int Offset) {
3639   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3640 
3641   // Skip out of bounds offsets, or else we would end up using an undefined
3642   // register.
3643   if (Offset >= NumElts || Offset < 0)
3644     return std::make_pair(AMDGPU::sub0, Offset);
3645 
3646   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3647 }
3648 
3649 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3650                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3651                                  int Offset) {
3652   MachineBasicBlock *MBB = MI.getParent();
3653   const DebugLoc &DL = MI.getDebugLoc();
3654   MachineBasicBlock::iterator I(&MI);
3655 
3656   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3657 
3658   assert(Idx->getReg() != AMDGPU::NoRegister);
3659 
3660   if (Offset == 0) {
3661     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3662   } else {
3663     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3664         .add(*Idx)
3665         .addImm(Offset);
3666   }
3667 }
3668 
3669 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3670                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3671                                    int Offset) {
3672   MachineBasicBlock *MBB = MI.getParent();
3673   const DebugLoc &DL = MI.getDebugLoc();
3674   MachineBasicBlock::iterator I(&MI);
3675 
3676   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3677 
3678   if (Offset == 0)
3679     return Idx->getReg();
3680 
3681   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3682   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3683       .add(*Idx)
3684       .addImm(Offset);
3685   return Tmp;
3686 }
3687 
3688 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3689                                           MachineBasicBlock &MBB,
3690                                           const GCNSubtarget &ST) {
3691   const SIInstrInfo *TII = ST.getInstrInfo();
3692   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3693   MachineFunction *MF = MBB.getParent();
3694   MachineRegisterInfo &MRI = MF->getRegInfo();
3695 
3696   Register Dst = MI.getOperand(0).getReg();
3697   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3698   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3699   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3700 
3701   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3702   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3703 
3704   unsigned SubReg;
3705   std::tie(SubReg, Offset)
3706     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3707 
3708   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3709 
3710   // Check for a SGPR index.
3711   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3712     MachineBasicBlock::iterator I(&MI);
3713     const DebugLoc &DL = MI.getDebugLoc();
3714 
3715     if (UseGPRIdxMode) {
3716       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3717       // to avoid interfering with other uses, so probably requires a new
3718       // optimization pass.
3719       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3720 
3721       const MCInstrDesc &GPRIDXDesc =
3722           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3723       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3724           .addReg(SrcReg)
3725           .addReg(Idx)
3726           .addImm(SubReg);
3727     } else {
3728       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3729 
3730       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3731         .addReg(SrcReg, 0, SubReg)
3732         .addReg(SrcReg, RegState::Implicit);
3733     }
3734 
3735     MI.eraseFromParent();
3736 
3737     return &MBB;
3738   }
3739 
3740   // Control flow needs to be inserted if indexing with a VGPR.
3741   const DebugLoc &DL = MI.getDebugLoc();
3742   MachineBasicBlock::iterator I(&MI);
3743 
3744   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3745   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3746 
3747   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3748 
3749   Register SGPRIdxReg;
3750   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3751                               UseGPRIdxMode, SGPRIdxReg);
3752 
3753   MachineBasicBlock *LoopBB = InsPt->getParent();
3754 
3755   if (UseGPRIdxMode) {
3756     const MCInstrDesc &GPRIDXDesc =
3757         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3758 
3759     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3760         .addReg(SrcReg)
3761         .addReg(SGPRIdxReg)
3762         .addImm(SubReg);
3763   } else {
3764     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3765       .addReg(SrcReg, 0, SubReg)
3766       .addReg(SrcReg, RegState::Implicit);
3767   }
3768 
3769   MI.eraseFromParent();
3770 
3771   return LoopBB;
3772 }
3773 
3774 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3775                                           MachineBasicBlock &MBB,
3776                                           const GCNSubtarget &ST) {
3777   const SIInstrInfo *TII = ST.getInstrInfo();
3778   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3779   MachineFunction *MF = MBB.getParent();
3780   MachineRegisterInfo &MRI = MF->getRegInfo();
3781 
3782   Register Dst = MI.getOperand(0).getReg();
3783   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3784   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3785   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3786   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3787   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3788   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3789 
3790   // This can be an immediate, but will be folded later.
3791   assert(Val->getReg());
3792 
3793   unsigned SubReg;
3794   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3795                                                          SrcVec->getReg(),
3796                                                          Offset);
3797   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3798 
3799   if (Idx->getReg() == AMDGPU::NoRegister) {
3800     MachineBasicBlock::iterator I(&MI);
3801     const DebugLoc &DL = MI.getDebugLoc();
3802 
3803     assert(Offset == 0);
3804 
3805     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3806         .add(*SrcVec)
3807         .add(*Val)
3808         .addImm(SubReg);
3809 
3810     MI.eraseFromParent();
3811     return &MBB;
3812   }
3813 
3814   // Check for a SGPR index.
3815   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3816     MachineBasicBlock::iterator I(&MI);
3817     const DebugLoc &DL = MI.getDebugLoc();
3818 
3819     if (UseGPRIdxMode) {
3820       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3821 
3822       const MCInstrDesc &GPRIDXDesc =
3823           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3824       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3825           .addReg(SrcVec->getReg())
3826           .add(*Val)
3827           .addReg(Idx)
3828           .addImm(SubReg);
3829     } else {
3830       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3831 
3832       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3833           TRI.getRegSizeInBits(*VecRC), 32, false);
3834       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3835           .addReg(SrcVec->getReg())
3836           .add(*Val)
3837           .addImm(SubReg);
3838     }
3839     MI.eraseFromParent();
3840     return &MBB;
3841   }
3842 
3843   // Control flow needs to be inserted if indexing with a VGPR.
3844   if (Val->isReg())
3845     MRI.clearKillFlags(Val->getReg());
3846 
3847   const DebugLoc &DL = MI.getDebugLoc();
3848 
3849   Register PhiReg = MRI.createVirtualRegister(VecRC);
3850 
3851   Register SGPRIdxReg;
3852   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3853                               UseGPRIdxMode, SGPRIdxReg);
3854   MachineBasicBlock *LoopBB = InsPt->getParent();
3855 
3856   if (UseGPRIdxMode) {
3857     const MCInstrDesc &GPRIDXDesc =
3858         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3859 
3860     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3861         .addReg(PhiReg)
3862         .add(*Val)
3863         .addReg(SGPRIdxReg)
3864         .addImm(AMDGPU::sub0);
3865   } else {
3866     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3867         TRI.getRegSizeInBits(*VecRC), 32, false);
3868     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3869         .addReg(PhiReg)
3870         .add(*Val)
3871         .addImm(AMDGPU::sub0);
3872   }
3873 
3874   MI.eraseFromParent();
3875   return LoopBB;
3876 }
3877 
3878 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3879   MachineInstr &MI, MachineBasicBlock *BB) const {
3880 
3881   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3882   MachineFunction *MF = BB->getParent();
3883   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3884 
3885   switch (MI.getOpcode()) {
3886   case AMDGPU::S_UADDO_PSEUDO:
3887   case AMDGPU::S_USUBO_PSEUDO: {
3888     const DebugLoc &DL = MI.getDebugLoc();
3889     MachineOperand &Dest0 = MI.getOperand(0);
3890     MachineOperand &Dest1 = MI.getOperand(1);
3891     MachineOperand &Src0 = MI.getOperand(2);
3892     MachineOperand &Src1 = MI.getOperand(3);
3893 
3894     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3895                        ? AMDGPU::S_ADD_I32
3896                        : AMDGPU::S_SUB_I32;
3897     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3898 
3899     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3900         .addImm(1)
3901         .addImm(0);
3902 
3903     MI.eraseFromParent();
3904     return BB;
3905   }
3906   case AMDGPU::S_ADD_U64_PSEUDO:
3907   case AMDGPU::S_SUB_U64_PSEUDO: {
3908     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3909     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3910     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3911     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3912     const DebugLoc &DL = MI.getDebugLoc();
3913 
3914     MachineOperand &Dest = MI.getOperand(0);
3915     MachineOperand &Src0 = MI.getOperand(1);
3916     MachineOperand &Src1 = MI.getOperand(2);
3917 
3918     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3919     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3920 
3921     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3922         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3923     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3924         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3925 
3926     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3927         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3928     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3929         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3930 
3931     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3932 
3933     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3934     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3935     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3936     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3937     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3938         .addReg(DestSub0)
3939         .addImm(AMDGPU::sub0)
3940         .addReg(DestSub1)
3941         .addImm(AMDGPU::sub1);
3942     MI.eraseFromParent();
3943     return BB;
3944   }
3945   case AMDGPU::V_ADD_U64_PSEUDO:
3946   case AMDGPU::V_SUB_U64_PSEUDO: {
3947     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3948     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3949     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3950     const DebugLoc &DL = MI.getDebugLoc();
3951 
3952     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3953 
3954     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3955 
3956     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3957     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3958 
3959     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3960     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3961 
3962     MachineOperand &Dest = MI.getOperand(0);
3963     MachineOperand &Src0 = MI.getOperand(1);
3964     MachineOperand &Src1 = MI.getOperand(2);
3965 
3966     const TargetRegisterClass *Src0RC = Src0.isReg()
3967                                             ? MRI.getRegClass(Src0.getReg())
3968                                             : &AMDGPU::VReg_64RegClass;
3969     const TargetRegisterClass *Src1RC = Src1.isReg()
3970                                             ? MRI.getRegClass(Src1.getReg())
3971                                             : &AMDGPU::VReg_64RegClass;
3972 
3973     const TargetRegisterClass *Src0SubRC =
3974         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3975     const TargetRegisterClass *Src1SubRC =
3976         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3977 
3978     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3979         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3980     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3981         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3982 
3983     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3984         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3985     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3986         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3987 
3988     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3989     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3990                                .addReg(CarryReg, RegState::Define)
3991                                .add(SrcReg0Sub0)
3992                                .add(SrcReg1Sub0)
3993                                .addImm(0); // clamp bit
3994 
3995     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3996     MachineInstr *HiHalf =
3997         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3998             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3999             .add(SrcReg0Sub1)
4000             .add(SrcReg1Sub1)
4001             .addReg(CarryReg, RegState::Kill)
4002             .addImm(0); // clamp bit
4003 
4004     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4005         .addReg(DestSub0)
4006         .addImm(AMDGPU::sub0)
4007         .addReg(DestSub1)
4008         .addImm(AMDGPU::sub1);
4009     TII->legalizeOperands(*LoHalf);
4010     TII->legalizeOperands(*HiHalf);
4011     MI.eraseFromParent();
4012     return BB;
4013   }
4014   case AMDGPU::S_ADD_CO_PSEUDO:
4015   case AMDGPU::S_SUB_CO_PSEUDO: {
4016     // This pseudo has a chance to be selected
4017     // only from uniform add/subcarry node. All the VGPR operands
4018     // therefore assumed to be splat vectors.
4019     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4020     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4021     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4022     MachineBasicBlock::iterator MII = MI;
4023     const DebugLoc &DL = MI.getDebugLoc();
4024     MachineOperand &Dest = MI.getOperand(0);
4025     MachineOperand &CarryDest = MI.getOperand(1);
4026     MachineOperand &Src0 = MI.getOperand(2);
4027     MachineOperand &Src1 = MI.getOperand(3);
4028     MachineOperand &Src2 = MI.getOperand(4);
4029     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4030                        ? AMDGPU::S_ADDC_U32
4031                        : AMDGPU::S_SUBB_U32;
4032     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4033       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4034       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4035           .addReg(Src0.getReg());
4036       Src0.setReg(RegOp0);
4037     }
4038     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4039       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4040       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4041           .addReg(Src1.getReg());
4042       Src1.setReg(RegOp1);
4043     }
4044     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4045     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4046       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4047           .addReg(Src2.getReg());
4048       Src2.setReg(RegOp2);
4049     }
4050 
4051     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4052     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4053       if (ST.hasScalarCompareEq64()) {
4054         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4055             .addReg(Src2.getReg())
4056             .addImm(0);
4057       } else {
4058         const TargetRegisterClass *SubRC =
4059             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4060         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4061             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4062         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4063             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4064         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4065 
4066         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4067             .add(Src2Sub0)
4068             .add(Src2Sub1);
4069 
4070         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4071             .addReg(Src2_32, RegState::Kill)
4072             .addImm(0);
4073       }
4074     } else {
4075       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4076           .addReg(Src2.getReg())
4077           .addImm(0);
4078     }
4079 
4080     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4081 
4082     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4083       .addReg(AMDGPU::SCC);
4084     MI.eraseFromParent();
4085     return BB;
4086   }
4087   case AMDGPU::SI_INIT_M0: {
4088     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4089             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4090         .add(MI.getOperand(0));
4091     MI.eraseFromParent();
4092     return BB;
4093   }
4094   case AMDGPU::GET_GROUPSTATICSIZE: {
4095     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4096            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4097     DebugLoc DL = MI.getDebugLoc();
4098     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4099         .add(MI.getOperand(0))
4100         .addImm(MFI->getLDSSize());
4101     MI.eraseFromParent();
4102     return BB;
4103   }
4104   case AMDGPU::SI_INDIRECT_SRC_V1:
4105   case AMDGPU::SI_INDIRECT_SRC_V2:
4106   case AMDGPU::SI_INDIRECT_SRC_V4:
4107   case AMDGPU::SI_INDIRECT_SRC_V8:
4108   case AMDGPU::SI_INDIRECT_SRC_V16:
4109   case AMDGPU::SI_INDIRECT_SRC_V32:
4110     return emitIndirectSrc(MI, *BB, *getSubtarget());
4111   case AMDGPU::SI_INDIRECT_DST_V1:
4112   case AMDGPU::SI_INDIRECT_DST_V2:
4113   case AMDGPU::SI_INDIRECT_DST_V4:
4114   case AMDGPU::SI_INDIRECT_DST_V8:
4115   case AMDGPU::SI_INDIRECT_DST_V16:
4116   case AMDGPU::SI_INDIRECT_DST_V32:
4117     return emitIndirectDst(MI, *BB, *getSubtarget());
4118   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4119   case AMDGPU::SI_KILL_I1_PSEUDO:
4120     return splitKillBlock(MI, BB);
4121   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4122     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4123     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4124     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4125 
4126     Register Dst = MI.getOperand(0).getReg();
4127     Register Src0 = MI.getOperand(1).getReg();
4128     Register Src1 = MI.getOperand(2).getReg();
4129     const DebugLoc &DL = MI.getDebugLoc();
4130     Register SrcCond = MI.getOperand(3).getReg();
4131 
4132     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4133     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4134     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4135     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4136 
4137     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4138       .addReg(SrcCond);
4139     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4140       .addImm(0)
4141       .addReg(Src0, 0, AMDGPU::sub0)
4142       .addImm(0)
4143       .addReg(Src1, 0, AMDGPU::sub0)
4144       .addReg(SrcCondCopy);
4145     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4146       .addImm(0)
4147       .addReg(Src0, 0, AMDGPU::sub1)
4148       .addImm(0)
4149       .addReg(Src1, 0, AMDGPU::sub1)
4150       .addReg(SrcCondCopy);
4151 
4152     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4153       .addReg(DstLo)
4154       .addImm(AMDGPU::sub0)
4155       .addReg(DstHi)
4156       .addImm(AMDGPU::sub1);
4157     MI.eraseFromParent();
4158     return BB;
4159   }
4160   case AMDGPU::SI_BR_UNDEF: {
4161     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4162     const DebugLoc &DL = MI.getDebugLoc();
4163     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4164                            .add(MI.getOperand(0));
4165     Br->getOperand(1).setIsUndef(true); // read undef SCC
4166     MI.eraseFromParent();
4167     return BB;
4168   }
4169   case AMDGPU::ADJCALLSTACKUP:
4170   case AMDGPU::ADJCALLSTACKDOWN: {
4171     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4172     MachineInstrBuilder MIB(*MF, &MI);
4173     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4174        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4175     return BB;
4176   }
4177   case AMDGPU::SI_CALL_ISEL: {
4178     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4179     const DebugLoc &DL = MI.getDebugLoc();
4180 
4181     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4182 
4183     MachineInstrBuilder MIB;
4184     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4185 
4186     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4187       MIB.add(MI.getOperand(I));
4188 
4189     MIB.cloneMemRefs(MI);
4190     MI.eraseFromParent();
4191     return BB;
4192   }
4193   case AMDGPU::V_ADD_CO_U32_e32:
4194   case AMDGPU::V_SUB_CO_U32_e32:
4195   case AMDGPU::V_SUBREV_CO_U32_e32: {
4196     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4197     const DebugLoc &DL = MI.getDebugLoc();
4198     unsigned Opc = MI.getOpcode();
4199 
4200     bool NeedClampOperand = false;
4201     if (TII->pseudoToMCOpcode(Opc) == -1) {
4202       Opc = AMDGPU::getVOPe64(Opc);
4203       NeedClampOperand = true;
4204     }
4205 
4206     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4207     if (TII->isVOP3(*I)) {
4208       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4209       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4210       I.addReg(TRI->getVCC(), RegState::Define);
4211     }
4212     I.add(MI.getOperand(1))
4213      .add(MI.getOperand(2));
4214     if (NeedClampOperand)
4215       I.addImm(0); // clamp bit for e64 encoding
4216 
4217     TII->legalizeOperands(*I);
4218 
4219     MI.eraseFromParent();
4220     return BB;
4221   }
4222   case AMDGPU::DS_GWS_INIT:
4223   case AMDGPU::DS_GWS_SEMA_BR:
4224   case AMDGPU::DS_GWS_BARRIER:
4225     if (Subtarget->needsAlignedVGPRs()) {
4226       // Add implicit aligned super-reg to force alignment on the data operand.
4227       const DebugLoc &DL = MI.getDebugLoc();
4228       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4229       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4230       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4231       Register DataReg = Op->getReg();
4232       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4233       Register Undef = MRI.createVirtualRegister(
4234           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4235       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4236       Register NewVR =
4237           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4238                                            : &AMDGPU::VReg_64_Align2RegClass);
4239       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4240           .addReg(DataReg, 0, Op->getSubReg())
4241           .addImm(AMDGPU::sub0)
4242           .addReg(Undef)
4243           .addImm(AMDGPU::sub1);
4244       Op->setReg(NewVR);
4245       Op->setSubReg(AMDGPU::sub0);
4246       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4247     }
4248     LLVM_FALLTHROUGH;
4249   case AMDGPU::DS_GWS_SEMA_V:
4250   case AMDGPU::DS_GWS_SEMA_P:
4251   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4252     // A s_waitcnt 0 is required to be the instruction immediately following.
4253     if (getSubtarget()->hasGWSAutoReplay()) {
4254       bundleInstWithWaitcnt(MI);
4255       return BB;
4256     }
4257 
4258     return emitGWSMemViolTestLoop(MI, BB);
4259   case AMDGPU::S_SETREG_B32: {
4260     // Try to optimize cases that only set the denormal mode or rounding mode.
4261     //
4262     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4263     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4264     // instead.
4265     //
4266     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4267     // allow you to have a no side effect instruction in the output of a
4268     // sideeffecting pattern.
4269     unsigned ID, Offset, Width;
4270     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4271     if (ID != AMDGPU::Hwreg::ID_MODE)
4272       return BB;
4273 
4274     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4275     const unsigned SetMask = WidthMask << Offset;
4276 
4277     if (getSubtarget()->hasDenormModeInst()) {
4278       unsigned SetDenormOp = 0;
4279       unsigned SetRoundOp = 0;
4280 
4281       // The dedicated instructions can only set the whole denorm or round mode
4282       // at once, not a subset of bits in either.
4283       if (SetMask ==
4284           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4285         // If this fully sets both the round and denorm mode, emit the two
4286         // dedicated instructions for these.
4287         SetRoundOp = AMDGPU::S_ROUND_MODE;
4288         SetDenormOp = AMDGPU::S_DENORM_MODE;
4289       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4290         SetRoundOp = AMDGPU::S_ROUND_MODE;
4291       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4292         SetDenormOp = AMDGPU::S_DENORM_MODE;
4293       }
4294 
4295       if (SetRoundOp || SetDenormOp) {
4296         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4297         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4298         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4299           unsigned ImmVal = Def->getOperand(1).getImm();
4300           if (SetRoundOp) {
4301             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4302                 .addImm(ImmVal & 0xf);
4303 
4304             // If we also have the denorm mode, get just the denorm mode bits.
4305             ImmVal >>= 4;
4306           }
4307 
4308           if (SetDenormOp) {
4309             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4310                 .addImm(ImmVal & 0xf);
4311           }
4312 
4313           MI.eraseFromParent();
4314           return BB;
4315         }
4316       }
4317     }
4318 
4319     // If only FP bits are touched, used the no side effects pseudo.
4320     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4321                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4322       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4323 
4324     return BB;
4325   }
4326   default:
4327     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4328   }
4329 }
4330 
4331 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4332   return isTypeLegal(VT.getScalarType());
4333 }
4334 
4335 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4336   // This currently forces unfolding various combinations of fsub into fma with
4337   // free fneg'd operands. As long as we have fast FMA (controlled by
4338   // isFMAFasterThanFMulAndFAdd), we should perform these.
4339 
4340   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4341   // most of these combines appear to be cycle neutral but save on instruction
4342   // count / code size.
4343   return true;
4344 }
4345 
4346 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4347                                          EVT VT) const {
4348   if (!VT.isVector()) {
4349     return MVT::i1;
4350   }
4351   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4352 }
4353 
4354 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4355   // TODO: Should i16 be used always if legal? For now it would force VALU
4356   // shifts.
4357   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4358 }
4359 
4360 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4361   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4362              ? Ty.changeElementSize(16)
4363              : Ty.changeElementSize(32);
4364 }
4365 
4366 // Answering this is somewhat tricky and depends on the specific device which
4367 // have different rates for fma or all f64 operations.
4368 //
4369 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4370 // regardless of which device (although the number of cycles differs between
4371 // devices), so it is always profitable for f64.
4372 //
4373 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4374 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4375 // which we can always do even without fused FP ops since it returns the same
4376 // result as the separate operations and since it is always full
4377 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4378 // however does not support denormals, so we do report fma as faster if we have
4379 // a fast fma device and require denormals.
4380 //
4381 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4382                                                   EVT VT) const {
4383   VT = VT.getScalarType();
4384 
4385   switch (VT.getSimpleVT().SimpleTy) {
4386   case MVT::f32: {
4387     // If mad is not available this depends only on if f32 fma is full rate.
4388     if (!Subtarget->hasMadMacF32Insts())
4389       return Subtarget->hasFastFMAF32();
4390 
4391     // Otherwise f32 mad is always full rate and returns the same result as
4392     // the separate operations so should be preferred over fma.
4393     // However does not support denomals.
4394     if (hasFP32Denormals(MF))
4395       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4396 
4397     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4398     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4399   }
4400   case MVT::f64:
4401     return true;
4402   case MVT::f16:
4403     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4404   default:
4405     break;
4406   }
4407 
4408   return false;
4409 }
4410 
4411 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4412                                    const SDNode *N) const {
4413   // TODO: Check future ftz flag
4414   // v_mad_f32/v_mac_f32 do not support denormals.
4415   EVT VT = N->getValueType(0);
4416   if (VT == MVT::f32)
4417     return Subtarget->hasMadMacF32Insts() &&
4418            !hasFP32Denormals(DAG.getMachineFunction());
4419   if (VT == MVT::f16) {
4420     return Subtarget->hasMadF16() &&
4421            !hasFP64FP16Denormals(DAG.getMachineFunction());
4422   }
4423 
4424   return false;
4425 }
4426 
4427 //===----------------------------------------------------------------------===//
4428 // Custom DAG Lowering Operations
4429 //===----------------------------------------------------------------------===//
4430 
4431 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4432 // wider vector type is legal.
4433 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4434                                              SelectionDAG &DAG) const {
4435   unsigned Opc = Op.getOpcode();
4436   EVT VT = Op.getValueType();
4437   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4438 
4439   SDValue Lo, Hi;
4440   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4441 
4442   SDLoc SL(Op);
4443   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4444                              Op->getFlags());
4445   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4446                              Op->getFlags());
4447 
4448   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4449 }
4450 
4451 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4452 // wider vector type is legal.
4453 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4454                                               SelectionDAG &DAG) const {
4455   unsigned Opc = Op.getOpcode();
4456   EVT VT = Op.getValueType();
4457   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4458          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4459 
4460   SDValue Lo0, Hi0;
4461   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4462   SDValue Lo1, Hi1;
4463   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4464 
4465   SDLoc SL(Op);
4466 
4467   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4468                              Op->getFlags());
4469   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4470                              Op->getFlags());
4471 
4472   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4473 }
4474 
4475 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4476                                               SelectionDAG &DAG) const {
4477   unsigned Opc = Op.getOpcode();
4478   EVT VT = Op.getValueType();
4479   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4480          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4481 
4482   SDValue Lo0, Hi0;
4483   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4484   SDValue Lo1, Hi1;
4485   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4486   SDValue Lo2, Hi2;
4487   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4488 
4489   SDLoc SL(Op);
4490 
4491   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4492                              Op->getFlags());
4493   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4494                              Op->getFlags());
4495 
4496   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4497 }
4498 
4499 
4500 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4501   switch (Op.getOpcode()) {
4502   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4503   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4504   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4505   case ISD::LOAD: {
4506     SDValue Result = LowerLOAD(Op, DAG);
4507     assert((!Result.getNode() ||
4508             Result.getNode()->getNumValues() == 2) &&
4509            "Load should return a value and a chain");
4510     return Result;
4511   }
4512 
4513   case ISD::FSIN:
4514   case ISD::FCOS:
4515     return LowerTrig(Op, DAG);
4516   case ISD::SELECT: return LowerSELECT(Op, DAG);
4517   case ISD::FDIV: return LowerFDIV(Op, DAG);
4518   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4519   case ISD::STORE: return LowerSTORE(Op, DAG);
4520   case ISD::GlobalAddress: {
4521     MachineFunction &MF = DAG.getMachineFunction();
4522     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4523     return LowerGlobalAddress(MFI, Op, DAG);
4524   }
4525   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4526   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4527   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4528   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4529   case ISD::INSERT_SUBVECTOR:
4530     return lowerINSERT_SUBVECTOR(Op, DAG);
4531   case ISD::INSERT_VECTOR_ELT:
4532     return lowerINSERT_VECTOR_ELT(Op, DAG);
4533   case ISD::EXTRACT_VECTOR_ELT:
4534     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4535   case ISD::VECTOR_SHUFFLE:
4536     return lowerVECTOR_SHUFFLE(Op, DAG);
4537   case ISD::BUILD_VECTOR:
4538     return lowerBUILD_VECTOR(Op, DAG);
4539   case ISD::FP_ROUND:
4540     return lowerFP_ROUND(Op, DAG);
4541   case ISD::TRAP:
4542     return lowerTRAP(Op, DAG);
4543   case ISD::DEBUGTRAP:
4544     return lowerDEBUGTRAP(Op, DAG);
4545   case ISD::FABS:
4546   case ISD::FNEG:
4547   case ISD::FCANONICALIZE:
4548   case ISD::BSWAP:
4549     return splitUnaryVectorOp(Op, DAG);
4550   case ISD::FMINNUM:
4551   case ISD::FMAXNUM:
4552     return lowerFMINNUM_FMAXNUM(Op, DAG);
4553   case ISD::FMA:
4554     return splitTernaryVectorOp(Op, DAG);
4555   case ISD::FP_TO_SINT:
4556   case ISD::FP_TO_UINT:
4557     return LowerFP_TO_INT(Op, DAG);
4558   case ISD::SHL:
4559   case ISD::SRA:
4560   case ISD::SRL:
4561   case ISD::ADD:
4562   case ISD::SUB:
4563   case ISD::MUL:
4564   case ISD::SMIN:
4565   case ISD::SMAX:
4566   case ISD::UMIN:
4567   case ISD::UMAX:
4568   case ISD::FADD:
4569   case ISD::FMUL:
4570   case ISD::FMINNUM_IEEE:
4571   case ISD::FMAXNUM_IEEE:
4572   case ISD::UADDSAT:
4573   case ISD::USUBSAT:
4574   case ISD::SADDSAT:
4575   case ISD::SSUBSAT:
4576     return splitBinaryVectorOp(Op, DAG);
4577   case ISD::SMULO:
4578   case ISD::UMULO:
4579     return lowerXMULO(Op, DAG);
4580   case ISD::DYNAMIC_STACKALLOC:
4581     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4582   }
4583   return SDValue();
4584 }
4585 
4586 // Used for D16: Casts the result of an instruction into the right vector,
4587 // packs values if loads return unpacked values.
4588 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4589                                        const SDLoc &DL,
4590                                        SelectionDAG &DAG, bool Unpacked) {
4591   if (!LoadVT.isVector())
4592     return Result;
4593 
4594   // Cast back to the original packed type or to a larger type that is a
4595   // multiple of 32 bit for D16. Widening the return type is a required for
4596   // legalization.
4597   EVT FittingLoadVT = LoadVT;
4598   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4599     FittingLoadVT =
4600         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4601                          LoadVT.getVectorNumElements() + 1);
4602   }
4603 
4604   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4605     // Truncate to v2i16/v4i16.
4606     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4607 
4608     // Workaround legalizer not scalarizing truncate after vector op
4609     // legalization but not creating intermediate vector trunc.
4610     SmallVector<SDValue, 4> Elts;
4611     DAG.ExtractVectorElements(Result, Elts);
4612     for (SDValue &Elt : Elts)
4613       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4614 
4615     // Pad illegal v1i16/v3fi6 to v4i16
4616     if ((LoadVT.getVectorNumElements() % 2) == 1)
4617       Elts.push_back(DAG.getUNDEF(MVT::i16));
4618 
4619     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4620 
4621     // Bitcast to original type (v2f16/v4f16).
4622     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4623   }
4624 
4625   // Cast back to the original packed type.
4626   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4627 }
4628 
4629 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4630                                               MemSDNode *M,
4631                                               SelectionDAG &DAG,
4632                                               ArrayRef<SDValue> Ops,
4633                                               bool IsIntrinsic) const {
4634   SDLoc DL(M);
4635 
4636   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4637   EVT LoadVT = M->getValueType(0);
4638 
4639   EVT EquivLoadVT = LoadVT;
4640   if (LoadVT.isVector()) {
4641     if (Unpacked) {
4642       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4643                                      LoadVT.getVectorNumElements());
4644     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4645       // Widen v3f16 to legal type
4646       EquivLoadVT =
4647           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4648                            LoadVT.getVectorNumElements() + 1);
4649     }
4650   }
4651 
4652   // Change from v4f16/v2f16 to EquivLoadVT.
4653   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4654 
4655   SDValue Load
4656     = DAG.getMemIntrinsicNode(
4657       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4658       VTList, Ops, M->getMemoryVT(),
4659       M->getMemOperand());
4660 
4661   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4662 
4663   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4664 }
4665 
4666 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4667                                              SelectionDAG &DAG,
4668                                              ArrayRef<SDValue> Ops) const {
4669   SDLoc DL(M);
4670   EVT LoadVT = M->getValueType(0);
4671   EVT EltType = LoadVT.getScalarType();
4672   EVT IntVT = LoadVT.changeTypeToInteger();
4673 
4674   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4675 
4676   unsigned Opc =
4677       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4678 
4679   if (IsD16) {
4680     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4681   }
4682 
4683   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4684   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4685     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4686 
4687   if (isTypeLegal(LoadVT)) {
4688     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4689                                M->getMemOperand(), DAG);
4690   }
4691 
4692   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4693   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4694   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4695                                         M->getMemOperand(), DAG);
4696   return DAG.getMergeValues(
4697       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4698       DL);
4699 }
4700 
4701 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4702                                   SDNode *N, SelectionDAG &DAG) {
4703   EVT VT = N->getValueType(0);
4704   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4705   unsigned CondCode = CD->getZExtValue();
4706   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4707     return DAG.getUNDEF(VT);
4708 
4709   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4710 
4711   SDValue LHS = N->getOperand(1);
4712   SDValue RHS = N->getOperand(2);
4713 
4714   SDLoc DL(N);
4715 
4716   EVT CmpVT = LHS.getValueType();
4717   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4718     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4719       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4720     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4721     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4722   }
4723 
4724   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4725 
4726   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4727   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4728 
4729   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4730                               DAG.getCondCode(CCOpcode));
4731   if (VT.bitsEq(CCVT))
4732     return SetCC;
4733   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4734 }
4735 
4736 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4737                                   SDNode *N, SelectionDAG &DAG) {
4738   EVT VT = N->getValueType(0);
4739   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4740 
4741   unsigned CondCode = CD->getZExtValue();
4742   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4743     return DAG.getUNDEF(VT);
4744 
4745   SDValue Src0 = N->getOperand(1);
4746   SDValue Src1 = N->getOperand(2);
4747   EVT CmpVT = Src0.getValueType();
4748   SDLoc SL(N);
4749 
4750   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4751     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4752     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4753   }
4754 
4755   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4756   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4757   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4758   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4759   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4760                               Src1, DAG.getCondCode(CCOpcode));
4761   if (VT.bitsEq(CCVT))
4762     return SetCC;
4763   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4764 }
4765 
4766 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4767                                     SelectionDAG &DAG) {
4768   EVT VT = N->getValueType(0);
4769   SDValue Src = N->getOperand(1);
4770   SDLoc SL(N);
4771 
4772   if (Src.getOpcode() == ISD::SETCC) {
4773     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4774     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4775                        Src.getOperand(1), Src.getOperand(2));
4776   }
4777   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4778     // (ballot 0) -> 0
4779     if (Arg->isNullValue())
4780       return DAG.getConstant(0, SL, VT);
4781 
4782     // (ballot 1) -> EXEC/EXEC_LO
4783     if (Arg->isOne()) {
4784       Register Exec;
4785       if (VT.getScalarSizeInBits() == 32)
4786         Exec = AMDGPU::EXEC_LO;
4787       else if (VT.getScalarSizeInBits() == 64)
4788         Exec = AMDGPU::EXEC;
4789       else
4790         return SDValue();
4791 
4792       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4793     }
4794   }
4795 
4796   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4797   // ISD::SETNE)
4798   return DAG.getNode(
4799       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4800       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4801 }
4802 
4803 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4804                                           SmallVectorImpl<SDValue> &Results,
4805                                           SelectionDAG &DAG) const {
4806   switch (N->getOpcode()) {
4807   case ISD::INSERT_VECTOR_ELT: {
4808     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4809       Results.push_back(Res);
4810     return;
4811   }
4812   case ISD::EXTRACT_VECTOR_ELT: {
4813     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4814       Results.push_back(Res);
4815     return;
4816   }
4817   case ISD::INTRINSIC_WO_CHAIN: {
4818     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4819     switch (IID) {
4820     case Intrinsic::amdgcn_cvt_pkrtz: {
4821       SDValue Src0 = N->getOperand(1);
4822       SDValue Src1 = N->getOperand(2);
4823       SDLoc SL(N);
4824       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4825                                 Src0, Src1);
4826       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4827       return;
4828     }
4829     case Intrinsic::amdgcn_cvt_pknorm_i16:
4830     case Intrinsic::amdgcn_cvt_pknorm_u16:
4831     case Intrinsic::amdgcn_cvt_pk_i16:
4832     case Intrinsic::amdgcn_cvt_pk_u16: {
4833       SDValue Src0 = N->getOperand(1);
4834       SDValue Src1 = N->getOperand(2);
4835       SDLoc SL(N);
4836       unsigned Opcode;
4837 
4838       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4839         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4840       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4841         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4842       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4843         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4844       else
4845         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4846 
4847       EVT VT = N->getValueType(0);
4848       if (isTypeLegal(VT))
4849         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4850       else {
4851         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4852         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4853       }
4854       return;
4855     }
4856     }
4857     break;
4858   }
4859   case ISD::INTRINSIC_W_CHAIN: {
4860     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4861       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4862         // FIXME: Hacky
4863         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4864           Results.push_back(Res.getOperand(I));
4865         }
4866       } else {
4867         Results.push_back(Res);
4868         Results.push_back(Res.getValue(1));
4869       }
4870       return;
4871     }
4872 
4873     break;
4874   }
4875   case ISD::SELECT: {
4876     SDLoc SL(N);
4877     EVT VT = N->getValueType(0);
4878     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4879     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4880     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4881 
4882     EVT SelectVT = NewVT;
4883     if (NewVT.bitsLT(MVT::i32)) {
4884       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4885       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4886       SelectVT = MVT::i32;
4887     }
4888 
4889     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4890                                     N->getOperand(0), LHS, RHS);
4891 
4892     if (NewVT != SelectVT)
4893       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4894     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4895     return;
4896   }
4897   case ISD::FNEG: {
4898     if (N->getValueType(0) != MVT::v2f16)
4899       break;
4900 
4901     SDLoc SL(N);
4902     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4903 
4904     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4905                              BC,
4906                              DAG.getConstant(0x80008000, SL, MVT::i32));
4907     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4908     return;
4909   }
4910   case ISD::FABS: {
4911     if (N->getValueType(0) != MVT::v2f16)
4912       break;
4913 
4914     SDLoc SL(N);
4915     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4916 
4917     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4918                              BC,
4919                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4920     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4921     return;
4922   }
4923   default:
4924     break;
4925   }
4926 }
4927 
4928 /// Helper function for LowerBRCOND
4929 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4930 
4931   SDNode *Parent = Value.getNode();
4932   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4933        I != E; ++I) {
4934 
4935     if (I.getUse().get() != Value)
4936       continue;
4937 
4938     if (I->getOpcode() == Opcode)
4939       return *I;
4940   }
4941   return nullptr;
4942 }
4943 
4944 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4945   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4946     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4947     case Intrinsic::amdgcn_if:
4948       return AMDGPUISD::IF;
4949     case Intrinsic::amdgcn_else:
4950       return AMDGPUISD::ELSE;
4951     case Intrinsic::amdgcn_loop:
4952       return AMDGPUISD::LOOP;
4953     case Intrinsic::amdgcn_end_cf:
4954       llvm_unreachable("should not occur");
4955     default:
4956       return 0;
4957     }
4958   }
4959 
4960   // break, if_break, else_break are all only used as inputs to loop, not
4961   // directly as branch conditions.
4962   return 0;
4963 }
4964 
4965 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4966   const Triple &TT = getTargetMachine().getTargetTriple();
4967   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4968           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4969          AMDGPU::shouldEmitConstantsToTextSection(TT);
4970 }
4971 
4972 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4973   // FIXME: Either avoid relying on address space here or change the default
4974   // address space for functions to avoid the explicit check.
4975   return (GV->getValueType()->isFunctionTy() ||
4976           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4977          !shouldEmitFixup(GV) &&
4978          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4979 }
4980 
4981 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4982   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4983 }
4984 
4985 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4986   if (!GV->hasExternalLinkage())
4987     return true;
4988 
4989   const auto OS = getTargetMachine().getTargetTriple().getOS();
4990   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4991 }
4992 
4993 /// This transforms the control flow intrinsics to get the branch destination as
4994 /// last parameter, also switches branch target with BR if the need arise
4995 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4996                                       SelectionDAG &DAG) const {
4997   SDLoc DL(BRCOND);
4998 
4999   SDNode *Intr = BRCOND.getOperand(1).getNode();
5000   SDValue Target = BRCOND.getOperand(2);
5001   SDNode *BR = nullptr;
5002   SDNode *SetCC = nullptr;
5003 
5004   if (Intr->getOpcode() == ISD::SETCC) {
5005     // As long as we negate the condition everything is fine
5006     SetCC = Intr;
5007     Intr = SetCC->getOperand(0).getNode();
5008 
5009   } else {
5010     // Get the target from BR if we don't negate the condition
5011     BR = findUser(BRCOND, ISD::BR);
5012     assert(BR && "brcond missing unconditional branch user");
5013     Target = BR->getOperand(1);
5014   }
5015 
5016   unsigned CFNode = isCFIntrinsic(Intr);
5017   if (CFNode == 0) {
5018     // This is a uniform branch so we don't need to legalize.
5019     return BRCOND;
5020   }
5021 
5022   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5023                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5024 
5025   assert(!SetCC ||
5026         (SetCC->getConstantOperandVal(1) == 1 &&
5027          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5028                                                              ISD::SETNE));
5029 
5030   // operands of the new intrinsic call
5031   SmallVector<SDValue, 4> Ops;
5032   if (HaveChain)
5033     Ops.push_back(BRCOND.getOperand(0));
5034 
5035   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5036   Ops.push_back(Target);
5037 
5038   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5039 
5040   // build the new intrinsic call
5041   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5042 
5043   if (!HaveChain) {
5044     SDValue Ops[] =  {
5045       SDValue(Result, 0),
5046       BRCOND.getOperand(0)
5047     };
5048 
5049     Result = DAG.getMergeValues(Ops, DL).getNode();
5050   }
5051 
5052   if (BR) {
5053     // Give the branch instruction our target
5054     SDValue Ops[] = {
5055       BR->getOperand(0),
5056       BRCOND.getOperand(2)
5057     };
5058     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5059     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5060   }
5061 
5062   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5063 
5064   // Copy the intrinsic results to registers
5065   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5066     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5067     if (!CopyToReg)
5068       continue;
5069 
5070     Chain = DAG.getCopyToReg(
5071       Chain, DL,
5072       CopyToReg->getOperand(1),
5073       SDValue(Result, i - 1),
5074       SDValue());
5075 
5076     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5077   }
5078 
5079   // Remove the old intrinsic from the chain
5080   DAG.ReplaceAllUsesOfValueWith(
5081     SDValue(Intr, Intr->getNumValues() - 1),
5082     Intr->getOperand(0));
5083 
5084   return Chain;
5085 }
5086 
5087 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5088                                           SelectionDAG &DAG) const {
5089   MVT VT = Op.getSimpleValueType();
5090   SDLoc DL(Op);
5091   // Checking the depth
5092   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5093     return DAG.getConstant(0, DL, VT);
5094 
5095   MachineFunction &MF = DAG.getMachineFunction();
5096   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5097   // Check for kernel and shader functions
5098   if (Info->isEntryFunction())
5099     return DAG.getConstant(0, DL, VT);
5100 
5101   MachineFrameInfo &MFI = MF.getFrameInfo();
5102   // There is a call to @llvm.returnaddress in this function
5103   MFI.setReturnAddressIsTaken(true);
5104 
5105   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5106   // Get the return address reg and mark it as an implicit live-in
5107   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5108 
5109   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5110 }
5111 
5112 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5113                                             SDValue Op,
5114                                             const SDLoc &DL,
5115                                             EVT VT) const {
5116   return Op.getValueType().bitsLE(VT) ?
5117       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5118     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5119                 DAG.getTargetConstant(0, DL, MVT::i32));
5120 }
5121 
5122 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5123   assert(Op.getValueType() == MVT::f16 &&
5124          "Do not know how to custom lower FP_ROUND for non-f16 type");
5125 
5126   SDValue Src = Op.getOperand(0);
5127   EVT SrcVT = Src.getValueType();
5128   if (SrcVT != MVT::f64)
5129     return Op;
5130 
5131   SDLoc DL(Op);
5132 
5133   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5134   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5135   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5136 }
5137 
5138 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5139                                                SelectionDAG &DAG) const {
5140   EVT VT = Op.getValueType();
5141   const MachineFunction &MF = DAG.getMachineFunction();
5142   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5143   bool IsIEEEMode = Info->getMode().IEEE;
5144 
5145   // FIXME: Assert during selection that this is only selected for
5146   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5147   // mode functions, but this happens to be OK since it's only done in cases
5148   // where there is known no sNaN.
5149   if (IsIEEEMode)
5150     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5151 
5152   if (VT == MVT::v4f16)
5153     return splitBinaryVectorOp(Op, DAG);
5154   return Op;
5155 }
5156 
5157 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5158   EVT VT = Op.getValueType();
5159   SDLoc SL(Op);
5160   SDValue LHS = Op.getOperand(0);
5161   SDValue RHS = Op.getOperand(1);
5162   bool isSigned = Op.getOpcode() == ISD::SMULO;
5163 
5164   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5165     const APInt &C = RHSC->getAPIntValue();
5166     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5167     if (C.isPowerOf2()) {
5168       // smulo(x, signed_min) is same as umulo(x, signed_min).
5169       bool UseArithShift = isSigned && !C.isMinSignedValue();
5170       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5171       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5172       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5173           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5174                       SL, VT, Result, ShiftAmt),
5175           LHS, ISD::SETNE);
5176       return DAG.getMergeValues({ Result, Overflow }, SL);
5177     }
5178   }
5179 
5180   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5181   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5182                             SL, VT, LHS, RHS);
5183 
5184   SDValue Sign = isSigned
5185     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5186                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5187     : DAG.getConstant(0, SL, VT);
5188   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5189 
5190   return DAG.getMergeValues({ Result, Overflow }, SL);
5191 }
5192 
5193 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5194   if (!Subtarget->isTrapHandlerEnabled() ||
5195       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5196     return lowerTrapEndpgm(Op, DAG);
5197 
5198   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5199     switch (*HsaAbiVer) {
5200     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5201     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5202       return lowerTrapHsaQueuePtr(Op, DAG);
5203     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5204       return Subtarget->supportsGetDoorbellID() ?
5205           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5206     }
5207   }
5208 
5209   llvm_unreachable("Unknown trap handler");
5210 }
5211 
5212 SDValue SITargetLowering::lowerTrapEndpgm(
5213     SDValue Op, SelectionDAG &DAG) const {
5214   SDLoc SL(Op);
5215   SDValue Chain = Op.getOperand(0);
5216   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5217 }
5218 
5219 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5220     SDValue Op, SelectionDAG &DAG) const {
5221   SDLoc SL(Op);
5222   SDValue Chain = Op.getOperand(0);
5223 
5224   MachineFunction &MF = DAG.getMachineFunction();
5225   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5226   Register UserSGPR = Info->getQueuePtrUserSGPR();
5227   assert(UserSGPR != AMDGPU::NoRegister);
5228   SDValue QueuePtr = CreateLiveInRegister(
5229     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5230   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5231   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5232                                    QueuePtr, SDValue());
5233 
5234   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5235   SDValue Ops[] = {
5236     ToReg,
5237     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5238     SGPR01,
5239     ToReg.getValue(1)
5240   };
5241   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5242 }
5243 
5244 SDValue SITargetLowering::lowerTrapHsa(
5245     SDValue Op, SelectionDAG &DAG) const {
5246   SDLoc SL(Op);
5247   SDValue Chain = Op.getOperand(0);
5248 
5249   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5250   SDValue Ops[] = {
5251     Chain,
5252     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5253   };
5254   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5255 }
5256 
5257 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5258   SDLoc SL(Op);
5259   SDValue Chain = Op.getOperand(0);
5260   MachineFunction &MF = DAG.getMachineFunction();
5261 
5262   if (!Subtarget->isTrapHandlerEnabled() ||
5263       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5264     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5265                                      "debugtrap handler not supported",
5266                                      Op.getDebugLoc(),
5267                                      DS_Warning);
5268     LLVMContext &Ctx = MF.getFunction().getContext();
5269     Ctx.diagnose(NoTrap);
5270     return Chain;
5271   }
5272 
5273   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5274   SDValue Ops[] = {
5275     Chain,
5276     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5277   };
5278   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5279 }
5280 
5281 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5282                                              SelectionDAG &DAG) const {
5283   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5284   if (Subtarget->hasApertureRegs()) {
5285     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5286         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5287         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5288     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5289         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5290         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5291     unsigned Encoding =
5292         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5293         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5294         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5295 
5296     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5297     SDValue ApertureReg = SDValue(
5298         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5299     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5300     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5301   }
5302 
5303   MachineFunction &MF = DAG.getMachineFunction();
5304   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5305   Register UserSGPR = Info->getQueuePtrUserSGPR();
5306   assert(UserSGPR != AMDGPU::NoRegister);
5307 
5308   SDValue QueuePtr = CreateLiveInRegister(
5309     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5310 
5311   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5312   // private_segment_aperture_base_hi.
5313   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5314 
5315   SDValue Ptr =
5316       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5317 
5318   // TODO: Use custom target PseudoSourceValue.
5319   // TODO: We should use the value from the IR intrinsic call, but it might not
5320   // be available and how do we get it?
5321   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5322   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5323                      commonAlignment(Align(64), StructOffset),
5324                      MachineMemOperand::MODereferenceable |
5325                          MachineMemOperand::MOInvariant);
5326 }
5327 
5328 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5329                                              SelectionDAG &DAG) const {
5330   SDLoc SL(Op);
5331   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5332 
5333   SDValue Src = ASC->getOperand(0);
5334   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5335 
5336   const AMDGPUTargetMachine &TM =
5337     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5338 
5339   // flat -> local/private
5340   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5341     unsigned DestAS = ASC->getDestAddressSpace();
5342 
5343     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5344         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5345       unsigned NullVal = TM.getNullPointerValue(DestAS);
5346       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5347       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5348       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5349 
5350       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5351                          NonNull, Ptr, SegmentNullPtr);
5352     }
5353   }
5354 
5355   // local/private -> flat
5356   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5357     unsigned SrcAS = ASC->getSrcAddressSpace();
5358 
5359     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5360         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5361       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5362       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5363 
5364       SDValue NonNull
5365         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5366 
5367       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5368       SDValue CvtPtr
5369         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5370 
5371       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5372                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5373                          FlatNullPtr);
5374     }
5375   }
5376 
5377   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5378       Src.getValueType() == MVT::i64)
5379     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5380 
5381   // global <-> flat are no-ops and never emitted.
5382 
5383   const MachineFunction &MF = DAG.getMachineFunction();
5384   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5385     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5386   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5387 
5388   return DAG.getUNDEF(ASC->getValueType(0));
5389 }
5390 
5391 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5392 // the small vector and inserting them into the big vector. That is better than
5393 // the default expansion of doing it via a stack slot. Even though the use of
5394 // the stack slot would be optimized away afterwards, the stack slot itself
5395 // remains.
5396 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5397                                                 SelectionDAG &DAG) const {
5398   SDValue Vec = Op.getOperand(0);
5399   SDValue Ins = Op.getOperand(1);
5400   SDValue Idx = Op.getOperand(2);
5401   EVT VecVT = Vec.getValueType();
5402   EVT InsVT = Ins.getValueType();
5403   EVT EltVT = VecVT.getVectorElementType();
5404   unsigned InsNumElts = InsVT.getVectorNumElements();
5405   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5406   SDLoc SL(Op);
5407 
5408   for (unsigned I = 0; I != InsNumElts; ++I) {
5409     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5410                               DAG.getConstant(I, SL, MVT::i32));
5411     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5412                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5413   }
5414   return Vec;
5415 }
5416 
5417 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5418                                                  SelectionDAG &DAG) const {
5419   SDValue Vec = Op.getOperand(0);
5420   SDValue InsVal = Op.getOperand(1);
5421   SDValue Idx = Op.getOperand(2);
5422   EVT VecVT = Vec.getValueType();
5423   EVT EltVT = VecVT.getVectorElementType();
5424   unsigned VecSize = VecVT.getSizeInBits();
5425   unsigned EltSize = EltVT.getSizeInBits();
5426 
5427 
5428   assert(VecSize <= 64);
5429 
5430   unsigned NumElts = VecVT.getVectorNumElements();
5431   SDLoc SL(Op);
5432   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5433 
5434   if (NumElts == 4 && EltSize == 16 && KIdx) {
5435     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5436 
5437     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5438                                  DAG.getConstant(0, SL, MVT::i32));
5439     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5440                                  DAG.getConstant(1, SL, MVT::i32));
5441 
5442     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5443     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5444 
5445     unsigned Idx = KIdx->getZExtValue();
5446     bool InsertLo = Idx < 2;
5447     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5448       InsertLo ? LoVec : HiVec,
5449       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5450       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5451 
5452     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5453 
5454     SDValue Concat = InsertLo ?
5455       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5456       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5457 
5458     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5459   }
5460 
5461   if (isa<ConstantSDNode>(Idx))
5462     return SDValue();
5463 
5464   MVT IntVT = MVT::getIntegerVT(VecSize);
5465 
5466   // Avoid stack access for dynamic indexing.
5467   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5468 
5469   // Create a congruent vector with the target value in each element so that
5470   // the required element can be masked and ORed into the target vector.
5471   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5472                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5473 
5474   assert(isPowerOf2_32(EltSize));
5475   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5476 
5477   // Convert vector index to bit-index.
5478   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5479 
5480   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5481   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5482                             DAG.getConstant(0xffff, SL, IntVT),
5483                             ScaledIdx);
5484 
5485   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5486   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5487                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5488 
5489   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5490   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5491 }
5492 
5493 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5494                                                   SelectionDAG &DAG) const {
5495   SDLoc SL(Op);
5496 
5497   EVT ResultVT = Op.getValueType();
5498   SDValue Vec = Op.getOperand(0);
5499   SDValue Idx = Op.getOperand(1);
5500   EVT VecVT = Vec.getValueType();
5501   unsigned VecSize = VecVT.getSizeInBits();
5502   EVT EltVT = VecVT.getVectorElementType();
5503   assert(VecSize <= 64);
5504 
5505   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5506 
5507   // Make sure we do any optimizations that will make it easier to fold
5508   // source modifiers before obscuring it with bit operations.
5509 
5510   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5511   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5512     return Combined;
5513 
5514   unsigned EltSize = EltVT.getSizeInBits();
5515   assert(isPowerOf2_32(EltSize));
5516 
5517   MVT IntVT = MVT::getIntegerVT(VecSize);
5518   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5519 
5520   // Convert vector index to bit-index (* EltSize)
5521   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5522 
5523   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5524   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5525 
5526   if (ResultVT == MVT::f16) {
5527     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5528     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5529   }
5530 
5531   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5532 }
5533 
5534 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5535   assert(Elt % 2 == 0);
5536   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5537 }
5538 
5539 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5540                                               SelectionDAG &DAG) const {
5541   SDLoc SL(Op);
5542   EVT ResultVT = Op.getValueType();
5543   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5544 
5545   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5546   EVT EltVT = PackVT.getVectorElementType();
5547   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5548 
5549   // vector_shuffle <0,1,6,7> lhs, rhs
5550   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5551   //
5552   // vector_shuffle <6,7,2,3> lhs, rhs
5553   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5554   //
5555   // vector_shuffle <6,7,0,1> lhs, rhs
5556   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5557 
5558   // Avoid scalarizing when both halves are reading from consecutive elements.
5559   SmallVector<SDValue, 4> Pieces;
5560   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5561     if (elementPairIsContiguous(SVN->getMask(), I)) {
5562       const int Idx = SVN->getMaskElt(I);
5563       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5564       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5565       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5566                                     PackVT, SVN->getOperand(VecIdx),
5567                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5568       Pieces.push_back(SubVec);
5569     } else {
5570       const int Idx0 = SVN->getMaskElt(I);
5571       const int Idx1 = SVN->getMaskElt(I + 1);
5572       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5573       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5574       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5575       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5576 
5577       SDValue Vec0 = SVN->getOperand(VecIdx0);
5578       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5579                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5580 
5581       SDValue Vec1 = SVN->getOperand(VecIdx1);
5582       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5583                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5584       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5585     }
5586   }
5587 
5588   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5589 }
5590 
5591 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5592                                             SelectionDAG &DAG) const {
5593   SDLoc SL(Op);
5594   EVT VT = Op.getValueType();
5595 
5596   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5597     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5598 
5599     // Turn into pair of packed build_vectors.
5600     // TODO: Special case for constants that can be materialized with s_mov_b64.
5601     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5602                                     { Op.getOperand(0), Op.getOperand(1) });
5603     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5604                                     { Op.getOperand(2), Op.getOperand(3) });
5605 
5606     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5607     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5608 
5609     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5610     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5611   }
5612 
5613   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5614   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5615 
5616   SDValue Lo = Op.getOperand(0);
5617   SDValue Hi = Op.getOperand(1);
5618 
5619   // Avoid adding defined bits with the zero_extend.
5620   if (Hi.isUndef()) {
5621     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5622     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5623     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5624   }
5625 
5626   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5627   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5628 
5629   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5630                               DAG.getConstant(16, SL, MVT::i32));
5631   if (Lo.isUndef())
5632     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5633 
5634   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5635   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5636 
5637   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5638   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5639 }
5640 
5641 bool
5642 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5643   // We can fold offsets for anything that doesn't require a GOT relocation.
5644   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5645           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5646           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5647          !shouldEmitGOTReloc(GA->getGlobal());
5648 }
5649 
5650 static SDValue
5651 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5652                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5653                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5654   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5655   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5656   // lowered to the following code sequence:
5657   //
5658   // For constant address space:
5659   //   s_getpc_b64 s[0:1]
5660   //   s_add_u32 s0, s0, $symbol
5661   //   s_addc_u32 s1, s1, 0
5662   //
5663   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5664   //   a fixup or relocation is emitted to replace $symbol with a literal
5665   //   constant, which is a pc-relative offset from the encoding of the $symbol
5666   //   operand to the global variable.
5667   //
5668   // For global address space:
5669   //   s_getpc_b64 s[0:1]
5670   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5671   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5672   //
5673   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5674   //   fixups or relocations are emitted to replace $symbol@*@lo and
5675   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5676   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5677   //   operand to the global variable.
5678   //
5679   // What we want here is an offset from the value returned by s_getpc
5680   // (which is the address of the s_add_u32 instruction) to the global
5681   // variable, but since the encoding of $symbol starts 4 bytes after the start
5682   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5683   // small. This requires us to add 4 to the global variable offset in order to
5684   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5685   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5686   // instruction.
5687   SDValue PtrLo =
5688       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5689   SDValue PtrHi;
5690   if (GAFlags == SIInstrInfo::MO_NONE) {
5691     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5692   } else {
5693     PtrHi =
5694         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5695   }
5696   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5697 }
5698 
5699 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5700                                              SDValue Op,
5701                                              SelectionDAG &DAG) const {
5702   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5703   SDLoc DL(GSD);
5704   EVT PtrVT = Op.getValueType();
5705 
5706   const GlobalValue *GV = GSD->getGlobal();
5707   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5708        shouldUseLDSConstAddress(GV)) ||
5709       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5710       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5711     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5712         GV->hasExternalLinkage()) {
5713       Type *Ty = GV->getValueType();
5714       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5715       // zero-sized type in other languages to declare the dynamic shared
5716       // memory which size is not known at the compile time. They will be
5717       // allocated by the runtime and placed directly after the static
5718       // allocated ones. They all share the same offset.
5719       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5720         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5721         // Adjust alignment for that dynamic shared memory array.
5722         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5723         return SDValue(
5724             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5725       }
5726     }
5727     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5728   }
5729 
5730   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5731     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5732                                             SIInstrInfo::MO_ABS32_LO);
5733     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5734   }
5735 
5736   if (shouldEmitFixup(GV))
5737     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5738   else if (shouldEmitPCReloc(GV))
5739     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5740                                    SIInstrInfo::MO_REL32);
5741 
5742   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5743                                             SIInstrInfo::MO_GOTPCREL32);
5744 
5745   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5746   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5747   const DataLayout &DataLayout = DAG.getDataLayout();
5748   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5749   MachinePointerInfo PtrInfo
5750     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5751 
5752   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5753                      MachineMemOperand::MODereferenceable |
5754                          MachineMemOperand::MOInvariant);
5755 }
5756 
5757 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5758                                    const SDLoc &DL, SDValue V) const {
5759   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5760   // the destination register.
5761   //
5762   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5763   // so we will end up with redundant moves to m0.
5764   //
5765   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5766 
5767   // A Null SDValue creates a glue result.
5768   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5769                                   V, Chain);
5770   return SDValue(M0, 0);
5771 }
5772 
5773 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5774                                                  SDValue Op,
5775                                                  MVT VT,
5776                                                  unsigned Offset) const {
5777   SDLoc SL(Op);
5778   SDValue Param = lowerKernargMemParameter(
5779       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5780   // The local size values will have the hi 16-bits as zero.
5781   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5782                      DAG.getValueType(VT));
5783 }
5784 
5785 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5786                                         EVT VT) {
5787   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5788                                       "non-hsa intrinsic with hsa target",
5789                                       DL.getDebugLoc());
5790   DAG.getContext()->diagnose(BadIntrin);
5791   return DAG.getUNDEF(VT);
5792 }
5793 
5794 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5795                                          EVT VT) {
5796   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5797                                       "intrinsic not supported on subtarget",
5798                                       DL.getDebugLoc());
5799   DAG.getContext()->diagnose(BadIntrin);
5800   return DAG.getUNDEF(VT);
5801 }
5802 
5803 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5804                                     ArrayRef<SDValue> Elts) {
5805   assert(!Elts.empty());
5806   MVT Type;
5807   unsigned NumElts;
5808 
5809   if (Elts.size() == 1) {
5810     Type = MVT::f32;
5811     NumElts = 1;
5812   } else if (Elts.size() == 2) {
5813     Type = MVT::v2f32;
5814     NumElts = 2;
5815   } else if (Elts.size() == 3) {
5816     Type = MVT::v3f32;
5817     NumElts = 3;
5818   } else if (Elts.size() <= 4) {
5819     Type = MVT::v4f32;
5820     NumElts = 4;
5821   } else if (Elts.size() <= 5) {
5822     Type = MVT::v5f32;
5823     NumElts = 5;
5824   } else if (Elts.size() <= 8) {
5825     Type = MVT::v8f32;
5826     NumElts = 8;
5827   } else {
5828     assert(Elts.size() <= 16);
5829     Type = MVT::v16f32;
5830     NumElts = 16;
5831   }
5832 
5833   SmallVector<SDValue, 16> VecElts(NumElts);
5834   for (unsigned i = 0; i < Elts.size(); ++i) {
5835     SDValue Elt = Elts[i];
5836     if (Elt.getValueType() != MVT::f32)
5837       Elt = DAG.getBitcast(MVT::f32, Elt);
5838     VecElts[i] = Elt;
5839   }
5840   for (unsigned i = Elts.size(); i < NumElts; ++i)
5841     VecElts[i] = DAG.getUNDEF(MVT::f32);
5842 
5843   if (NumElts == 1)
5844     return VecElts[0];
5845   return DAG.getBuildVector(Type, DL, VecElts);
5846 }
5847 
5848 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5849                               SDValue Src, int ExtraElts) {
5850   EVT SrcVT = Src.getValueType();
5851 
5852   SmallVector<SDValue, 8> Elts;
5853 
5854   if (SrcVT.isVector())
5855     DAG.ExtractVectorElements(Src, Elts);
5856   else
5857     Elts.push_back(Src);
5858 
5859   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5860   while (ExtraElts--)
5861     Elts.push_back(Undef);
5862 
5863   return DAG.getBuildVector(CastVT, DL, Elts);
5864 }
5865 
5866 // Re-construct the required return value for a image load intrinsic.
5867 // This is more complicated due to the optional use TexFailCtrl which means the required
5868 // return type is an aggregate
5869 static SDValue constructRetValue(SelectionDAG &DAG,
5870                                  MachineSDNode *Result,
5871                                  ArrayRef<EVT> ResultTypes,
5872                                  bool IsTexFail, bool Unpacked, bool IsD16,
5873                                  int DMaskPop, int NumVDataDwords,
5874                                  const SDLoc &DL) {
5875   // Determine the required return type. This is the same regardless of IsTexFail flag
5876   EVT ReqRetVT = ResultTypes[0];
5877   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5878   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5879     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5880 
5881   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5882     DMaskPop : (DMaskPop + 1) / 2;
5883 
5884   MVT DataDwordVT = NumDataDwords == 1 ?
5885     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5886 
5887   MVT MaskPopVT = MaskPopDwords == 1 ?
5888     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5889 
5890   SDValue Data(Result, 0);
5891   SDValue TexFail;
5892 
5893   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5894     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5895     if (MaskPopVT.isVector()) {
5896       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5897                          SDValue(Result, 0), ZeroIdx);
5898     } else {
5899       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5900                          SDValue(Result, 0), ZeroIdx);
5901     }
5902   }
5903 
5904   if (DataDwordVT.isVector())
5905     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5906                           NumDataDwords - MaskPopDwords);
5907 
5908   if (IsD16)
5909     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5910 
5911   EVT LegalReqRetVT = ReqRetVT;
5912   if (!ReqRetVT.isVector()) {
5913     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5914   } else {
5915     // We need to widen the return vector to a legal type
5916     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5917         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5918       LegalReqRetVT =
5919           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5920                            ReqRetVT.getVectorNumElements() + 1);
5921     }
5922   }
5923   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5924 
5925   if (IsTexFail) {
5926     TexFail =
5927         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5928                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5929 
5930     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5931   }
5932 
5933   if (Result->getNumValues() == 1)
5934     return Data;
5935 
5936   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5937 }
5938 
5939 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5940                          SDValue *LWE, bool &IsTexFail) {
5941   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5942 
5943   uint64_t Value = TexFailCtrlConst->getZExtValue();
5944   if (Value) {
5945     IsTexFail = true;
5946   }
5947 
5948   SDLoc DL(TexFailCtrlConst);
5949   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5950   Value &= ~(uint64_t)0x1;
5951   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5952   Value &= ~(uint64_t)0x2;
5953 
5954   return Value == 0;
5955 }
5956 
5957 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
5958                                       MVT PackVectorVT,
5959                                       SmallVectorImpl<SDValue> &PackedAddrs,
5960                                       unsigned DimIdx, unsigned EndIdx,
5961                                       unsigned NumGradients) {
5962   SDLoc DL(Op);
5963   for (unsigned I = DimIdx; I < EndIdx; I++) {
5964     SDValue Addr = Op.getOperand(I);
5965 
5966     // Gradients are packed with undef for each coordinate.
5967     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5968     // 1D: undef,dx/dh; undef,dx/dv
5969     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5970     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5971     if (((I + 1) >= EndIdx) ||
5972         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5973                                          I == DimIdx + NumGradients - 1))) {
5974       if (Addr.getValueType() != MVT::i16)
5975         Addr = DAG.getBitcast(MVT::i16, Addr);
5976       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5977     } else {
5978       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5979       I++;
5980     }
5981     Addr = DAG.getBitcast(MVT::f32, Addr);
5982     PackedAddrs.push_back(Addr);
5983   }
5984 }
5985 
5986 SDValue SITargetLowering::lowerImage(SDValue Op,
5987                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5988                                      SelectionDAG &DAG, bool WithChain) const {
5989   SDLoc DL(Op);
5990   MachineFunction &MF = DAG.getMachineFunction();
5991   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5992   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5993       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5994   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5995   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5996       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5997   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5998       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5999   unsigned IntrOpcode = Intr->BaseOpcode;
6000   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6001 
6002   SmallVector<EVT, 3> ResultTypes(Op->values());
6003   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6004   bool IsD16 = false;
6005   bool IsG16 = false;
6006   bool IsA16 = false;
6007   SDValue VData;
6008   int NumVDataDwords;
6009   bool AdjustRetType = false;
6010 
6011   // Offset of intrinsic arguments
6012   const unsigned ArgOffset = WithChain ? 2 : 1;
6013 
6014   unsigned DMask;
6015   unsigned DMaskLanes = 0;
6016 
6017   if (BaseOpcode->Atomic) {
6018     VData = Op.getOperand(2);
6019 
6020     bool Is64Bit = VData.getValueType() == MVT::i64;
6021     if (BaseOpcode->AtomicX2) {
6022       SDValue VData2 = Op.getOperand(3);
6023       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6024                                  {VData, VData2});
6025       if (Is64Bit)
6026         VData = DAG.getBitcast(MVT::v4i32, VData);
6027 
6028       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6029       DMask = Is64Bit ? 0xf : 0x3;
6030       NumVDataDwords = Is64Bit ? 4 : 2;
6031     } else {
6032       DMask = Is64Bit ? 0x3 : 0x1;
6033       NumVDataDwords = Is64Bit ? 2 : 1;
6034     }
6035   } else {
6036     auto *DMaskConst =
6037         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6038     DMask = DMaskConst->getZExtValue();
6039     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6040 
6041     if (BaseOpcode->Store) {
6042       VData = Op.getOperand(2);
6043 
6044       MVT StoreVT = VData.getSimpleValueType();
6045       if (StoreVT.getScalarType() == MVT::f16) {
6046         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6047           return Op; // D16 is unsupported for this instruction
6048 
6049         IsD16 = true;
6050         VData = handleD16VData(VData, DAG, true);
6051       }
6052 
6053       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6054     } else {
6055       // Work out the num dwords based on the dmask popcount and underlying type
6056       // and whether packing is supported.
6057       MVT LoadVT = ResultTypes[0].getSimpleVT();
6058       if (LoadVT.getScalarType() == MVT::f16) {
6059         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6060           return Op; // D16 is unsupported for this instruction
6061 
6062         IsD16 = true;
6063       }
6064 
6065       // Confirm that the return type is large enough for the dmask specified
6066       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6067           (!LoadVT.isVector() && DMaskLanes > 1))
6068           return Op;
6069 
6070       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6071       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6072       // instructions.
6073       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6074           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6075         NumVDataDwords = (DMaskLanes + 1) / 2;
6076       else
6077         NumVDataDwords = DMaskLanes;
6078 
6079       AdjustRetType = true;
6080     }
6081   }
6082 
6083   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6084   SmallVector<SDValue, 4> VAddrs;
6085 
6086   // Optimize _L to _LZ when _L is zero
6087   if (LZMappingInfo) {
6088     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6089             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6090       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6091         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6092         VAddrEnd--;                      // remove 'lod'
6093       }
6094     }
6095   }
6096 
6097   // Optimize _mip away, when 'lod' is zero
6098   if (MIPMappingInfo) {
6099     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6100             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6101       if (ConstantLod->isNullValue()) {
6102         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6103         VAddrEnd--;                           // remove 'mip'
6104       }
6105     }
6106   }
6107 
6108   // Push back extra arguments.
6109   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6110     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6111 
6112   // Check for 16 bit addresses or derivatives and pack if true.
6113   MVT VAddrVT =
6114       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6115   MVT VAddrScalarVT = VAddrVT.getScalarType();
6116   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6117   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6118 
6119   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6120   VAddrScalarVT = VAddrVT.getScalarType();
6121   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6122   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6123 
6124   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6125     // 16 bit gradients are supported, but are tied to the A16 control
6126     // so both gradients and addresses must be 16 bit
6127     LLVM_DEBUG(
6128         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6129                   "require 16 bit args for both gradients and addresses");
6130     return Op;
6131   }
6132 
6133   if (IsA16) {
6134     if (!ST->hasA16()) {
6135       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6136                            "support 16 bit addresses\n");
6137       return Op;
6138     }
6139   }
6140 
6141   // We've dealt with incorrect input so we know that if IsA16, IsG16
6142   // are set then we have to compress/pack operands (either address,
6143   // gradient or both)
6144   // In the case where a16 and gradients are tied (no G16 support) then we
6145   // have already verified that both IsA16 and IsG16 are true
6146   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6147     // Activate g16
6148     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6149         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6150     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6151   }
6152 
6153   // Add gradients (packed or unpacked)
6154   if (IsG16) {
6155     // Pack the gradients
6156     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6157     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6158                               ArgOffset + Intr->GradientStart,
6159                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6160   } else {
6161     for (unsigned I = ArgOffset + Intr->GradientStart;
6162          I < ArgOffset + Intr->CoordStart; I++)
6163       VAddrs.push_back(Op.getOperand(I));
6164   }
6165 
6166   // Add addresses (packed or unpacked)
6167   if (IsA16) {
6168     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6169                               ArgOffset + Intr->CoordStart, VAddrEnd,
6170                               0 /* No gradients */);
6171   } else {
6172     // Add uncompressed address
6173     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6174       VAddrs.push_back(Op.getOperand(I));
6175   }
6176 
6177   // If the register allocator cannot place the address registers contiguously
6178   // without introducing moves, then using the non-sequential address encoding
6179   // is always preferable, since it saves VALU instructions and is usually a
6180   // wash in terms of code size or even better.
6181   //
6182   // However, we currently have no way of hinting to the register allocator that
6183   // MIMG addresses should be placed contiguously when it is possible to do so,
6184   // so force non-NSA for the common 2-address case as a heuristic.
6185   //
6186   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6187   // allocation when possible.
6188   bool UseNSA =
6189       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6190   SDValue VAddr;
6191   if (!UseNSA)
6192     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6193 
6194   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6195   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6196   SDValue Unorm;
6197   if (!BaseOpcode->Sampler) {
6198     Unorm = True;
6199   } else {
6200     auto UnormConst =
6201         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6202 
6203     Unorm = UnormConst->getZExtValue() ? True : False;
6204   }
6205 
6206   SDValue TFE;
6207   SDValue LWE;
6208   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6209   bool IsTexFail = false;
6210   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6211     return Op;
6212 
6213   if (IsTexFail) {
6214     if (!DMaskLanes) {
6215       // Expecting to get an error flag since TFC is on - and dmask is 0
6216       // Force dmask to be at least 1 otherwise the instruction will fail
6217       DMask = 0x1;
6218       DMaskLanes = 1;
6219       NumVDataDwords = 1;
6220     }
6221     NumVDataDwords += 1;
6222     AdjustRetType = true;
6223   }
6224 
6225   // Has something earlier tagged that the return type needs adjusting
6226   // This happens if the instruction is a load or has set TexFailCtrl flags
6227   if (AdjustRetType) {
6228     // NumVDataDwords reflects the true number of dwords required in the return type
6229     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6230       // This is a no-op load. This can be eliminated
6231       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6232       if (isa<MemSDNode>(Op))
6233         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6234       return Undef;
6235     }
6236 
6237     EVT NewVT = NumVDataDwords > 1 ?
6238                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6239                 : MVT::i32;
6240 
6241     ResultTypes[0] = NewVT;
6242     if (ResultTypes.size() == 3) {
6243       // Original result was aggregate type used for TexFailCtrl results
6244       // The actual instruction returns as a vector type which has now been
6245       // created. Remove the aggregate result.
6246       ResultTypes.erase(&ResultTypes[1]);
6247     }
6248   }
6249 
6250   unsigned CPol = cast<ConstantSDNode>(
6251       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6252   if (BaseOpcode->Atomic)
6253     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6254   if (CPol & ~AMDGPU::CPol::ALL)
6255     return Op;
6256 
6257   SmallVector<SDValue, 26> Ops;
6258   if (BaseOpcode->Store || BaseOpcode->Atomic)
6259     Ops.push_back(VData); // vdata
6260   if (UseNSA)
6261     append_range(Ops, VAddrs);
6262   else
6263     Ops.push_back(VAddr);
6264   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6265   if (BaseOpcode->Sampler)
6266     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6267   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6268   if (IsGFX10Plus)
6269     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6270   Ops.push_back(Unorm);
6271   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6272   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6273                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6274   if (IsGFX10Plus)
6275     Ops.push_back(IsA16 ? True : False);
6276   if (!Subtarget->hasGFX90AInsts()) {
6277     Ops.push_back(TFE); //tfe
6278   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6279     report_fatal_error("TFE is not supported on this GPU");
6280   }
6281   Ops.push_back(LWE); // lwe
6282   if (!IsGFX10Plus)
6283     Ops.push_back(DimInfo->DA ? True : False);
6284   if (BaseOpcode->HasD16)
6285     Ops.push_back(IsD16 ? True : False);
6286   if (isa<MemSDNode>(Op))
6287     Ops.push_back(Op.getOperand(0)); // chain
6288 
6289   int NumVAddrDwords =
6290       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6291   int Opcode = -1;
6292 
6293   if (IsGFX10Plus) {
6294     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6295                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6296                                           : AMDGPU::MIMGEncGfx10Default,
6297                                    NumVDataDwords, NumVAddrDwords);
6298   } else {
6299     if (Subtarget->hasGFX90AInsts()) {
6300       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6301                                      NumVDataDwords, NumVAddrDwords);
6302       if (Opcode == -1)
6303         report_fatal_error(
6304             "requested image instruction is not supported on this GPU");
6305     }
6306     if (Opcode == -1 &&
6307         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6308       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6309                                      NumVDataDwords, NumVAddrDwords);
6310     if (Opcode == -1)
6311       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6312                                      NumVDataDwords, NumVAddrDwords);
6313   }
6314   assert(Opcode != -1);
6315 
6316   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6317   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6318     MachineMemOperand *MemRef = MemOp->getMemOperand();
6319     DAG.setNodeMemRefs(NewNode, {MemRef});
6320   }
6321 
6322   if (BaseOpcode->AtomicX2) {
6323     SmallVector<SDValue, 1> Elt;
6324     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6325     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6326   }
6327   if (BaseOpcode->Store)
6328     return SDValue(NewNode, 0);
6329   return constructRetValue(DAG, NewNode,
6330                            OrigResultTypes, IsTexFail,
6331                            Subtarget->hasUnpackedD16VMem(), IsD16,
6332                            DMaskLanes, NumVDataDwords, DL);
6333 }
6334 
6335 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6336                                        SDValue Offset, SDValue CachePolicy,
6337                                        SelectionDAG &DAG) const {
6338   MachineFunction &MF = DAG.getMachineFunction();
6339 
6340   const DataLayout &DataLayout = DAG.getDataLayout();
6341   Align Alignment =
6342       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6343 
6344   MachineMemOperand *MMO = MF.getMachineMemOperand(
6345       MachinePointerInfo(),
6346       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6347           MachineMemOperand::MOInvariant,
6348       VT.getStoreSize(), Alignment);
6349 
6350   if (!Offset->isDivergent()) {
6351     SDValue Ops[] = {
6352         Rsrc,
6353         Offset, // Offset
6354         CachePolicy
6355     };
6356 
6357     // Widen vec3 load to vec4.
6358     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6359       EVT WidenedVT =
6360           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6361       auto WidenedOp = DAG.getMemIntrinsicNode(
6362           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6363           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6364       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6365                                    DAG.getVectorIdxConstant(0, DL));
6366       return Subvector;
6367     }
6368 
6369     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6370                                    DAG.getVTList(VT), Ops, VT, MMO);
6371   }
6372 
6373   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6374   // assume that the buffer is unswizzled.
6375   SmallVector<SDValue, 4> Loads;
6376   unsigned NumLoads = 1;
6377   MVT LoadVT = VT.getSimpleVT();
6378   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6379   assert((LoadVT.getScalarType() == MVT::i32 ||
6380           LoadVT.getScalarType() == MVT::f32));
6381 
6382   if (NumElts == 8 || NumElts == 16) {
6383     NumLoads = NumElts / 4;
6384     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6385   }
6386 
6387   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6388   SDValue Ops[] = {
6389       DAG.getEntryNode(),                               // Chain
6390       Rsrc,                                             // rsrc
6391       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6392       {},                                               // voffset
6393       {},                                               // soffset
6394       {},                                               // offset
6395       CachePolicy,                                      // cachepolicy
6396       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6397   };
6398 
6399   // Use the alignment to ensure that the required offsets will fit into the
6400   // immediate offsets.
6401   setBufferOffsets(Offset, DAG, &Ops[3],
6402                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6403 
6404   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6405   for (unsigned i = 0; i < NumLoads; ++i) {
6406     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6407     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6408                                         LoadVT, MMO, DAG));
6409   }
6410 
6411   if (NumElts == 8 || NumElts == 16)
6412     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6413 
6414   return Loads[0];
6415 }
6416 
6417 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6418                                                   SelectionDAG &DAG) const {
6419   MachineFunction &MF = DAG.getMachineFunction();
6420   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6421 
6422   EVT VT = Op.getValueType();
6423   SDLoc DL(Op);
6424   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6425 
6426   // TODO: Should this propagate fast-math-flags?
6427 
6428   switch (IntrinsicID) {
6429   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6430     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6431       return emitNonHSAIntrinsicError(DAG, DL, VT);
6432     return getPreloadedValue(DAG, *MFI, VT,
6433                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6434   }
6435   case Intrinsic::amdgcn_dispatch_ptr:
6436   case Intrinsic::amdgcn_queue_ptr: {
6437     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6438       DiagnosticInfoUnsupported BadIntrin(
6439           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6440           DL.getDebugLoc());
6441       DAG.getContext()->diagnose(BadIntrin);
6442       return DAG.getUNDEF(VT);
6443     }
6444 
6445     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6446       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6447     return getPreloadedValue(DAG, *MFI, VT, RegID);
6448   }
6449   case Intrinsic::amdgcn_implicitarg_ptr: {
6450     if (MFI->isEntryFunction())
6451       return getImplicitArgPtr(DAG, DL);
6452     return getPreloadedValue(DAG, *MFI, VT,
6453                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6454   }
6455   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6456     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6457       // This only makes sense to call in a kernel, so just lower to null.
6458       return DAG.getConstant(0, DL, VT);
6459     }
6460 
6461     return getPreloadedValue(DAG, *MFI, VT,
6462                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6463   }
6464   case Intrinsic::amdgcn_dispatch_id: {
6465     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6466   }
6467   case Intrinsic::amdgcn_rcp:
6468     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6469   case Intrinsic::amdgcn_rsq:
6470     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6471   case Intrinsic::amdgcn_rsq_legacy:
6472     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6473       return emitRemovedIntrinsicError(DAG, DL, VT);
6474     return SDValue();
6475   case Intrinsic::amdgcn_rcp_legacy:
6476     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6477       return emitRemovedIntrinsicError(DAG, DL, VT);
6478     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6479   case Intrinsic::amdgcn_rsq_clamp: {
6480     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6481       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6482 
6483     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6484     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6485     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6486 
6487     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6488     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6489                               DAG.getConstantFP(Max, DL, VT));
6490     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6491                        DAG.getConstantFP(Min, DL, VT));
6492   }
6493   case Intrinsic::r600_read_ngroups_x:
6494     if (Subtarget->isAmdHsaOS())
6495       return emitNonHSAIntrinsicError(DAG, DL, VT);
6496 
6497     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6498                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6499                                     false);
6500   case Intrinsic::r600_read_ngroups_y:
6501     if (Subtarget->isAmdHsaOS())
6502       return emitNonHSAIntrinsicError(DAG, DL, VT);
6503 
6504     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6505                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6506                                     false);
6507   case Intrinsic::r600_read_ngroups_z:
6508     if (Subtarget->isAmdHsaOS())
6509       return emitNonHSAIntrinsicError(DAG, DL, VT);
6510 
6511     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6512                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6513                                     false);
6514   case Intrinsic::r600_read_global_size_x:
6515     if (Subtarget->isAmdHsaOS())
6516       return emitNonHSAIntrinsicError(DAG, DL, VT);
6517 
6518     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6519                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6520                                     Align(4), false);
6521   case Intrinsic::r600_read_global_size_y:
6522     if (Subtarget->isAmdHsaOS())
6523       return emitNonHSAIntrinsicError(DAG, DL, VT);
6524 
6525     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6526                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6527                                     Align(4), false);
6528   case Intrinsic::r600_read_global_size_z:
6529     if (Subtarget->isAmdHsaOS())
6530       return emitNonHSAIntrinsicError(DAG, DL, VT);
6531 
6532     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6533                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6534                                     Align(4), false);
6535   case Intrinsic::r600_read_local_size_x:
6536     if (Subtarget->isAmdHsaOS())
6537       return emitNonHSAIntrinsicError(DAG, DL, VT);
6538 
6539     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6540                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6541   case Intrinsic::r600_read_local_size_y:
6542     if (Subtarget->isAmdHsaOS())
6543       return emitNonHSAIntrinsicError(DAG, DL, VT);
6544 
6545     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6546                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6547   case Intrinsic::r600_read_local_size_z:
6548     if (Subtarget->isAmdHsaOS())
6549       return emitNonHSAIntrinsicError(DAG, DL, VT);
6550 
6551     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6552                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6553   case Intrinsic::amdgcn_workgroup_id_x:
6554     return getPreloadedValue(DAG, *MFI, VT,
6555                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6556   case Intrinsic::amdgcn_workgroup_id_y:
6557     return getPreloadedValue(DAG, *MFI, VT,
6558                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6559   case Intrinsic::amdgcn_workgroup_id_z:
6560     return getPreloadedValue(DAG, *MFI, VT,
6561                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6562   case Intrinsic::amdgcn_workitem_id_x:
6563     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6564                           SDLoc(DAG.getEntryNode()),
6565                           MFI->getArgInfo().WorkItemIDX);
6566   case Intrinsic::amdgcn_workitem_id_y:
6567     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6568                           SDLoc(DAG.getEntryNode()),
6569                           MFI->getArgInfo().WorkItemIDY);
6570   case Intrinsic::amdgcn_workitem_id_z:
6571     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6572                           SDLoc(DAG.getEntryNode()),
6573                           MFI->getArgInfo().WorkItemIDZ);
6574   case Intrinsic::amdgcn_wavefrontsize:
6575     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6576                            SDLoc(Op), MVT::i32);
6577   case Intrinsic::amdgcn_s_buffer_load: {
6578     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6579     if (CPol & ~AMDGPU::CPol::ALL)
6580       return Op;
6581     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6582                         DAG);
6583   }
6584   case Intrinsic::amdgcn_fdiv_fast:
6585     return lowerFDIV_FAST(Op, DAG);
6586   case Intrinsic::amdgcn_sin:
6587     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6588 
6589   case Intrinsic::amdgcn_cos:
6590     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6591 
6592   case Intrinsic::amdgcn_mul_u24:
6593     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6594   case Intrinsic::amdgcn_mul_i24:
6595     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6596 
6597   case Intrinsic::amdgcn_log_clamp: {
6598     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6599       return SDValue();
6600 
6601     return emitRemovedIntrinsicError(DAG, DL, VT);
6602   }
6603   case Intrinsic::amdgcn_ldexp:
6604     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6605                        Op.getOperand(1), Op.getOperand(2));
6606 
6607   case Intrinsic::amdgcn_fract:
6608     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6609 
6610   case Intrinsic::amdgcn_class:
6611     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6612                        Op.getOperand(1), Op.getOperand(2));
6613   case Intrinsic::amdgcn_div_fmas:
6614     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6615                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6616                        Op.getOperand(4));
6617 
6618   case Intrinsic::amdgcn_div_fixup:
6619     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6620                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6621 
6622   case Intrinsic::amdgcn_div_scale: {
6623     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6624 
6625     // Translate to the operands expected by the machine instruction. The
6626     // first parameter must be the same as the first instruction.
6627     SDValue Numerator = Op.getOperand(1);
6628     SDValue Denominator = Op.getOperand(2);
6629 
6630     // Note this order is opposite of the machine instruction's operations,
6631     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6632     // intrinsic has the numerator as the first operand to match a normal
6633     // division operation.
6634 
6635     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6636 
6637     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6638                        Denominator, Numerator);
6639   }
6640   case Intrinsic::amdgcn_icmp: {
6641     // There is a Pat that handles this variant, so return it as-is.
6642     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6643         Op.getConstantOperandVal(2) == 0 &&
6644         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6645       return Op;
6646     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6647   }
6648   case Intrinsic::amdgcn_fcmp: {
6649     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6650   }
6651   case Intrinsic::amdgcn_ballot:
6652     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6653   case Intrinsic::amdgcn_fmed3:
6654     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6655                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6656   case Intrinsic::amdgcn_fdot2:
6657     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6658                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6659                        Op.getOperand(4));
6660   case Intrinsic::amdgcn_fmul_legacy:
6661     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6662                        Op.getOperand(1), Op.getOperand(2));
6663   case Intrinsic::amdgcn_sffbh:
6664     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6665   case Intrinsic::amdgcn_sbfe:
6666     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6667                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6668   case Intrinsic::amdgcn_ubfe:
6669     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6670                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6671   case Intrinsic::amdgcn_cvt_pkrtz:
6672   case Intrinsic::amdgcn_cvt_pknorm_i16:
6673   case Intrinsic::amdgcn_cvt_pknorm_u16:
6674   case Intrinsic::amdgcn_cvt_pk_i16:
6675   case Intrinsic::amdgcn_cvt_pk_u16: {
6676     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6677     EVT VT = Op.getValueType();
6678     unsigned Opcode;
6679 
6680     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6681       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6682     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6683       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6684     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6685       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6686     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6687       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6688     else
6689       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6690 
6691     if (isTypeLegal(VT))
6692       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6693 
6694     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6695                                Op.getOperand(1), Op.getOperand(2));
6696     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6697   }
6698   case Intrinsic::amdgcn_fmad_ftz:
6699     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6700                        Op.getOperand(2), Op.getOperand(3));
6701 
6702   case Intrinsic::amdgcn_if_break:
6703     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6704                                       Op->getOperand(1), Op->getOperand(2)), 0);
6705 
6706   case Intrinsic::amdgcn_groupstaticsize: {
6707     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6708     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6709       return Op;
6710 
6711     const Module *M = MF.getFunction().getParent();
6712     const GlobalValue *GV =
6713         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6714     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6715                                             SIInstrInfo::MO_ABS32_LO);
6716     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6717   }
6718   case Intrinsic::amdgcn_is_shared:
6719   case Intrinsic::amdgcn_is_private: {
6720     SDLoc SL(Op);
6721     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6722       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6723     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6724     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6725                                  Op.getOperand(1));
6726 
6727     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6728                                 DAG.getConstant(1, SL, MVT::i32));
6729     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6730   }
6731   case Intrinsic::amdgcn_alignbit:
6732     return DAG.getNode(ISD::FSHR, DL, VT,
6733                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6734   case Intrinsic::amdgcn_perm:
6735     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6736                        Op.getOperand(2), Op.getOperand(3));
6737   case Intrinsic::amdgcn_reloc_constant: {
6738     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6739     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6740     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6741     auto RelocSymbol = cast<GlobalVariable>(
6742         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6743     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6744                                             SIInstrInfo::MO_ABS32_LO);
6745     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6746   }
6747   default:
6748     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6749             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6750       return lowerImage(Op, ImageDimIntr, DAG, false);
6751 
6752     return Op;
6753   }
6754 }
6755 
6756 // This function computes an appropriate offset to pass to
6757 // MachineMemOperand::setOffset() based on the offset inputs to
6758 // an intrinsic.  If any of the offsets are non-contstant or
6759 // if VIndex is non-zero then this function returns 0.  Otherwise,
6760 // it returns the sum of VOffset, SOffset, and Offset.
6761 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6762                                       SDValue SOffset,
6763                                       SDValue Offset,
6764                                       SDValue VIndex = SDValue()) {
6765 
6766   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6767       !isa<ConstantSDNode>(Offset))
6768     return 0;
6769 
6770   if (VIndex) {
6771     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6772       return 0;
6773   }
6774 
6775   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6776          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6777          cast<ConstantSDNode>(Offset)->getSExtValue();
6778 }
6779 
6780 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6781                                                      SelectionDAG &DAG,
6782                                                      unsigned NewOpcode) const {
6783   SDLoc DL(Op);
6784 
6785   SDValue VData = Op.getOperand(2);
6786   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6787   SDValue Ops[] = {
6788     Op.getOperand(0), // Chain
6789     VData,            // vdata
6790     Op.getOperand(3), // rsrc
6791     DAG.getConstant(0, DL, MVT::i32), // vindex
6792     Offsets.first,    // voffset
6793     Op.getOperand(5), // soffset
6794     Offsets.second,   // offset
6795     Op.getOperand(6), // cachepolicy
6796     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6797   };
6798 
6799   auto *M = cast<MemSDNode>(Op);
6800   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6801 
6802   EVT MemVT = VData.getValueType();
6803   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6804                                  M->getMemOperand());
6805 }
6806 
6807 SDValue
6808 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6809                                                 unsigned NewOpcode) const {
6810   SDLoc DL(Op);
6811 
6812   SDValue VData = Op.getOperand(2);
6813   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6814   SDValue Ops[] = {
6815     Op.getOperand(0), // Chain
6816     VData,            // vdata
6817     Op.getOperand(3), // rsrc
6818     Op.getOperand(4), // vindex
6819     Offsets.first,    // voffset
6820     Op.getOperand(6), // soffset
6821     Offsets.second,   // offset
6822     Op.getOperand(7), // cachepolicy
6823     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6824   };
6825 
6826   auto *M = cast<MemSDNode>(Op);
6827   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6828                                                       Ops[3]));
6829 
6830   EVT MemVT = VData.getValueType();
6831   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6832                                  M->getMemOperand());
6833 }
6834 
6835 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6836                                                  SelectionDAG &DAG) const {
6837   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6838   SDLoc DL(Op);
6839 
6840   switch (IntrID) {
6841   case Intrinsic::amdgcn_ds_ordered_add:
6842   case Intrinsic::amdgcn_ds_ordered_swap: {
6843     MemSDNode *M = cast<MemSDNode>(Op);
6844     SDValue Chain = M->getOperand(0);
6845     SDValue M0 = M->getOperand(2);
6846     SDValue Value = M->getOperand(3);
6847     unsigned IndexOperand = M->getConstantOperandVal(7);
6848     unsigned WaveRelease = M->getConstantOperandVal(8);
6849     unsigned WaveDone = M->getConstantOperandVal(9);
6850 
6851     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6852     IndexOperand &= ~0x3f;
6853     unsigned CountDw = 0;
6854 
6855     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6856       CountDw = (IndexOperand >> 24) & 0xf;
6857       IndexOperand &= ~(0xf << 24);
6858 
6859       if (CountDw < 1 || CountDw > 4) {
6860         report_fatal_error(
6861             "ds_ordered_count: dword count must be between 1 and 4");
6862       }
6863     }
6864 
6865     if (IndexOperand)
6866       report_fatal_error("ds_ordered_count: bad index operand");
6867 
6868     if (WaveDone && !WaveRelease)
6869       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6870 
6871     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6872     unsigned ShaderType =
6873         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6874     unsigned Offset0 = OrderedCountIndex << 2;
6875     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6876                        (Instruction << 4);
6877 
6878     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6879       Offset1 |= (CountDw - 1) << 6;
6880 
6881     unsigned Offset = Offset0 | (Offset1 << 8);
6882 
6883     SDValue Ops[] = {
6884       Chain,
6885       Value,
6886       DAG.getTargetConstant(Offset, DL, MVT::i16),
6887       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6888     };
6889     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6890                                    M->getVTList(), Ops, M->getMemoryVT(),
6891                                    M->getMemOperand());
6892   }
6893   case Intrinsic::amdgcn_ds_fadd: {
6894     MemSDNode *M = cast<MemSDNode>(Op);
6895     unsigned Opc;
6896     switch (IntrID) {
6897     case Intrinsic::amdgcn_ds_fadd:
6898       Opc = ISD::ATOMIC_LOAD_FADD;
6899       break;
6900     }
6901 
6902     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6903                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6904                          M->getMemOperand());
6905   }
6906   case Intrinsic::amdgcn_atomic_inc:
6907   case Intrinsic::amdgcn_atomic_dec:
6908   case Intrinsic::amdgcn_ds_fmin:
6909   case Intrinsic::amdgcn_ds_fmax: {
6910     MemSDNode *M = cast<MemSDNode>(Op);
6911     unsigned Opc;
6912     switch (IntrID) {
6913     case Intrinsic::amdgcn_atomic_inc:
6914       Opc = AMDGPUISD::ATOMIC_INC;
6915       break;
6916     case Intrinsic::amdgcn_atomic_dec:
6917       Opc = AMDGPUISD::ATOMIC_DEC;
6918       break;
6919     case Intrinsic::amdgcn_ds_fmin:
6920       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6921       break;
6922     case Intrinsic::amdgcn_ds_fmax:
6923       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6924       break;
6925     default:
6926       llvm_unreachable("Unknown intrinsic!");
6927     }
6928     SDValue Ops[] = {
6929       M->getOperand(0), // Chain
6930       M->getOperand(2), // Ptr
6931       M->getOperand(3)  // Value
6932     };
6933 
6934     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6935                                    M->getMemoryVT(), M->getMemOperand());
6936   }
6937   case Intrinsic::amdgcn_buffer_load:
6938   case Intrinsic::amdgcn_buffer_load_format: {
6939     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6940     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6941     unsigned IdxEn = 1;
6942     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6943       IdxEn = Idx->getZExtValue() != 0;
6944     SDValue Ops[] = {
6945       Op.getOperand(0), // Chain
6946       Op.getOperand(2), // rsrc
6947       Op.getOperand(3), // vindex
6948       SDValue(),        // voffset -- will be set by setBufferOffsets
6949       SDValue(),        // soffset -- will be set by setBufferOffsets
6950       SDValue(),        // offset -- will be set by setBufferOffsets
6951       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6952       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6953     };
6954 
6955     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6956     // We don't know the offset if vindex is non-zero, so clear it.
6957     if (IdxEn)
6958       Offset = 0;
6959 
6960     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6961         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6962 
6963     EVT VT = Op.getValueType();
6964     EVT IntVT = VT.changeTypeToInteger();
6965     auto *M = cast<MemSDNode>(Op);
6966     M->getMemOperand()->setOffset(Offset);
6967     EVT LoadVT = Op.getValueType();
6968 
6969     if (LoadVT.getScalarType() == MVT::f16)
6970       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6971                                  M, DAG, Ops);
6972 
6973     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6974     if (LoadVT.getScalarType() == MVT::i8 ||
6975         LoadVT.getScalarType() == MVT::i16)
6976       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6977 
6978     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6979                                M->getMemOperand(), DAG);
6980   }
6981   case Intrinsic::amdgcn_raw_buffer_load:
6982   case Intrinsic::amdgcn_raw_buffer_load_format: {
6983     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6984 
6985     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6986     SDValue Ops[] = {
6987       Op.getOperand(0), // Chain
6988       Op.getOperand(2), // rsrc
6989       DAG.getConstant(0, DL, MVT::i32), // vindex
6990       Offsets.first,    // voffset
6991       Op.getOperand(4), // soffset
6992       Offsets.second,   // offset
6993       Op.getOperand(5), // cachepolicy, swizzled buffer
6994       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6995     };
6996 
6997     auto *M = cast<MemSDNode>(Op);
6998     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6999     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7000   }
7001   case Intrinsic::amdgcn_struct_buffer_load:
7002   case Intrinsic::amdgcn_struct_buffer_load_format: {
7003     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7004 
7005     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7006     SDValue Ops[] = {
7007       Op.getOperand(0), // Chain
7008       Op.getOperand(2), // rsrc
7009       Op.getOperand(3), // vindex
7010       Offsets.first,    // voffset
7011       Op.getOperand(5), // soffset
7012       Offsets.second,   // offset
7013       Op.getOperand(6), // cachepolicy, swizzled buffer
7014       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7015     };
7016 
7017     auto *M = cast<MemSDNode>(Op);
7018     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
7019                                                         Ops[2]));
7020     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7021   }
7022   case Intrinsic::amdgcn_tbuffer_load: {
7023     MemSDNode *M = cast<MemSDNode>(Op);
7024     EVT LoadVT = Op.getValueType();
7025 
7026     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7027     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7028     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7029     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7030     unsigned IdxEn = 1;
7031     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7032       IdxEn = Idx->getZExtValue() != 0;
7033     SDValue Ops[] = {
7034       Op.getOperand(0),  // Chain
7035       Op.getOperand(2),  // rsrc
7036       Op.getOperand(3),  // vindex
7037       Op.getOperand(4),  // voffset
7038       Op.getOperand(5),  // soffset
7039       Op.getOperand(6),  // offset
7040       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7041       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7042       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7043     };
7044 
7045     if (LoadVT.getScalarType() == MVT::f16)
7046       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7047                                  M, DAG, Ops);
7048     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7049                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7050                                DAG);
7051   }
7052   case Intrinsic::amdgcn_raw_tbuffer_load: {
7053     MemSDNode *M = cast<MemSDNode>(Op);
7054     EVT LoadVT = Op.getValueType();
7055     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7056 
7057     SDValue Ops[] = {
7058       Op.getOperand(0),  // Chain
7059       Op.getOperand(2),  // rsrc
7060       DAG.getConstant(0, DL, MVT::i32), // vindex
7061       Offsets.first,     // voffset
7062       Op.getOperand(4),  // soffset
7063       Offsets.second,    // offset
7064       Op.getOperand(5),  // format
7065       Op.getOperand(6),  // cachepolicy, swizzled buffer
7066       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7067     };
7068 
7069     if (LoadVT.getScalarType() == MVT::f16)
7070       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7071                                  M, DAG, Ops);
7072     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7073                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7074                                DAG);
7075   }
7076   case Intrinsic::amdgcn_struct_tbuffer_load: {
7077     MemSDNode *M = cast<MemSDNode>(Op);
7078     EVT LoadVT = Op.getValueType();
7079     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7080 
7081     SDValue Ops[] = {
7082       Op.getOperand(0),  // Chain
7083       Op.getOperand(2),  // rsrc
7084       Op.getOperand(3),  // vindex
7085       Offsets.first,     // voffset
7086       Op.getOperand(5),  // soffset
7087       Offsets.second,    // offset
7088       Op.getOperand(6),  // format
7089       Op.getOperand(7),  // cachepolicy, swizzled buffer
7090       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7091     };
7092 
7093     if (LoadVT.getScalarType() == MVT::f16)
7094       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7095                                  M, DAG, Ops);
7096     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7097                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7098                                DAG);
7099   }
7100   case Intrinsic::amdgcn_buffer_atomic_swap:
7101   case Intrinsic::amdgcn_buffer_atomic_add:
7102   case Intrinsic::amdgcn_buffer_atomic_sub:
7103   case Intrinsic::amdgcn_buffer_atomic_csub:
7104   case Intrinsic::amdgcn_buffer_atomic_smin:
7105   case Intrinsic::amdgcn_buffer_atomic_umin:
7106   case Intrinsic::amdgcn_buffer_atomic_smax:
7107   case Intrinsic::amdgcn_buffer_atomic_umax:
7108   case Intrinsic::amdgcn_buffer_atomic_and:
7109   case Intrinsic::amdgcn_buffer_atomic_or:
7110   case Intrinsic::amdgcn_buffer_atomic_xor:
7111   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7112     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7113     unsigned IdxEn = 1;
7114     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7115       IdxEn = Idx->getZExtValue() != 0;
7116     SDValue Ops[] = {
7117       Op.getOperand(0), // Chain
7118       Op.getOperand(2), // vdata
7119       Op.getOperand(3), // rsrc
7120       Op.getOperand(4), // vindex
7121       SDValue(),        // voffset -- will be set by setBufferOffsets
7122       SDValue(),        // soffset -- will be set by setBufferOffsets
7123       SDValue(),        // offset -- will be set by setBufferOffsets
7124       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7125       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7126     };
7127     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7128     // We don't know the offset if vindex is non-zero, so clear it.
7129     if (IdxEn)
7130       Offset = 0;
7131     EVT VT = Op.getValueType();
7132 
7133     auto *M = cast<MemSDNode>(Op);
7134     M->getMemOperand()->setOffset(Offset);
7135     unsigned Opcode = 0;
7136 
7137     switch (IntrID) {
7138     case Intrinsic::amdgcn_buffer_atomic_swap:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7140       break;
7141     case Intrinsic::amdgcn_buffer_atomic_add:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7143       break;
7144     case Intrinsic::amdgcn_buffer_atomic_sub:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7146       break;
7147     case Intrinsic::amdgcn_buffer_atomic_csub:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7149       break;
7150     case Intrinsic::amdgcn_buffer_atomic_smin:
7151       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7152       break;
7153     case Intrinsic::amdgcn_buffer_atomic_umin:
7154       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7155       break;
7156     case Intrinsic::amdgcn_buffer_atomic_smax:
7157       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7158       break;
7159     case Intrinsic::amdgcn_buffer_atomic_umax:
7160       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7161       break;
7162     case Intrinsic::amdgcn_buffer_atomic_and:
7163       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7164       break;
7165     case Intrinsic::amdgcn_buffer_atomic_or:
7166       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7167       break;
7168     case Intrinsic::amdgcn_buffer_atomic_xor:
7169       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7170       break;
7171     case Intrinsic::amdgcn_buffer_atomic_fadd:
7172       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7173         DiagnosticInfoUnsupported
7174           NoFpRet(DAG.getMachineFunction().getFunction(),
7175                   "return versions of fp atomics not supported",
7176                   DL.getDebugLoc(), DS_Error);
7177         DAG.getContext()->diagnose(NoFpRet);
7178         return SDValue();
7179       }
7180       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7181       break;
7182     default:
7183       llvm_unreachable("unhandled atomic opcode");
7184     }
7185 
7186     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7187                                    M->getMemOperand());
7188   }
7189   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7190     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7191   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7192     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7193   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7194     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7195   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7196     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7197   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7198     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7199   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7200     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7201   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7202     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7203   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7204     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7205   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7206     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7207   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7208     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7209   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7210     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7211   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7212     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7213   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7214     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7215   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7216     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7217   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7218     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7219   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7220     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7221   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7222     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7223   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7224     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7225   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7226     return lowerStructBufferAtomicIntrin(Op, DAG,
7227                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7228   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7229     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7230   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7231     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7232   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7233     return lowerStructBufferAtomicIntrin(Op, DAG,
7234                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7235   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7236     return lowerStructBufferAtomicIntrin(Op, DAG,
7237                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7238   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7239     return lowerStructBufferAtomicIntrin(Op, DAG,
7240                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7241   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7242     return lowerStructBufferAtomicIntrin(Op, DAG,
7243                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7244   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7245     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7246   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7247     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7248   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7249     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7250   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7251     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7252   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7253     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7254 
7255   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7256     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7257     unsigned IdxEn = 1;
7258     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7259       IdxEn = Idx->getZExtValue() != 0;
7260     SDValue Ops[] = {
7261       Op.getOperand(0), // Chain
7262       Op.getOperand(2), // src
7263       Op.getOperand(3), // cmp
7264       Op.getOperand(4), // rsrc
7265       Op.getOperand(5), // vindex
7266       SDValue(),        // voffset -- will be set by setBufferOffsets
7267       SDValue(),        // soffset -- will be set by setBufferOffsets
7268       SDValue(),        // offset -- will be set by setBufferOffsets
7269       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7270       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7271     };
7272     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7273     // We don't know the offset if vindex is non-zero, so clear it.
7274     if (IdxEn)
7275       Offset = 0;
7276     EVT VT = Op.getValueType();
7277     auto *M = cast<MemSDNode>(Op);
7278     M->getMemOperand()->setOffset(Offset);
7279 
7280     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7281                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7282   }
7283   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7284     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7285     SDValue Ops[] = {
7286       Op.getOperand(0), // Chain
7287       Op.getOperand(2), // src
7288       Op.getOperand(3), // cmp
7289       Op.getOperand(4), // rsrc
7290       DAG.getConstant(0, DL, MVT::i32), // vindex
7291       Offsets.first,    // voffset
7292       Op.getOperand(6), // soffset
7293       Offsets.second,   // offset
7294       Op.getOperand(7), // cachepolicy
7295       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7296     };
7297     EVT VT = Op.getValueType();
7298     auto *M = cast<MemSDNode>(Op);
7299     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7300 
7301     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7302                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7303   }
7304   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7305     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7306     SDValue Ops[] = {
7307       Op.getOperand(0), // Chain
7308       Op.getOperand(2), // src
7309       Op.getOperand(3), // cmp
7310       Op.getOperand(4), // rsrc
7311       Op.getOperand(5), // vindex
7312       Offsets.first,    // voffset
7313       Op.getOperand(7), // soffset
7314       Offsets.second,   // offset
7315       Op.getOperand(8), // cachepolicy
7316       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7317     };
7318     EVT VT = Op.getValueType();
7319     auto *M = cast<MemSDNode>(Op);
7320     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7321                                                         Ops[4]));
7322 
7323     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7324                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7325   }
7326   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7327     SDLoc DL(Op);
7328     MemSDNode *M = cast<MemSDNode>(Op);
7329     SDValue NodePtr = M->getOperand(2);
7330     SDValue RayExtent = M->getOperand(3);
7331     SDValue RayOrigin = M->getOperand(4);
7332     SDValue RayDir = M->getOperand(5);
7333     SDValue RayInvDir = M->getOperand(6);
7334     SDValue TDescr = M->getOperand(7);
7335 
7336     assert(NodePtr.getValueType() == MVT::i32 ||
7337            NodePtr.getValueType() == MVT::i64);
7338     assert(RayDir.getValueType() == MVT::v4f16 ||
7339            RayDir.getValueType() == MVT::v4f32);
7340 
7341     if (!Subtarget->hasGFX10_AEncoding()) {
7342       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7343       return SDValue();
7344     }
7345 
7346     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7347     bool Is64 = NodePtr.getValueType() == MVT::i64;
7348     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7349                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7350                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7351                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7352 
7353     SmallVector<SDValue, 16> Ops;
7354 
7355     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7356       SmallVector<SDValue, 3> Lanes;
7357       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7358       if (Lanes[0].getValueSizeInBits() == 32) {
7359         for (unsigned I = 0; I < 3; ++I)
7360           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7361       } else {
7362         if (IsAligned) {
7363           Ops.push_back(
7364             DAG.getBitcast(MVT::i32,
7365                            DAG.getBuildVector(MVT::v2f16, DL,
7366                                               { Lanes[0], Lanes[1] })));
7367           Ops.push_back(Lanes[2]);
7368         } else {
7369           SDValue Elt0 = Ops.pop_back_val();
7370           Ops.push_back(
7371             DAG.getBitcast(MVT::i32,
7372                            DAG.getBuildVector(MVT::v2f16, DL,
7373                                               { Elt0, Lanes[0] })));
7374           Ops.push_back(
7375             DAG.getBitcast(MVT::i32,
7376                            DAG.getBuildVector(MVT::v2f16, DL,
7377                                               { Lanes[1], Lanes[2] })));
7378         }
7379       }
7380     };
7381 
7382     if (Is64)
7383       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7384     else
7385       Ops.push_back(NodePtr);
7386 
7387     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7388     packLanes(RayOrigin, true);
7389     packLanes(RayDir, true);
7390     packLanes(RayInvDir, false);
7391     Ops.push_back(TDescr);
7392     if (IsA16)
7393       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7394     Ops.push_back(M->getChain());
7395 
7396     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7397     MachineMemOperand *MemRef = M->getMemOperand();
7398     DAG.setNodeMemRefs(NewNode, {MemRef});
7399     return SDValue(NewNode, 0);
7400   }
7401   case Intrinsic::amdgcn_global_atomic_fadd:
7402     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7403       DiagnosticInfoUnsupported
7404         NoFpRet(DAG.getMachineFunction().getFunction(),
7405                 "return versions of fp atomics not supported",
7406                 DL.getDebugLoc(), DS_Error);
7407       DAG.getContext()->diagnose(NoFpRet);
7408       return SDValue();
7409     }
7410     LLVM_FALLTHROUGH;
7411   case Intrinsic::amdgcn_global_atomic_fmin:
7412   case Intrinsic::amdgcn_global_atomic_fmax:
7413   case Intrinsic::amdgcn_flat_atomic_fadd:
7414   case Intrinsic::amdgcn_flat_atomic_fmin:
7415   case Intrinsic::amdgcn_flat_atomic_fmax: {
7416     MemSDNode *M = cast<MemSDNode>(Op);
7417     SDValue Ops[] = {
7418       M->getOperand(0), // Chain
7419       M->getOperand(2), // Ptr
7420       M->getOperand(3)  // Value
7421     };
7422     unsigned Opcode = 0;
7423     switch (IntrID) {
7424     case Intrinsic::amdgcn_global_atomic_fadd:
7425     case Intrinsic::amdgcn_flat_atomic_fadd: {
7426       EVT VT = Op.getOperand(3).getValueType();
7427       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7428                            DAG.getVTList(VT, MVT::Other), Ops,
7429                            M->getMemOperand());
7430     }
7431     case Intrinsic::amdgcn_global_atomic_fmin:
7432     case Intrinsic::amdgcn_flat_atomic_fmin: {
7433       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7434       break;
7435     }
7436     case Intrinsic::amdgcn_global_atomic_fmax:
7437     case Intrinsic::amdgcn_flat_atomic_fmax: {
7438       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7439       break;
7440     }
7441     default:
7442       llvm_unreachable("unhandled atomic opcode");
7443     }
7444     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7445                                    M->getVTList(), Ops, M->getMemoryVT(),
7446                                    M->getMemOperand());
7447   }
7448   default:
7449 
7450     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7451             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7452       return lowerImage(Op, ImageDimIntr, DAG, true);
7453 
7454     return SDValue();
7455   }
7456 }
7457 
7458 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7459 // dwordx4 if on SI.
7460 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7461                                               SDVTList VTList,
7462                                               ArrayRef<SDValue> Ops, EVT MemVT,
7463                                               MachineMemOperand *MMO,
7464                                               SelectionDAG &DAG) const {
7465   EVT VT = VTList.VTs[0];
7466   EVT WidenedVT = VT;
7467   EVT WidenedMemVT = MemVT;
7468   if (!Subtarget->hasDwordx3LoadStores() &&
7469       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7470     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7471                                  WidenedVT.getVectorElementType(), 4);
7472     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7473                                     WidenedMemVT.getVectorElementType(), 4);
7474     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7475   }
7476 
7477   assert(VTList.NumVTs == 2);
7478   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7479 
7480   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7481                                        WidenedMemVT, MMO);
7482   if (WidenedVT != VT) {
7483     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7484                                DAG.getVectorIdxConstant(0, DL));
7485     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7486   }
7487   return NewOp;
7488 }
7489 
7490 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7491                                          bool ImageStore) const {
7492   EVT StoreVT = VData.getValueType();
7493 
7494   // No change for f16 and legal vector D16 types.
7495   if (!StoreVT.isVector())
7496     return VData;
7497 
7498   SDLoc DL(VData);
7499   unsigned NumElements = StoreVT.getVectorNumElements();
7500 
7501   if (Subtarget->hasUnpackedD16VMem()) {
7502     // We need to unpack the packed data to store.
7503     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7504     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7505 
7506     EVT EquivStoreVT =
7507         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7508     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7509     return DAG.UnrollVectorOp(ZExt.getNode());
7510   }
7511 
7512   // The sq block of gfx8.1 does not estimate register use correctly for d16
7513   // image store instructions. The data operand is computed as if it were not a
7514   // d16 image instruction.
7515   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7516     // Bitcast to i16
7517     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7518     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7519 
7520     // Decompose into scalars
7521     SmallVector<SDValue, 4> Elts;
7522     DAG.ExtractVectorElements(IntVData, Elts);
7523 
7524     // Group pairs of i16 into v2i16 and bitcast to i32
7525     SmallVector<SDValue, 4> PackedElts;
7526     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7527       SDValue Pair =
7528           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7529       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7530       PackedElts.push_back(IntPair);
7531     }
7532     if ((NumElements % 2) == 1) {
7533       // Handle v3i16
7534       unsigned I = Elts.size() / 2;
7535       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7536                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7537       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7538       PackedElts.push_back(IntPair);
7539     }
7540 
7541     // Pad using UNDEF
7542     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7543 
7544     // Build final vector
7545     EVT VecVT =
7546         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7547     return DAG.getBuildVector(VecVT, DL, PackedElts);
7548   }
7549 
7550   if (NumElements == 3) {
7551     EVT IntStoreVT =
7552         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7553     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7554 
7555     EVT WidenedStoreVT = EVT::getVectorVT(
7556         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7557     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7558                                          WidenedStoreVT.getStoreSizeInBits());
7559     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7560     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7561   }
7562 
7563   assert(isTypeLegal(StoreVT));
7564   return VData;
7565 }
7566 
7567 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7568                                               SelectionDAG &DAG) const {
7569   SDLoc DL(Op);
7570   SDValue Chain = Op.getOperand(0);
7571   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7572   MachineFunction &MF = DAG.getMachineFunction();
7573 
7574   switch (IntrinsicID) {
7575   case Intrinsic::amdgcn_exp_compr: {
7576     SDValue Src0 = Op.getOperand(4);
7577     SDValue Src1 = Op.getOperand(5);
7578     // Hack around illegal type on SI by directly selecting it.
7579     if (isTypeLegal(Src0.getValueType()))
7580       return SDValue();
7581 
7582     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7583     SDValue Undef = DAG.getUNDEF(MVT::f32);
7584     const SDValue Ops[] = {
7585       Op.getOperand(2), // tgt
7586       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7587       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7588       Undef, // src2
7589       Undef, // src3
7590       Op.getOperand(7), // vm
7591       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7592       Op.getOperand(3), // en
7593       Op.getOperand(0) // Chain
7594     };
7595 
7596     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7597     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7598   }
7599   case Intrinsic::amdgcn_s_barrier: {
7600     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7601       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7602       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7603       if (WGSize <= ST.getWavefrontSize())
7604         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7605                                           Op.getOperand(0)), 0);
7606     }
7607     return SDValue();
7608   };
7609   case Intrinsic::amdgcn_tbuffer_store: {
7610     SDValue VData = Op.getOperand(2);
7611     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7612     if (IsD16)
7613       VData = handleD16VData(VData, DAG);
7614     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7615     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7616     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7617     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7618     unsigned IdxEn = 1;
7619     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7620       IdxEn = Idx->getZExtValue() != 0;
7621     SDValue Ops[] = {
7622       Chain,
7623       VData,             // vdata
7624       Op.getOperand(3),  // rsrc
7625       Op.getOperand(4),  // vindex
7626       Op.getOperand(5),  // voffset
7627       Op.getOperand(6),  // soffset
7628       Op.getOperand(7),  // offset
7629       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7630       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7631       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7632     };
7633     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7634                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7635     MemSDNode *M = cast<MemSDNode>(Op);
7636     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7637                                    M->getMemoryVT(), M->getMemOperand());
7638   }
7639 
7640   case Intrinsic::amdgcn_struct_tbuffer_store: {
7641     SDValue VData = Op.getOperand(2);
7642     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7643     if (IsD16)
7644       VData = handleD16VData(VData, DAG);
7645     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7646     SDValue Ops[] = {
7647       Chain,
7648       VData,             // vdata
7649       Op.getOperand(3),  // rsrc
7650       Op.getOperand(4),  // vindex
7651       Offsets.first,     // voffset
7652       Op.getOperand(6),  // soffset
7653       Offsets.second,    // offset
7654       Op.getOperand(7),  // format
7655       Op.getOperand(8),  // cachepolicy, swizzled buffer
7656       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7657     };
7658     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7659                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7660     MemSDNode *M = cast<MemSDNode>(Op);
7661     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7662                                    M->getMemoryVT(), M->getMemOperand());
7663   }
7664 
7665   case Intrinsic::amdgcn_raw_tbuffer_store: {
7666     SDValue VData = Op.getOperand(2);
7667     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7668     if (IsD16)
7669       VData = handleD16VData(VData, DAG);
7670     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7671     SDValue Ops[] = {
7672       Chain,
7673       VData,             // vdata
7674       Op.getOperand(3),  // rsrc
7675       DAG.getConstant(0, DL, MVT::i32), // vindex
7676       Offsets.first,     // voffset
7677       Op.getOperand(5),  // soffset
7678       Offsets.second,    // offset
7679       Op.getOperand(6),  // format
7680       Op.getOperand(7),  // cachepolicy, swizzled buffer
7681       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7682     };
7683     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7684                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7685     MemSDNode *M = cast<MemSDNode>(Op);
7686     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7687                                    M->getMemoryVT(), M->getMemOperand());
7688   }
7689 
7690   case Intrinsic::amdgcn_buffer_store:
7691   case Intrinsic::amdgcn_buffer_store_format: {
7692     SDValue VData = Op.getOperand(2);
7693     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7694     if (IsD16)
7695       VData = handleD16VData(VData, DAG);
7696     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7697     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7698     unsigned IdxEn = 1;
7699     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7700       IdxEn = Idx->getZExtValue() != 0;
7701     SDValue Ops[] = {
7702       Chain,
7703       VData,
7704       Op.getOperand(3), // rsrc
7705       Op.getOperand(4), // vindex
7706       SDValue(), // voffset -- will be set by setBufferOffsets
7707       SDValue(), // soffset -- will be set by setBufferOffsets
7708       SDValue(), // offset -- will be set by setBufferOffsets
7709       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7710       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7711     };
7712     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7713     // We don't know the offset if vindex is non-zero, so clear it.
7714     if (IdxEn)
7715       Offset = 0;
7716     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7717                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7718     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7719     MemSDNode *M = cast<MemSDNode>(Op);
7720     M->getMemOperand()->setOffset(Offset);
7721 
7722     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7723     EVT VDataType = VData.getValueType().getScalarType();
7724     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7725       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7726 
7727     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7728                                    M->getMemoryVT(), M->getMemOperand());
7729   }
7730 
7731   case Intrinsic::amdgcn_raw_buffer_store:
7732   case Intrinsic::amdgcn_raw_buffer_store_format: {
7733     const bool IsFormat =
7734         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7735 
7736     SDValue VData = Op.getOperand(2);
7737     EVT VDataVT = VData.getValueType();
7738     EVT EltType = VDataVT.getScalarType();
7739     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7740     if (IsD16) {
7741       VData = handleD16VData(VData, DAG);
7742       VDataVT = VData.getValueType();
7743     }
7744 
7745     if (!isTypeLegal(VDataVT)) {
7746       VData =
7747           DAG.getNode(ISD::BITCAST, DL,
7748                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7749     }
7750 
7751     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7752     SDValue Ops[] = {
7753       Chain,
7754       VData,
7755       Op.getOperand(3), // rsrc
7756       DAG.getConstant(0, DL, MVT::i32), // vindex
7757       Offsets.first,    // voffset
7758       Op.getOperand(5), // soffset
7759       Offsets.second,   // offset
7760       Op.getOperand(6), // cachepolicy, swizzled buffer
7761       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7762     };
7763     unsigned Opc =
7764         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7765     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7766     MemSDNode *M = cast<MemSDNode>(Op);
7767     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7768 
7769     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7770     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7771       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7772 
7773     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7774                                    M->getMemoryVT(), M->getMemOperand());
7775   }
7776 
7777   case Intrinsic::amdgcn_struct_buffer_store:
7778   case Intrinsic::amdgcn_struct_buffer_store_format: {
7779     const bool IsFormat =
7780         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7781 
7782     SDValue VData = Op.getOperand(2);
7783     EVT VDataVT = VData.getValueType();
7784     EVT EltType = VDataVT.getScalarType();
7785     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7786 
7787     if (IsD16) {
7788       VData = handleD16VData(VData, DAG);
7789       VDataVT = VData.getValueType();
7790     }
7791 
7792     if (!isTypeLegal(VDataVT)) {
7793       VData =
7794           DAG.getNode(ISD::BITCAST, DL,
7795                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7796     }
7797 
7798     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7799     SDValue Ops[] = {
7800       Chain,
7801       VData,
7802       Op.getOperand(3), // rsrc
7803       Op.getOperand(4), // vindex
7804       Offsets.first,    // voffset
7805       Op.getOperand(6), // soffset
7806       Offsets.second,   // offset
7807       Op.getOperand(7), // cachepolicy, swizzled buffer
7808       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7809     };
7810     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7811                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7812     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7813     MemSDNode *M = cast<MemSDNode>(Op);
7814     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7815                                                         Ops[3]));
7816 
7817     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7818     EVT VDataType = VData.getValueType().getScalarType();
7819     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7820       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7821 
7822     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7823                                    M->getMemoryVT(), M->getMemOperand());
7824   }
7825   case Intrinsic::amdgcn_end_cf:
7826     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7827                                       Op->getOperand(2), Chain), 0);
7828 
7829   default: {
7830     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7831             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7832       return lowerImage(Op, ImageDimIntr, DAG, true);
7833 
7834     return Op;
7835   }
7836   }
7837 }
7838 
7839 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7840 // offset (the offset that is included in bounds checking and swizzling, to be
7841 // split between the instruction's voffset and immoffset fields) and soffset
7842 // (the offset that is excluded from bounds checking and swizzling, to go in
7843 // the instruction's soffset field).  This function takes the first kind of
7844 // offset and figures out how to split it between voffset and immoffset.
7845 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7846     SDValue Offset, SelectionDAG &DAG) const {
7847   SDLoc DL(Offset);
7848   const unsigned MaxImm = 4095;
7849   SDValue N0 = Offset;
7850   ConstantSDNode *C1 = nullptr;
7851 
7852   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7853     N0 = SDValue();
7854   else if (DAG.isBaseWithConstantOffset(N0)) {
7855     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7856     N0 = N0.getOperand(0);
7857   }
7858 
7859   if (C1) {
7860     unsigned ImmOffset = C1->getZExtValue();
7861     // If the immediate value is too big for the immoffset field, put the value
7862     // and -4096 into the immoffset field so that the value that is copied/added
7863     // for the voffset field is a multiple of 4096, and it stands more chance
7864     // of being CSEd with the copy/add for another similar load/store.
7865     // However, do not do that rounding down to a multiple of 4096 if that is a
7866     // negative number, as it appears to be illegal to have a negative offset
7867     // in the vgpr, even if adding the immediate offset makes it positive.
7868     unsigned Overflow = ImmOffset & ~MaxImm;
7869     ImmOffset -= Overflow;
7870     if ((int32_t)Overflow < 0) {
7871       Overflow += ImmOffset;
7872       ImmOffset = 0;
7873     }
7874     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7875     if (Overflow) {
7876       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7877       if (!N0)
7878         N0 = OverflowVal;
7879       else {
7880         SDValue Ops[] = { N0, OverflowVal };
7881         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7882       }
7883     }
7884   }
7885   if (!N0)
7886     N0 = DAG.getConstant(0, DL, MVT::i32);
7887   if (!C1)
7888     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7889   return {N0, SDValue(C1, 0)};
7890 }
7891 
7892 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7893 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7894 // pointed to by Offsets.
7895 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7896                                             SelectionDAG &DAG, SDValue *Offsets,
7897                                             Align Alignment) const {
7898   SDLoc DL(CombinedOffset);
7899   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7900     uint32_t Imm = C->getZExtValue();
7901     uint32_t SOffset, ImmOffset;
7902     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7903                                  Alignment)) {
7904       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7905       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7906       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7907       return SOffset + ImmOffset;
7908     }
7909   }
7910   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7911     SDValue N0 = CombinedOffset.getOperand(0);
7912     SDValue N1 = CombinedOffset.getOperand(1);
7913     uint32_t SOffset, ImmOffset;
7914     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7915     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7916                                                 Subtarget, Alignment)) {
7917       Offsets[0] = N0;
7918       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7919       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7920       return 0;
7921     }
7922   }
7923   Offsets[0] = CombinedOffset;
7924   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7925   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7926   return 0;
7927 }
7928 
7929 // Handle 8 bit and 16 bit buffer loads
7930 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7931                                                      EVT LoadVT, SDLoc DL,
7932                                                      ArrayRef<SDValue> Ops,
7933                                                      MemSDNode *M) const {
7934   EVT IntVT = LoadVT.changeTypeToInteger();
7935   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7936          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7937 
7938   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7939   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7940                                                Ops, IntVT,
7941                                                M->getMemOperand());
7942   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7943   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7944 
7945   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7946 }
7947 
7948 // Handle 8 bit and 16 bit buffer stores
7949 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7950                                                       EVT VDataType, SDLoc DL,
7951                                                       SDValue Ops[],
7952                                                       MemSDNode *M) const {
7953   if (VDataType == MVT::f16)
7954     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7955 
7956   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7957   Ops[1] = BufferStoreExt;
7958   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7959                                  AMDGPUISD::BUFFER_STORE_SHORT;
7960   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7961   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7962                                      M->getMemOperand());
7963 }
7964 
7965 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7966                                  ISD::LoadExtType ExtType, SDValue Op,
7967                                  const SDLoc &SL, EVT VT) {
7968   if (VT.bitsLT(Op.getValueType()))
7969     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7970 
7971   switch (ExtType) {
7972   case ISD::SEXTLOAD:
7973     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7974   case ISD::ZEXTLOAD:
7975     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7976   case ISD::EXTLOAD:
7977     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7978   case ISD::NON_EXTLOAD:
7979     return Op;
7980   }
7981 
7982   llvm_unreachable("invalid ext type");
7983 }
7984 
7985 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7986   SelectionDAG &DAG = DCI.DAG;
7987   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7988     return SDValue();
7989 
7990   // FIXME: Constant loads should all be marked invariant.
7991   unsigned AS = Ld->getAddressSpace();
7992   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7993       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7994       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7995     return SDValue();
7996 
7997   // Don't do this early, since it may interfere with adjacent load merging for
7998   // illegal types. We can avoid losing alignment information for exotic types
7999   // pre-legalize.
8000   EVT MemVT = Ld->getMemoryVT();
8001   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8002       MemVT.getSizeInBits() >= 32)
8003     return SDValue();
8004 
8005   SDLoc SL(Ld);
8006 
8007   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8008          "unexpected vector extload");
8009 
8010   // TODO: Drop only high part of range.
8011   SDValue Ptr = Ld->getBasePtr();
8012   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8013                                 MVT::i32, SL, Ld->getChain(), Ptr,
8014                                 Ld->getOffset(),
8015                                 Ld->getPointerInfo(), MVT::i32,
8016                                 Ld->getAlignment(),
8017                                 Ld->getMemOperand()->getFlags(),
8018                                 Ld->getAAInfo(),
8019                                 nullptr); // Drop ranges
8020 
8021   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8022   if (MemVT.isFloatingPoint()) {
8023     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8024            "unexpected fp extload");
8025     TruncVT = MemVT.changeTypeToInteger();
8026   }
8027 
8028   SDValue Cvt = NewLoad;
8029   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8030     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8031                       DAG.getValueType(TruncVT));
8032   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8033              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8034     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8035   } else {
8036     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8037   }
8038 
8039   EVT VT = Ld->getValueType(0);
8040   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8041 
8042   DCI.AddToWorklist(Cvt.getNode());
8043 
8044   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8045   // the appropriate extension from the 32-bit load.
8046   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8047   DCI.AddToWorklist(Cvt.getNode());
8048 
8049   // Handle conversion back to floating point if necessary.
8050   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8051 
8052   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8053 }
8054 
8055 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8056   SDLoc DL(Op);
8057   LoadSDNode *Load = cast<LoadSDNode>(Op);
8058   ISD::LoadExtType ExtType = Load->getExtensionType();
8059   EVT MemVT = Load->getMemoryVT();
8060 
8061   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8062     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8063       return SDValue();
8064 
8065     // FIXME: Copied from PPC
8066     // First, load into 32 bits, then truncate to 1 bit.
8067 
8068     SDValue Chain = Load->getChain();
8069     SDValue BasePtr = Load->getBasePtr();
8070     MachineMemOperand *MMO = Load->getMemOperand();
8071 
8072     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8073 
8074     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8075                                    BasePtr, RealMemVT, MMO);
8076 
8077     if (!MemVT.isVector()) {
8078       SDValue Ops[] = {
8079         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8080         NewLD.getValue(1)
8081       };
8082 
8083       return DAG.getMergeValues(Ops, DL);
8084     }
8085 
8086     SmallVector<SDValue, 3> Elts;
8087     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8088       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8089                                 DAG.getConstant(I, DL, MVT::i32));
8090 
8091       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8092     }
8093 
8094     SDValue Ops[] = {
8095       DAG.getBuildVector(MemVT, DL, Elts),
8096       NewLD.getValue(1)
8097     };
8098 
8099     return DAG.getMergeValues(Ops, DL);
8100   }
8101 
8102   if (!MemVT.isVector())
8103     return SDValue();
8104 
8105   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8106          "Custom lowering for non-i32 vectors hasn't been implemented.");
8107 
8108   unsigned Alignment = Load->getAlignment();
8109   unsigned AS = Load->getAddressSpace();
8110   if (Subtarget->hasLDSMisalignedBug() &&
8111       AS == AMDGPUAS::FLAT_ADDRESS &&
8112       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8113     return SplitVectorLoad(Op, DAG);
8114   }
8115 
8116   MachineFunction &MF = DAG.getMachineFunction();
8117   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8118   // If there is a possibilty that flat instruction access scratch memory
8119   // then we need to use the same legalization rules we use for private.
8120   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8121       !Subtarget->hasMultiDwordFlatScratchAddressing())
8122     AS = MFI->hasFlatScratchInit() ?
8123          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8124 
8125   unsigned NumElements = MemVT.getVectorNumElements();
8126 
8127   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8128       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8129     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8130       if (MemVT.isPow2VectorType())
8131         return SDValue();
8132       return WidenOrSplitVectorLoad(Op, DAG);
8133     }
8134     // Non-uniform loads will be selected to MUBUF instructions, so they
8135     // have the same legalization requirements as global and private
8136     // loads.
8137     //
8138   }
8139 
8140   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8141       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8142       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8143     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8144         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8145         Alignment >= 4 && NumElements < 32) {
8146       if (MemVT.isPow2VectorType())
8147         return SDValue();
8148       return WidenOrSplitVectorLoad(Op, DAG);
8149     }
8150     // Non-uniform loads will be selected to MUBUF instructions, so they
8151     // have the same legalization requirements as global and private
8152     // loads.
8153     //
8154   }
8155   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8156       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8157       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8158       AS == AMDGPUAS::FLAT_ADDRESS) {
8159     if (NumElements > 4)
8160       return SplitVectorLoad(Op, DAG);
8161     // v3 loads not supported on SI.
8162     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8163       return WidenOrSplitVectorLoad(Op, DAG);
8164 
8165     // v3 and v4 loads are supported for private and global memory.
8166     return SDValue();
8167   }
8168   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8169     // Depending on the setting of the private_element_size field in the
8170     // resource descriptor, we can only make private accesses up to a certain
8171     // size.
8172     switch (Subtarget->getMaxPrivateElementSize()) {
8173     case 4: {
8174       SDValue Ops[2];
8175       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8176       return DAG.getMergeValues(Ops, DL);
8177     }
8178     case 8:
8179       if (NumElements > 2)
8180         return SplitVectorLoad(Op, DAG);
8181       return SDValue();
8182     case 16:
8183       // Same as global/flat
8184       if (NumElements > 4)
8185         return SplitVectorLoad(Op, DAG);
8186       // v3 loads not supported on SI.
8187       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8188         return WidenOrSplitVectorLoad(Op, DAG);
8189 
8190       return SDValue();
8191     default:
8192       llvm_unreachable("unsupported private_element_size");
8193     }
8194   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8195     // Use ds_read_b128 or ds_read_b96 when possible.
8196     if (Subtarget->hasDS96AndDS128() &&
8197         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8198          MemVT.getStoreSize() == 12) &&
8199         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8200                                            Load->getAlign()))
8201       return SDValue();
8202 
8203     if (NumElements > 2)
8204       return SplitVectorLoad(Op, DAG);
8205 
8206     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8207     // address is negative, then the instruction is incorrectly treated as
8208     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8209     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8210     // load later in the SILoadStoreOptimizer.
8211     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8212         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8213         Load->getAlignment() < 8) {
8214       return SplitVectorLoad(Op, DAG);
8215     }
8216   }
8217 
8218   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8219                                       MemVT, *Load->getMemOperand())) {
8220     SDValue Ops[2];
8221     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8222     return DAG.getMergeValues(Ops, DL);
8223   }
8224 
8225   return SDValue();
8226 }
8227 
8228 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8229   EVT VT = Op.getValueType();
8230   assert(VT.getSizeInBits() == 64);
8231 
8232   SDLoc DL(Op);
8233   SDValue Cond = Op.getOperand(0);
8234 
8235   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8236   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8237 
8238   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8239   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8240 
8241   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8242   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8243 
8244   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8245 
8246   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8247   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8248 
8249   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8250 
8251   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8252   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8253 }
8254 
8255 // Catch division cases where we can use shortcuts with rcp and rsq
8256 // instructions.
8257 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8258                                               SelectionDAG &DAG) const {
8259   SDLoc SL(Op);
8260   SDValue LHS = Op.getOperand(0);
8261   SDValue RHS = Op.getOperand(1);
8262   EVT VT = Op.getValueType();
8263   const SDNodeFlags Flags = Op->getFlags();
8264 
8265   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8266 
8267   // Without !fpmath accuracy information, we can't do more because we don't
8268   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8269   if (!AllowInaccurateRcp)
8270     return SDValue();
8271 
8272   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8273     if (CLHS->isExactlyValue(1.0)) {
8274       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8275       // the CI documentation has a worst case error of 1 ulp.
8276       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8277       // use it as long as we aren't trying to use denormals.
8278       //
8279       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8280 
8281       // 1.0 / sqrt(x) -> rsq(x)
8282 
8283       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8284       // error seems really high at 2^29 ULP.
8285       if (RHS.getOpcode() == ISD::FSQRT)
8286         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8287 
8288       // 1.0 / x -> rcp(x)
8289       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8290     }
8291 
8292     // Same as for 1.0, but expand the sign out of the constant.
8293     if (CLHS->isExactlyValue(-1.0)) {
8294       // -1.0 / x -> rcp (fneg x)
8295       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8296       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8297     }
8298   }
8299 
8300   // Turn into multiply by the reciprocal.
8301   // x / y -> x * (1.0 / y)
8302   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8303   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8304 }
8305 
8306 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8307                                                 SelectionDAG &DAG) const {
8308   SDLoc SL(Op);
8309   SDValue X = Op.getOperand(0);
8310   SDValue Y = Op.getOperand(1);
8311   EVT VT = Op.getValueType();
8312   const SDNodeFlags Flags = Op->getFlags();
8313 
8314   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8315                             DAG.getTarget().Options.UnsafeFPMath;
8316   if (!AllowInaccurateDiv)
8317     return SDValue();
8318 
8319   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8320   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8321 
8322   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8323   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8324 
8325   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8326   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8327   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8328   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8329   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8330   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8331 }
8332 
8333 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8334                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8335                           SDNodeFlags Flags) {
8336   if (GlueChain->getNumValues() <= 1) {
8337     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8338   }
8339 
8340   assert(GlueChain->getNumValues() == 3);
8341 
8342   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8343   switch (Opcode) {
8344   default: llvm_unreachable("no chain equivalent for opcode");
8345   case ISD::FMUL:
8346     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8347     break;
8348   }
8349 
8350   return DAG.getNode(Opcode, SL, VTList,
8351                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8352                      Flags);
8353 }
8354 
8355 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8356                            EVT VT, SDValue A, SDValue B, SDValue C,
8357                            SDValue GlueChain, SDNodeFlags Flags) {
8358   if (GlueChain->getNumValues() <= 1) {
8359     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8360   }
8361 
8362   assert(GlueChain->getNumValues() == 3);
8363 
8364   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8365   switch (Opcode) {
8366   default: llvm_unreachable("no chain equivalent for opcode");
8367   case ISD::FMA:
8368     Opcode = AMDGPUISD::FMA_W_CHAIN;
8369     break;
8370   }
8371 
8372   return DAG.getNode(Opcode, SL, VTList,
8373                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8374                      Flags);
8375 }
8376 
8377 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8378   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8379     return FastLowered;
8380 
8381   SDLoc SL(Op);
8382   SDValue Src0 = Op.getOperand(0);
8383   SDValue Src1 = Op.getOperand(1);
8384 
8385   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8386   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8387 
8388   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8389   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8390 
8391   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8392   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8393 
8394   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8395 }
8396 
8397 // Faster 2.5 ULP division that does not support denormals.
8398 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8399   SDLoc SL(Op);
8400   SDValue LHS = Op.getOperand(1);
8401   SDValue RHS = Op.getOperand(2);
8402 
8403   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8404 
8405   const APFloat K0Val(BitsToFloat(0x6f800000));
8406   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8407 
8408   const APFloat K1Val(BitsToFloat(0x2f800000));
8409   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8410 
8411   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8412 
8413   EVT SetCCVT =
8414     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8415 
8416   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8417 
8418   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8419 
8420   // TODO: Should this propagate fast-math-flags?
8421   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8422 
8423   // rcp does not support denormals.
8424   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8425 
8426   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8427 
8428   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8429 }
8430 
8431 // Returns immediate value for setting the F32 denorm mode when using the
8432 // S_DENORM_MODE instruction.
8433 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8434                                     const SDLoc &SL, const GCNSubtarget *ST) {
8435   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8436   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8437                                 ? FP_DENORM_FLUSH_NONE
8438                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8439 
8440   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8441   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8442 }
8443 
8444 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8445   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8446     return FastLowered;
8447 
8448   // The selection matcher assumes anything with a chain selecting to a
8449   // mayRaiseFPException machine instruction. Since we're introducing a chain
8450   // here, we need to explicitly report nofpexcept for the regular fdiv
8451   // lowering.
8452   SDNodeFlags Flags = Op->getFlags();
8453   Flags.setNoFPExcept(true);
8454 
8455   SDLoc SL(Op);
8456   SDValue LHS = Op.getOperand(0);
8457   SDValue RHS = Op.getOperand(1);
8458 
8459   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8460 
8461   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8462 
8463   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8464                                           {RHS, RHS, LHS}, Flags);
8465   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8466                                         {LHS, RHS, LHS}, Flags);
8467 
8468   // Denominator is scaled to not be denormal, so using rcp is ok.
8469   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8470                                   DenominatorScaled, Flags);
8471   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8472                                      DenominatorScaled, Flags);
8473 
8474   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8475                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8476                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8477   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8478 
8479   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8480 
8481   if (!HasFP32Denormals) {
8482     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8483     // lowering. The chain dependence is insufficient, and we need glue. We do
8484     // not need the glue variants in a strictfp function.
8485 
8486     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8487 
8488     SDNode *EnableDenorm;
8489     if (Subtarget->hasDenormModeInst()) {
8490       const SDValue EnableDenormValue =
8491           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8492 
8493       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8494                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8495     } else {
8496       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8497                                                         SL, MVT::i32);
8498       EnableDenorm =
8499           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8500                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8501     }
8502 
8503     SDValue Ops[3] = {
8504       NegDivScale0,
8505       SDValue(EnableDenorm, 0),
8506       SDValue(EnableDenorm, 1)
8507     };
8508 
8509     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8510   }
8511 
8512   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8513                              ApproxRcp, One, NegDivScale0, Flags);
8514 
8515   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8516                              ApproxRcp, Fma0, Flags);
8517 
8518   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8519                            Fma1, Fma1, Flags);
8520 
8521   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8522                              NumeratorScaled, Mul, Flags);
8523 
8524   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8525                              Fma2, Fma1, Mul, Fma2, Flags);
8526 
8527   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8528                              NumeratorScaled, Fma3, Flags);
8529 
8530   if (!HasFP32Denormals) {
8531     SDNode *DisableDenorm;
8532     if (Subtarget->hasDenormModeInst()) {
8533       const SDValue DisableDenormValue =
8534           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8535 
8536       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8537                                   Fma4.getValue(1), DisableDenormValue,
8538                                   Fma4.getValue(2)).getNode();
8539     } else {
8540       const SDValue DisableDenormValue =
8541           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8542 
8543       DisableDenorm = DAG.getMachineNode(
8544           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8545           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8546     }
8547 
8548     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8549                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8550     DAG.setRoot(OutputChain);
8551   }
8552 
8553   SDValue Scale = NumeratorScaled.getValue(1);
8554   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8555                              {Fma4, Fma1, Fma3, Scale}, Flags);
8556 
8557   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8558 }
8559 
8560 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8561   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8562     return FastLowered;
8563 
8564   SDLoc SL(Op);
8565   SDValue X = Op.getOperand(0);
8566   SDValue Y = Op.getOperand(1);
8567 
8568   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8569 
8570   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8571 
8572   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8573 
8574   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8575 
8576   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8577 
8578   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8579 
8580   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8581 
8582   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8583 
8584   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8585 
8586   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8587   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8588 
8589   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8590                              NegDivScale0, Mul, DivScale1);
8591 
8592   SDValue Scale;
8593 
8594   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8595     // Workaround a hardware bug on SI where the condition output from div_scale
8596     // is not usable.
8597 
8598     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8599 
8600     // Figure out if the scale to use for div_fmas.
8601     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8602     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8603     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8604     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8605 
8606     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8607     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8608 
8609     SDValue Scale0Hi
8610       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8611     SDValue Scale1Hi
8612       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8613 
8614     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8615     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8616     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8617   } else {
8618     Scale = DivScale1.getValue(1);
8619   }
8620 
8621   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8622                              Fma4, Fma3, Mul, Scale);
8623 
8624   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8625 }
8626 
8627 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8628   EVT VT = Op.getValueType();
8629 
8630   if (VT == MVT::f32)
8631     return LowerFDIV32(Op, DAG);
8632 
8633   if (VT == MVT::f64)
8634     return LowerFDIV64(Op, DAG);
8635 
8636   if (VT == MVT::f16)
8637     return LowerFDIV16(Op, DAG);
8638 
8639   llvm_unreachable("Unexpected type for fdiv");
8640 }
8641 
8642 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8643   SDLoc DL(Op);
8644   StoreSDNode *Store = cast<StoreSDNode>(Op);
8645   EVT VT = Store->getMemoryVT();
8646 
8647   if (VT == MVT::i1) {
8648     return DAG.getTruncStore(Store->getChain(), DL,
8649        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8650        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8651   }
8652 
8653   assert(VT.isVector() &&
8654          Store->getValue().getValueType().getScalarType() == MVT::i32);
8655 
8656   unsigned AS = Store->getAddressSpace();
8657   if (Subtarget->hasLDSMisalignedBug() &&
8658       AS == AMDGPUAS::FLAT_ADDRESS &&
8659       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8660     return SplitVectorStore(Op, DAG);
8661   }
8662 
8663   MachineFunction &MF = DAG.getMachineFunction();
8664   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8665   // If there is a possibilty that flat instruction access scratch memory
8666   // then we need to use the same legalization rules we use for private.
8667   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8668       !Subtarget->hasMultiDwordFlatScratchAddressing())
8669     AS = MFI->hasFlatScratchInit() ?
8670          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8671 
8672   unsigned NumElements = VT.getVectorNumElements();
8673   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8674       AS == AMDGPUAS::FLAT_ADDRESS) {
8675     if (NumElements > 4)
8676       return SplitVectorStore(Op, DAG);
8677     // v3 stores not supported on SI.
8678     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8679       return SplitVectorStore(Op, DAG);
8680 
8681     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8682                                         VT, *Store->getMemOperand()))
8683       return expandUnalignedStore(Store, DAG);
8684 
8685     return SDValue();
8686   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8687     switch (Subtarget->getMaxPrivateElementSize()) {
8688     case 4:
8689       return scalarizeVectorStore(Store, DAG);
8690     case 8:
8691       if (NumElements > 2)
8692         return SplitVectorStore(Op, DAG);
8693       return SDValue();
8694     case 16:
8695       if (NumElements > 4 ||
8696           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8697         return SplitVectorStore(Op, DAG);
8698       return SDValue();
8699     default:
8700       llvm_unreachable("unsupported private_element_size");
8701     }
8702   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8703     // Use ds_write_b128 or ds_write_b96 when possible.
8704     if (Subtarget->hasDS96AndDS128() &&
8705         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8706          (VT.getStoreSize() == 12)) &&
8707         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8708                                            Store->getAlign()))
8709       return SDValue();
8710 
8711     if (NumElements > 2)
8712       return SplitVectorStore(Op, DAG);
8713 
8714     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8715     // address is negative, then the instruction is incorrectly treated as
8716     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8717     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8718     // store later in the SILoadStoreOptimizer.
8719     if (!Subtarget->hasUsableDSOffset() &&
8720         NumElements == 2 && VT.getStoreSize() == 8 &&
8721         Store->getAlignment() < 8) {
8722       return SplitVectorStore(Op, DAG);
8723     }
8724 
8725     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8726                                         VT, *Store->getMemOperand())) {
8727       if (VT.isVector())
8728         return SplitVectorStore(Op, DAG);
8729       return expandUnalignedStore(Store, DAG);
8730     }
8731 
8732     return SDValue();
8733   } else {
8734     llvm_unreachable("unhandled address space");
8735   }
8736 }
8737 
8738 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8739   SDLoc DL(Op);
8740   EVT VT = Op.getValueType();
8741   SDValue Arg = Op.getOperand(0);
8742   SDValue TrigVal;
8743 
8744   // Propagate fast-math flags so that the multiply we introduce can be folded
8745   // if Arg is already the result of a multiply by constant.
8746   auto Flags = Op->getFlags();
8747 
8748   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8749 
8750   if (Subtarget->hasTrigReducedRange()) {
8751     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8752     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8753   } else {
8754     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8755   }
8756 
8757   switch (Op.getOpcode()) {
8758   case ISD::FCOS:
8759     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8760   case ISD::FSIN:
8761     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8762   default:
8763     llvm_unreachable("Wrong trig opcode");
8764   }
8765 }
8766 
8767 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8768   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8769   assert(AtomicNode->isCompareAndSwap());
8770   unsigned AS = AtomicNode->getAddressSpace();
8771 
8772   // No custom lowering required for local address space
8773   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8774     return Op;
8775 
8776   // Non-local address space requires custom lowering for atomic compare
8777   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8778   SDLoc DL(Op);
8779   SDValue ChainIn = Op.getOperand(0);
8780   SDValue Addr = Op.getOperand(1);
8781   SDValue Old = Op.getOperand(2);
8782   SDValue New = Op.getOperand(3);
8783   EVT VT = Op.getValueType();
8784   MVT SimpleVT = VT.getSimpleVT();
8785   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8786 
8787   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8788   SDValue Ops[] = { ChainIn, Addr, NewOld };
8789 
8790   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8791                                  Ops, VT, AtomicNode->getMemOperand());
8792 }
8793 
8794 //===----------------------------------------------------------------------===//
8795 // Custom DAG optimizations
8796 //===----------------------------------------------------------------------===//
8797 
8798 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8799                                                      DAGCombinerInfo &DCI) const {
8800   EVT VT = N->getValueType(0);
8801   EVT ScalarVT = VT.getScalarType();
8802   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8803     return SDValue();
8804 
8805   SelectionDAG &DAG = DCI.DAG;
8806   SDLoc DL(N);
8807 
8808   SDValue Src = N->getOperand(0);
8809   EVT SrcVT = Src.getValueType();
8810 
8811   // TODO: We could try to match extracting the higher bytes, which would be
8812   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8813   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8814   // about in practice.
8815   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8816     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8817       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8818       DCI.AddToWorklist(Cvt.getNode());
8819 
8820       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8821       if (ScalarVT != MVT::f32) {
8822         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8823                           DAG.getTargetConstant(0, DL, MVT::i32));
8824       }
8825       return Cvt;
8826     }
8827   }
8828 
8829   return SDValue();
8830 }
8831 
8832 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8833 
8834 // This is a variant of
8835 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8836 //
8837 // The normal DAG combiner will do this, but only if the add has one use since
8838 // that would increase the number of instructions.
8839 //
8840 // This prevents us from seeing a constant offset that can be folded into a
8841 // memory instruction's addressing mode. If we know the resulting add offset of
8842 // a pointer can be folded into an addressing offset, we can replace the pointer
8843 // operand with the add of new constant offset. This eliminates one of the uses,
8844 // and may allow the remaining use to also be simplified.
8845 //
8846 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8847                                                unsigned AddrSpace,
8848                                                EVT MemVT,
8849                                                DAGCombinerInfo &DCI) const {
8850   SDValue N0 = N->getOperand(0);
8851   SDValue N1 = N->getOperand(1);
8852 
8853   // We only do this to handle cases where it's profitable when there are
8854   // multiple uses of the add, so defer to the standard combine.
8855   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8856       N0->hasOneUse())
8857     return SDValue();
8858 
8859   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8860   if (!CN1)
8861     return SDValue();
8862 
8863   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8864   if (!CAdd)
8865     return SDValue();
8866 
8867   // If the resulting offset is too large, we can't fold it into the addressing
8868   // mode offset.
8869   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8870   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8871 
8872   AddrMode AM;
8873   AM.HasBaseReg = true;
8874   AM.BaseOffs = Offset.getSExtValue();
8875   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8876     return SDValue();
8877 
8878   SelectionDAG &DAG = DCI.DAG;
8879   SDLoc SL(N);
8880   EVT VT = N->getValueType(0);
8881 
8882   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8883   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8884 
8885   SDNodeFlags Flags;
8886   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8887                           (N0.getOpcode() == ISD::OR ||
8888                            N0->getFlags().hasNoUnsignedWrap()));
8889 
8890   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8891 }
8892 
8893 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8894 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8895 /// specific intrinsic, but they all place the pointer operand first.
8896 static unsigned getBasePtrIndex(const MemSDNode *N) {
8897   switch (N->getOpcode()) {
8898   case ISD::STORE:
8899   case ISD::INTRINSIC_W_CHAIN:
8900   case ISD::INTRINSIC_VOID:
8901     return 2;
8902   default:
8903     return 1;
8904   }
8905 }
8906 
8907 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8908                                                   DAGCombinerInfo &DCI) const {
8909   SelectionDAG &DAG = DCI.DAG;
8910   SDLoc SL(N);
8911 
8912   unsigned PtrIdx = getBasePtrIndex(N);
8913   SDValue Ptr = N->getOperand(PtrIdx);
8914 
8915   // TODO: We could also do this for multiplies.
8916   if (Ptr.getOpcode() == ISD::SHL) {
8917     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8918                                           N->getMemoryVT(), DCI);
8919     if (NewPtr) {
8920       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8921 
8922       NewOps[PtrIdx] = NewPtr;
8923       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8924     }
8925   }
8926 
8927   return SDValue();
8928 }
8929 
8930 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8931   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8932          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8933          (Opc == ISD::XOR && Val == 0);
8934 }
8935 
8936 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8937 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8938 // integer combine opportunities since most 64-bit operations are decomposed
8939 // this way.  TODO: We won't want this for SALU especially if it is an inline
8940 // immediate.
8941 SDValue SITargetLowering::splitBinaryBitConstantOp(
8942   DAGCombinerInfo &DCI,
8943   const SDLoc &SL,
8944   unsigned Opc, SDValue LHS,
8945   const ConstantSDNode *CRHS) const {
8946   uint64_t Val = CRHS->getZExtValue();
8947   uint32_t ValLo = Lo_32(Val);
8948   uint32_t ValHi = Hi_32(Val);
8949   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8950 
8951     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8952          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8953         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8954     // If we need to materialize a 64-bit immediate, it will be split up later
8955     // anyway. Avoid creating the harder to understand 64-bit immediate
8956     // materialization.
8957     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8958   }
8959 
8960   return SDValue();
8961 }
8962 
8963 // Returns true if argument is a boolean value which is not serialized into
8964 // memory or argument and does not require v_cndmask_b32 to be deserialized.
8965 static bool isBoolSGPR(SDValue V) {
8966   if (V.getValueType() != MVT::i1)
8967     return false;
8968   switch (V.getOpcode()) {
8969   default:
8970     break;
8971   case ISD::SETCC:
8972   case AMDGPUISD::FP_CLASS:
8973     return true;
8974   case ISD::AND:
8975   case ISD::OR:
8976   case ISD::XOR:
8977     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
8978   }
8979   return false;
8980 }
8981 
8982 // If a constant has all zeroes or all ones within each byte return it.
8983 // Otherwise return 0.
8984 static uint32_t getConstantPermuteMask(uint32_t C) {
8985   // 0xff for any zero byte in the mask
8986   uint32_t ZeroByteMask = 0;
8987   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8988   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8989   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8990   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8991   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8992   if ((NonZeroByteMask & C) != NonZeroByteMask)
8993     return 0; // Partial bytes selected.
8994   return C;
8995 }
8996 
8997 // Check if a node selects whole bytes from its operand 0 starting at a byte
8998 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8999 // or -1 if not succeeded.
9000 // Note byte select encoding:
9001 // value 0-3 selects corresponding source byte;
9002 // value 0xc selects zero;
9003 // value 0xff selects 0xff.
9004 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9005   assert(V.getValueSizeInBits() == 32);
9006 
9007   if (V.getNumOperands() != 2)
9008     return ~0;
9009 
9010   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9011   if (!N1)
9012     return ~0;
9013 
9014   uint32_t C = N1->getZExtValue();
9015 
9016   switch (V.getOpcode()) {
9017   default:
9018     break;
9019   case ISD::AND:
9020     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9021       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9022     }
9023     break;
9024 
9025   case ISD::OR:
9026     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9027       return (0x03020100 & ~ConstMask) | ConstMask;
9028     }
9029     break;
9030 
9031   case ISD::SHL:
9032     if (C % 8)
9033       return ~0;
9034 
9035     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9036 
9037   case ISD::SRL:
9038     if (C % 8)
9039       return ~0;
9040 
9041     return uint32_t(0x0c0c0c0c03020100ull >> C);
9042   }
9043 
9044   return ~0;
9045 }
9046 
9047 SDValue SITargetLowering::performAndCombine(SDNode *N,
9048                                             DAGCombinerInfo &DCI) const {
9049   if (DCI.isBeforeLegalize())
9050     return SDValue();
9051 
9052   SelectionDAG &DAG = DCI.DAG;
9053   EVT VT = N->getValueType(0);
9054   SDValue LHS = N->getOperand(0);
9055   SDValue RHS = N->getOperand(1);
9056 
9057 
9058   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9059   if (VT == MVT::i64 && CRHS) {
9060     if (SDValue Split
9061         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9062       return Split;
9063   }
9064 
9065   if (CRHS && VT == MVT::i32) {
9066     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9067     // nb = number of trailing zeroes in mask
9068     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9069     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9070     uint64_t Mask = CRHS->getZExtValue();
9071     unsigned Bits = countPopulation(Mask);
9072     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9073         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9074       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9075         unsigned Shift = CShift->getZExtValue();
9076         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9077         unsigned Offset = NB + Shift;
9078         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9079           SDLoc SL(N);
9080           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9081                                     LHS->getOperand(0),
9082                                     DAG.getConstant(Offset, SL, MVT::i32),
9083                                     DAG.getConstant(Bits, SL, MVT::i32));
9084           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9085           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9086                                     DAG.getValueType(NarrowVT));
9087           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9088                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9089           return Shl;
9090         }
9091       }
9092     }
9093 
9094     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9095     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9096         isa<ConstantSDNode>(LHS.getOperand(2))) {
9097       uint32_t Sel = getConstantPermuteMask(Mask);
9098       if (!Sel)
9099         return SDValue();
9100 
9101       // Select 0xc for all zero bytes
9102       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9103       SDLoc DL(N);
9104       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9105                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9106     }
9107   }
9108 
9109   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9110   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9111   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9112     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9113     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9114 
9115     SDValue X = LHS.getOperand(0);
9116     SDValue Y = RHS.getOperand(0);
9117     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9118       return SDValue();
9119 
9120     if (LCC == ISD::SETO) {
9121       if (X != LHS.getOperand(1))
9122         return SDValue();
9123 
9124       if (RCC == ISD::SETUNE) {
9125         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9126         if (!C1 || !C1->isInfinity() || C1->isNegative())
9127           return SDValue();
9128 
9129         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9130                               SIInstrFlags::N_SUBNORMAL |
9131                               SIInstrFlags::N_ZERO |
9132                               SIInstrFlags::P_ZERO |
9133                               SIInstrFlags::P_SUBNORMAL |
9134                               SIInstrFlags::P_NORMAL;
9135 
9136         static_assert(((~(SIInstrFlags::S_NAN |
9137                           SIInstrFlags::Q_NAN |
9138                           SIInstrFlags::N_INFINITY |
9139                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9140                       "mask not equal");
9141 
9142         SDLoc DL(N);
9143         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9144                            X, DAG.getConstant(Mask, DL, MVT::i32));
9145       }
9146     }
9147   }
9148 
9149   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9150     std::swap(LHS, RHS);
9151 
9152   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9153       RHS.hasOneUse()) {
9154     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9155     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9156     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9157     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9158     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9159         (RHS.getOperand(0) == LHS.getOperand(0) &&
9160          LHS.getOperand(0) == LHS.getOperand(1))) {
9161       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9162       unsigned NewMask = LCC == ISD::SETO ?
9163         Mask->getZExtValue() & ~OrdMask :
9164         Mask->getZExtValue() & OrdMask;
9165 
9166       SDLoc DL(N);
9167       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9168                          DAG.getConstant(NewMask, DL, MVT::i32));
9169     }
9170   }
9171 
9172   if (VT == MVT::i32 &&
9173       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9174     // and x, (sext cc from i1) => select cc, x, 0
9175     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9176       std::swap(LHS, RHS);
9177     if (isBoolSGPR(RHS.getOperand(0)))
9178       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9179                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9180   }
9181 
9182   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9183   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9184   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9185       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9186     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9187     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9188     if (LHSMask != ~0u && RHSMask != ~0u) {
9189       // Canonicalize the expression in an attempt to have fewer unique masks
9190       // and therefore fewer registers used to hold the masks.
9191       if (LHSMask > RHSMask) {
9192         std::swap(LHSMask, RHSMask);
9193         std::swap(LHS, RHS);
9194       }
9195 
9196       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9197       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9198       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9199       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9200 
9201       // Check of we need to combine values from two sources within a byte.
9202       if (!(LHSUsedLanes & RHSUsedLanes) &&
9203           // If we select high and lower word keep it for SDWA.
9204           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9205           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9206         // Each byte in each mask is either selector mask 0-3, or has higher
9207         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9208         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9209         // mask which is not 0xff wins. By anding both masks we have a correct
9210         // result except that 0x0c shall be corrected to give 0x0c only.
9211         uint32_t Mask = LHSMask & RHSMask;
9212         for (unsigned I = 0; I < 32; I += 8) {
9213           uint32_t ByteSel = 0xff << I;
9214           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9215             Mask &= (0x0c << I) & 0xffffffff;
9216         }
9217 
9218         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9219         // or 0x0c.
9220         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9221         SDLoc DL(N);
9222 
9223         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9224                            LHS.getOperand(0), RHS.getOperand(0),
9225                            DAG.getConstant(Sel, DL, MVT::i32));
9226       }
9227     }
9228   }
9229 
9230   return SDValue();
9231 }
9232 
9233 SDValue SITargetLowering::performOrCombine(SDNode *N,
9234                                            DAGCombinerInfo &DCI) const {
9235   SelectionDAG &DAG = DCI.DAG;
9236   SDValue LHS = N->getOperand(0);
9237   SDValue RHS = N->getOperand(1);
9238 
9239   EVT VT = N->getValueType(0);
9240   if (VT == MVT::i1) {
9241     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9242     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9243         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9244       SDValue Src = LHS.getOperand(0);
9245       if (Src != RHS.getOperand(0))
9246         return SDValue();
9247 
9248       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9249       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9250       if (!CLHS || !CRHS)
9251         return SDValue();
9252 
9253       // Only 10 bits are used.
9254       static const uint32_t MaxMask = 0x3ff;
9255 
9256       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9257       SDLoc DL(N);
9258       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9259                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9260     }
9261 
9262     return SDValue();
9263   }
9264 
9265   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9266   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9267       LHS.getOpcode() == AMDGPUISD::PERM &&
9268       isa<ConstantSDNode>(LHS.getOperand(2))) {
9269     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9270     if (!Sel)
9271       return SDValue();
9272 
9273     Sel |= LHS.getConstantOperandVal(2);
9274     SDLoc DL(N);
9275     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9276                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9277   }
9278 
9279   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9280   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9281   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9282       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9283     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9284     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9285     if (LHSMask != ~0u && RHSMask != ~0u) {
9286       // Canonicalize the expression in an attempt to have fewer unique masks
9287       // and therefore fewer registers used to hold the masks.
9288       if (LHSMask > RHSMask) {
9289         std::swap(LHSMask, RHSMask);
9290         std::swap(LHS, RHS);
9291       }
9292 
9293       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9294       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9295       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9296       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9297 
9298       // Check of we need to combine values from two sources within a byte.
9299       if (!(LHSUsedLanes & RHSUsedLanes) &&
9300           // If we select high and lower word keep it for SDWA.
9301           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9302           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9303         // Kill zero bytes selected by other mask. Zero value is 0xc.
9304         LHSMask &= ~RHSUsedLanes;
9305         RHSMask &= ~LHSUsedLanes;
9306         // Add 4 to each active LHS lane
9307         LHSMask |= LHSUsedLanes & 0x04040404;
9308         // Combine masks
9309         uint32_t Sel = LHSMask | RHSMask;
9310         SDLoc DL(N);
9311 
9312         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9313                            LHS.getOperand(0), RHS.getOperand(0),
9314                            DAG.getConstant(Sel, DL, MVT::i32));
9315       }
9316     }
9317   }
9318 
9319   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9320     return SDValue();
9321 
9322   // TODO: This could be a generic combine with a predicate for extracting the
9323   // high half of an integer being free.
9324 
9325   // (or i64:x, (zero_extend i32:y)) ->
9326   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9327   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9328       RHS.getOpcode() != ISD::ZERO_EXTEND)
9329     std::swap(LHS, RHS);
9330 
9331   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9332     SDValue ExtSrc = RHS.getOperand(0);
9333     EVT SrcVT = ExtSrc.getValueType();
9334     if (SrcVT == MVT::i32) {
9335       SDLoc SL(N);
9336       SDValue LowLHS, HiBits;
9337       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9338       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9339 
9340       DCI.AddToWorklist(LowOr.getNode());
9341       DCI.AddToWorklist(HiBits.getNode());
9342 
9343       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9344                                 LowOr, HiBits);
9345       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9346     }
9347   }
9348 
9349   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9350   if (CRHS) {
9351     if (SDValue Split
9352           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9353       return Split;
9354   }
9355 
9356   return SDValue();
9357 }
9358 
9359 SDValue SITargetLowering::performXorCombine(SDNode *N,
9360                                             DAGCombinerInfo &DCI) const {
9361   EVT VT = N->getValueType(0);
9362   if (VT != MVT::i64)
9363     return SDValue();
9364 
9365   SDValue LHS = N->getOperand(0);
9366   SDValue RHS = N->getOperand(1);
9367 
9368   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9369   if (CRHS) {
9370     if (SDValue Split
9371           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9372       return Split;
9373   }
9374 
9375   return SDValue();
9376 }
9377 
9378 // Instructions that will be lowered with a final instruction that zeros the
9379 // high result bits.
9380 // XXX - probably only need to list legal operations.
9381 static bool fp16SrcZerosHighBits(unsigned Opc) {
9382   switch (Opc) {
9383   case ISD::FADD:
9384   case ISD::FSUB:
9385   case ISD::FMUL:
9386   case ISD::FDIV:
9387   case ISD::FREM:
9388   case ISD::FMA:
9389   case ISD::FMAD:
9390   case ISD::FCANONICALIZE:
9391   case ISD::FP_ROUND:
9392   case ISD::UINT_TO_FP:
9393   case ISD::SINT_TO_FP:
9394   case ISD::FABS:
9395     // Fabs is lowered to a bit operation, but it's an and which will clear the
9396     // high bits anyway.
9397   case ISD::FSQRT:
9398   case ISD::FSIN:
9399   case ISD::FCOS:
9400   case ISD::FPOWI:
9401   case ISD::FPOW:
9402   case ISD::FLOG:
9403   case ISD::FLOG2:
9404   case ISD::FLOG10:
9405   case ISD::FEXP:
9406   case ISD::FEXP2:
9407   case ISD::FCEIL:
9408   case ISD::FTRUNC:
9409   case ISD::FRINT:
9410   case ISD::FNEARBYINT:
9411   case ISD::FROUND:
9412   case ISD::FFLOOR:
9413   case ISD::FMINNUM:
9414   case ISD::FMAXNUM:
9415   case AMDGPUISD::FRACT:
9416   case AMDGPUISD::CLAMP:
9417   case AMDGPUISD::COS_HW:
9418   case AMDGPUISD::SIN_HW:
9419   case AMDGPUISD::FMIN3:
9420   case AMDGPUISD::FMAX3:
9421   case AMDGPUISD::FMED3:
9422   case AMDGPUISD::FMAD_FTZ:
9423   case AMDGPUISD::RCP:
9424   case AMDGPUISD::RSQ:
9425   case AMDGPUISD::RCP_IFLAG:
9426   case AMDGPUISD::LDEXP:
9427     return true;
9428   default:
9429     // fcopysign, select and others may be lowered to 32-bit bit operations
9430     // which don't zero the high bits.
9431     return false;
9432   }
9433 }
9434 
9435 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9436                                                    DAGCombinerInfo &DCI) const {
9437   if (!Subtarget->has16BitInsts() ||
9438       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9439     return SDValue();
9440 
9441   EVT VT = N->getValueType(0);
9442   if (VT != MVT::i32)
9443     return SDValue();
9444 
9445   SDValue Src = N->getOperand(0);
9446   if (Src.getValueType() != MVT::i16)
9447     return SDValue();
9448 
9449   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9450   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9451   if (Src.getOpcode() == ISD::BITCAST) {
9452     SDValue BCSrc = Src.getOperand(0);
9453     if (BCSrc.getValueType() == MVT::f16 &&
9454         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9455       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9456   }
9457 
9458   return SDValue();
9459 }
9460 
9461 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9462                                                         DAGCombinerInfo &DCI)
9463                                                         const {
9464   SDValue Src = N->getOperand(0);
9465   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9466 
9467   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9468       VTSign->getVT() == MVT::i8) ||
9469       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9470       VTSign->getVT() == MVT::i16)) &&
9471       Src.hasOneUse()) {
9472     auto *M = cast<MemSDNode>(Src);
9473     SDValue Ops[] = {
9474       Src.getOperand(0), // Chain
9475       Src.getOperand(1), // rsrc
9476       Src.getOperand(2), // vindex
9477       Src.getOperand(3), // voffset
9478       Src.getOperand(4), // soffset
9479       Src.getOperand(5), // offset
9480       Src.getOperand(6),
9481       Src.getOperand(7)
9482     };
9483     // replace with BUFFER_LOAD_BYTE/SHORT
9484     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9485                                          Src.getOperand(0).getValueType());
9486     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9487                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9488     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9489                                                           ResList,
9490                                                           Ops, M->getMemoryVT(),
9491                                                           M->getMemOperand());
9492     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9493                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9494   }
9495   return SDValue();
9496 }
9497 
9498 SDValue SITargetLowering::performClassCombine(SDNode *N,
9499                                               DAGCombinerInfo &DCI) const {
9500   SelectionDAG &DAG = DCI.DAG;
9501   SDValue Mask = N->getOperand(1);
9502 
9503   // fp_class x, 0 -> false
9504   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9505     if (CMask->isNullValue())
9506       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9507   }
9508 
9509   if (N->getOperand(0).isUndef())
9510     return DAG.getUNDEF(MVT::i1);
9511 
9512   return SDValue();
9513 }
9514 
9515 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9516                                             DAGCombinerInfo &DCI) const {
9517   EVT VT = N->getValueType(0);
9518   SDValue N0 = N->getOperand(0);
9519 
9520   if (N0.isUndef())
9521     return N0;
9522 
9523   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9524                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9525     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9526                            N->getFlags());
9527   }
9528 
9529   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9530     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9531                            N0.getOperand(0), N->getFlags());
9532   }
9533 
9534   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9535 }
9536 
9537 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9538                                        unsigned MaxDepth) const {
9539   unsigned Opcode = Op.getOpcode();
9540   if (Opcode == ISD::FCANONICALIZE)
9541     return true;
9542 
9543   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9544     auto F = CFP->getValueAPF();
9545     if (F.isNaN() && F.isSignaling())
9546       return false;
9547     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9548   }
9549 
9550   // If source is a result of another standard FP operation it is already in
9551   // canonical form.
9552   if (MaxDepth == 0)
9553     return false;
9554 
9555   switch (Opcode) {
9556   // These will flush denorms if required.
9557   case ISD::FADD:
9558   case ISD::FSUB:
9559   case ISD::FMUL:
9560   case ISD::FCEIL:
9561   case ISD::FFLOOR:
9562   case ISD::FMA:
9563   case ISD::FMAD:
9564   case ISD::FSQRT:
9565   case ISD::FDIV:
9566   case ISD::FREM:
9567   case ISD::FP_ROUND:
9568   case ISD::FP_EXTEND:
9569   case AMDGPUISD::FMUL_LEGACY:
9570   case AMDGPUISD::FMAD_FTZ:
9571   case AMDGPUISD::RCP:
9572   case AMDGPUISD::RSQ:
9573   case AMDGPUISD::RSQ_CLAMP:
9574   case AMDGPUISD::RCP_LEGACY:
9575   case AMDGPUISD::RCP_IFLAG:
9576   case AMDGPUISD::DIV_SCALE:
9577   case AMDGPUISD::DIV_FMAS:
9578   case AMDGPUISD::DIV_FIXUP:
9579   case AMDGPUISD::FRACT:
9580   case AMDGPUISD::LDEXP:
9581   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9582   case AMDGPUISD::CVT_F32_UBYTE0:
9583   case AMDGPUISD::CVT_F32_UBYTE1:
9584   case AMDGPUISD::CVT_F32_UBYTE2:
9585   case AMDGPUISD::CVT_F32_UBYTE3:
9586     return true;
9587 
9588   // It can/will be lowered or combined as a bit operation.
9589   // Need to check their input recursively to handle.
9590   case ISD::FNEG:
9591   case ISD::FABS:
9592   case ISD::FCOPYSIGN:
9593     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9594 
9595   case ISD::FSIN:
9596   case ISD::FCOS:
9597   case ISD::FSINCOS:
9598     return Op.getValueType().getScalarType() != MVT::f16;
9599 
9600   case ISD::FMINNUM:
9601   case ISD::FMAXNUM:
9602   case ISD::FMINNUM_IEEE:
9603   case ISD::FMAXNUM_IEEE:
9604   case AMDGPUISD::CLAMP:
9605   case AMDGPUISD::FMED3:
9606   case AMDGPUISD::FMAX3:
9607   case AMDGPUISD::FMIN3: {
9608     // FIXME: Shouldn't treat the generic operations different based these.
9609     // However, we aren't really required to flush the result from
9610     // minnum/maxnum..
9611 
9612     // snans will be quieted, so we only need to worry about denormals.
9613     if (Subtarget->supportsMinMaxDenormModes() ||
9614         denormalsEnabledForType(DAG, Op.getValueType()))
9615       return true;
9616 
9617     // Flushing may be required.
9618     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9619     // targets need to check their input recursively.
9620 
9621     // FIXME: Does this apply with clamp? It's implemented with max.
9622     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9623       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9624         return false;
9625     }
9626 
9627     return true;
9628   }
9629   case ISD::SELECT: {
9630     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9631            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9632   }
9633   case ISD::BUILD_VECTOR: {
9634     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9635       SDValue SrcOp = Op.getOperand(i);
9636       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9637         return false;
9638     }
9639 
9640     return true;
9641   }
9642   case ISD::EXTRACT_VECTOR_ELT:
9643   case ISD::EXTRACT_SUBVECTOR: {
9644     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9645   }
9646   case ISD::INSERT_VECTOR_ELT: {
9647     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9648            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9649   }
9650   case ISD::UNDEF:
9651     // Could be anything.
9652     return false;
9653 
9654   case ISD::BITCAST:
9655     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9656   case ISD::TRUNCATE: {
9657     // Hack round the mess we make when legalizing extract_vector_elt
9658     if (Op.getValueType() == MVT::i16) {
9659       SDValue TruncSrc = Op.getOperand(0);
9660       if (TruncSrc.getValueType() == MVT::i32 &&
9661           TruncSrc.getOpcode() == ISD::BITCAST &&
9662           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9663         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9664       }
9665     }
9666     return false;
9667   }
9668   case ISD::INTRINSIC_WO_CHAIN: {
9669     unsigned IntrinsicID
9670       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9671     // TODO: Handle more intrinsics
9672     switch (IntrinsicID) {
9673     case Intrinsic::amdgcn_cvt_pkrtz:
9674     case Intrinsic::amdgcn_cubeid:
9675     case Intrinsic::amdgcn_frexp_mant:
9676     case Intrinsic::amdgcn_fdot2:
9677     case Intrinsic::amdgcn_rcp:
9678     case Intrinsic::amdgcn_rsq:
9679     case Intrinsic::amdgcn_rsq_clamp:
9680     case Intrinsic::amdgcn_rcp_legacy:
9681     case Intrinsic::amdgcn_rsq_legacy:
9682     case Intrinsic::amdgcn_trig_preop:
9683       return true;
9684     default:
9685       break;
9686     }
9687 
9688     LLVM_FALLTHROUGH;
9689   }
9690   default:
9691     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9692            DAG.isKnownNeverSNaN(Op);
9693   }
9694 
9695   llvm_unreachable("invalid operation");
9696 }
9697 
9698 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9699                                        unsigned MaxDepth) const {
9700   MachineRegisterInfo &MRI = MF.getRegInfo();
9701   MachineInstr *MI = MRI.getVRegDef(Reg);
9702   unsigned Opcode = MI->getOpcode();
9703 
9704   if (Opcode == AMDGPU::G_FCANONICALIZE)
9705     return true;
9706 
9707   if (Opcode == AMDGPU::G_FCONSTANT) {
9708     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9709     if (F.isNaN() && F.isSignaling())
9710       return false;
9711     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9712   }
9713 
9714   if (MaxDepth == 0)
9715     return false;
9716 
9717   switch (Opcode) {
9718   case AMDGPU::G_FMINNUM_IEEE:
9719   case AMDGPU::G_FMAXNUM_IEEE: {
9720     if (Subtarget->supportsMinMaxDenormModes() ||
9721         denormalsEnabledForType(MRI.getType(Reg), MF))
9722       return true;
9723     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9724       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9725         return false;
9726     }
9727     return true;
9728   }
9729   default:
9730     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9731            isKnownNeverSNaN(Reg, MRI);
9732   }
9733 
9734   llvm_unreachable("invalid operation");
9735 }
9736 
9737 // Constant fold canonicalize.
9738 SDValue SITargetLowering::getCanonicalConstantFP(
9739   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9740   // Flush denormals to 0 if not enabled.
9741   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9742     return DAG.getConstantFP(0.0, SL, VT);
9743 
9744   if (C.isNaN()) {
9745     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9746     if (C.isSignaling()) {
9747       // Quiet a signaling NaN.
9748       // FIXME: Is this supposed to preserve payload bits?
9749       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9750     }
9751 
9752     // Make sure it is the canonical NaN bitpattern.
9753     //
9754     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9755     // immediate?
9756     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9757       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9758   }
9759 
9760   // Already canonical.
9761   return DAG.getConstantFP(C, SL, VT);
9762 }
9763 
9764 static bool vectorEltWillFoldAway(SDValue Op) {
9765   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9766 }
9767 
9768 SDValue SITargetLowering::performFCanonicalizeCombine(
9769   SDNode *N,
9770   DAGCombinerInfo &DCI) const {
9771   SelectionDAG &DAG = DCI.DAG;
9772   SDValue N0 = N->getOperand(0);
9773   EVT VT = N->getValueType(0);
9774 
9775   // fcanonicalize undef -> qnan
9776   if (N0.isUndef()) {
9777     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9778     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9779   }
9780 
9781   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9782     EVT VT = N->getValueType(0);
9783     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9784   }
9785 
9786   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9787   //                                                   (fcanonicalize k)
9788   //
9789   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9790 
9791   // TODO: This could be better with wider vectors that will be split to v2f16,
9792   // and to consider uses since there aren't that many packed operations.
9793   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9794       isTypeLegal(MVT::v2f16)) {
9795     SDLoc SL(N);
9796     SDValue NewElts[2];
9797     SDValue Lo = N0.getOperand(0);
9798     SDValue Hi = N0.getOperand(1);
9799     EVT EltVT = Lo.getValueType();
9800 
9801     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9802       for (unsigned I = 0; I != 2; ++I) {
9803         SDValue Op = N0.getOperand(I);
9804         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9805           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9806                                               CFP->getValueAPF());
9807         } else if (Op.isUndef()) {
9808           // Handled below based on what the other operand is.
9809           NewElts[I] = Op;
9810         } else {
9811           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9812         }
9813       }
9814 
9815       // If one half is undef, and one is constant, perfer a splat vector rather
9816       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9817       // cheaper to use and may be free with a packed operation.
9818       if (NewElts[0].isUndef()) {
9819         if (isa<ConstantFPSDNode>(NewElts[1]))
9820           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9821             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9822       }
9823 
9824       if (NewElts[1].isUndef()) {
9825         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9826           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9827       }
9828 
9829       return DAG.getBuildVector(VT, SL, NewElts);
9830     }
9831   }
9832 
9833   unsigned SrcOpc = N0.getOpcode();
9834 
9835   // If it's free to do so, push canonicalizes further up the source, which may
9836   // find a canonical source.
9837   //
9838   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9839   // sNaNs.
9840   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9841     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9842     if (CRHS && N0.hasOneUse()) {
9843       SDLoc SL(N);
9844       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9845                                    N0.getOperand(0));
9846       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9847       DCI.AddToWorklist(Canon0.getNode());
9848 
9849       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9850     }
9851   }
9852 
9853   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9854 }
9855 
9856 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9857   switch (Opc) {
9858   case ISD::FMAXNUM:
9859   case ISD::FMAXNUM_IEEE:
9860     return AMDGPUISD::FMAX3;
9861   case ISD::SMAX:
9862     return AMDGPUISD::SMAX3;
9863   case ISD::UMAX:
9864     return AMDGPUISD::UMAX3;
9865   case ISD::FMINNUM:
9866   case ISD::FMINNUM_IEEE:
9867     return AMDGPUISD::FMIN3;
9868   case ISD::SMIN:
9869     return AMDGPUISD::SMIN3;
9870   case ISD::UMIN:
9871     return AMDGPUISD::UMIN3;
9872   default:
9873     llvm_unreachable("Not a min/max opcode");
9874   }
9875 }
9876 
9877 SDValue SITargetLowering::performIntMed3ImmCombine(
9878   SelectionDAG &DAG, const SDLoc &SL,
9879   SDValue Op0, SDValue Op1, bool Signed) const {
9880   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9881   if (!K1)
9882     return SDValue();
9883 
9884   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9885   if (!K0)
9886     return SDValue();
9887 
9888   if (Signed) {
9889     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9890       return SDValue();
9891   } else {
9892     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9893       return SDValue();
9894   }
9895 
9896   EVT VT = K0->getValueType(0);
9897   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9898   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9899     return DAG.getNode(Med3Opc, SL, VT,
9900                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9901   }
9902 
9903   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9904   if (VT == MVT::i16) {
9905     MVT NVT = MVT::i32;
9906     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9907 
9908     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9909     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9910     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9911 
9912     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9913     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9914   }
9915 
9916   return SDValue();
9917 }
9918 
9919 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9920   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9921     return C;
9922 
9923   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9924     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9925       return C;
9926   }
9927 
9928   return nullptr;
9929 }
9930 
9931 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9932                                                   const SDLoc &SL,
9933                                                   SDValue Op0,
9934                                                   SDValue Op1) const {
9935   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9936   if (!K1)
9937     return SDValue();
9938 
9939   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9940   if (!K0)
9941     return SDValue();
9942 
9943   // Ordered >= (although NaN inputs should have folded away by now).
9944   if (K0->getValueAPF() > K1->getValueAPF())
9945     return SDValue();
9946 
9947   const MachineFunction &MF = DAG.getMachineFunction();
9948   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9949 
9950   // TODO: Check IEEE bit enabled?
9951   EVT VT = Op0.getValueType();
9952   if (Info->getMode().DX10Clamp) {
9953     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9954     // hardware fmed3 behavior converting to a min.
9955     // FIXME: Should this be allowing -0.0?
9956     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9957       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9958   }
9959 
9960   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9961   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9962     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9963     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9964     // then give the other result, which is different from med3 with a NaN
9965     // input.
9966     SDValue Var = Op0.getOperand(0);
9967     if (!DAG.isKnownNeverSNaN(Var))
9968       return SDValue();
9969 
9970     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9971 
9972     if ((!K0->hasOneUse() ||
9973          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9974         (!K1->hasOneUse() ||
9975          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9976       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9977                          Var, SDValue(K0, 0), SDValue(K1, 0));
9978     }
9979   }
9980 
9981   return SDValue();
9982 }
9983 
9984 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9985                                                DAGCombinerInfo &DCI) const {
9986   SelectionDAG &DAG = DCI.DAG;
9987 
9988   EVT VT = N->getValueType(0);
9989   unsigned Opc = N->getOpcode();
9990   SDValue Op0 = N->getOperand(0);
9991   SDValue Op1 = N->getOperand(1);
9992 
9993   // Only do this if the inner op has one use since this will just increases
9994   // register pressure for no benefit.
9995 
9996   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9997       !VT.isVector() &&
9998       (VT == MVT::i32 || VT == MVT::f32 ||
9999        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10000     // max(max(a, b), c) -> max3(a, b, c)
10001     // min(min(a, b), c) -> min3(a, b, c)
10002     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10003       SDLoc DL(N);
10004       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10005                          DL,
10006                          N->getValueType(0),
10007                          Op0.getOperand(0),
10008                          Op0.getOperand(1),
10009                          Op1);
10010     }
10011 
10012     // Try commuted.
10013     // max(a, max(b, c)) -> max3(a, b, c)
10014     // min(a, min(b, c)) -> min3(a, b, c)
10015     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10016       SDLoc DL(N);
10017       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10018                          DL,
10019                          N->getValueType(0),
10020                          Op0,
10021                          Op1.getOperand(0),
10022                          Op1.getOperand(1));
10023     }
10024   }
10025 
10026   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10027   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10028     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10029       return Med3;
10030   }
10031 
10032   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10033     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10034       return Med3;
10035   }
10036 
10037   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10038   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10039        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10040        (Opc == AMDGPUISD::FMIN_LEGACY &&
10041         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10042       (VT == MVT::f32 || VT == MVT::f64 ||
10043        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10044        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10045       Op0.hasOneUse()) {
10046     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10047       return Res;
10048   }
10049 
10050   return SDValue();
10051 }
10052 
10053 static bool isClampZeroToOne(SDValue A, SDValue B) {
10054   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10055     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10056       // FIXME: Should this be allowing -0.0?
10057       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10058              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10059     }
10060   }
10061 
10062   return false;
10063 }
10064 
10065 // FIXME: Should only worry about snans for version with chain.
10066 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10067                                               DAGCombinerInfo &DCI) const {
10068   EVT VT = N->getValueType(0);
10069   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10070   // NaNs. With a NaN input, the order of the operands may change the result.
10071 
10072   SelectionDAG &DAG = DCI.DAG;
10073   SDLoc SL(N);
10074 
10075   SDValue Src0 = N->getOperand(0);
10076   SDValue Src1 = N->getOperand(1);
10077   SDValue Src2 = N->getOperand(2);
10078 
10079   if (isClampZeroToOne(Src0, Src1)) {
10080     // const_a, const_b, x -> clamp is safe in all cases including signaling
10081     // nans.
10082     // FIXME: Should this be allowing -0.0?
10083     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10084   }
10085 
10086   const MachineFunction &MF = DAG.getMachineFunction();
10087   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10088 
10089   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10090   // handling no dx10-clamp?
10091   if (Info->getMode().DX10Clamp) {
10092     // If NaNs is clamped to 0, we are free to reorder the inputs.
10093 
10094     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10095       std::swap(Src0, Src1);
10096 
10097     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10098       std::swap(Src1, Src2);
10099 
10100     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10101       std::swap(Src0, Src1);
10102 
10103     if (isClampZeroToOne(Src1, Src2))
10104       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10105   }
10106 
10107   return SDValue();
10108 }
10109 
10110 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10111                                                  DAGCombinerInfo &DCI) const {
10112   SDValue Src0 = N->getOperand(0);
10113   SDValue Src1 = N->getOperand(1);
10114   if (Src0.isUndef() && Src1.isUndef())
10115     return DCI.DAG.getUNDEF(N->getValueType(0));
10116   return SDValue();
10117 }
10118 
10119 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10120 // expanded into a set of cmp/select instructions.
10121 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10122                                                 unsigned NumElem,
10123                                                 bool IsDivergentIdx) {
10124   if (UseDivergentRegisterIndexing)
10125     return false;
10126 
10127   unsigned VecSize = EltSize * NumElem;
10128 
10129   // Sub-dword vectors of size 2 dword or less have better implementation.
10130   if (VecSize <= 64 && EltSize < 32)
10131     return false;
10132 
10133   // Always expand the rest of sub-dword instructions, otherwise it will be
10134   // lowered via memory.
10135   if (EltSize < 32)
10136     return true;
10137 
10138   // Always do this if var-idx is divergent, otherwise it will become a loop.
10139   if (IsDivergentIdx)
10140     return true;
10141 
10142   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10143   unsigned NumInsts = NumElem /* Number of compares */ +
10144                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10145   return NumInsts <= 16;
10146 }
10147 
10148 static bool shouldExpandVectorDynExt(SDNode *N) {
10149   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10150   if (isa<ConstantSDNode>(Idx))
10151     return false;
10152 
10153   SDValue Vec = N->getOperand(0);
10154   EVT VecVT = Vec.getValueType();
10155   EVT EltVT = VecVT.getVectorElementType();
10156   unsigned EltSize = EltVT.getSizeInBits();
10157   unsigned NumElem = VecVT.getVectorNumElements();
10158 
10159   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10160                                                     Idx->isDivergent());
10161 }
10162 
10163 SDValue SITargetLowering::performExtractVectorEltCombine(
10164   SDNode *N, DAGCombinerInfo &DCI) const {
10165   SDValue Vec = N->getOperand(0);
10166   SelectionDAG &DAG = DCI.DAG;
10167 
10168   EVT VecVT = Vec.getValueType();
10169   EVT EltVT = VecVT.getVectorElementType();
10170 
10171   if ((Vec.getOpcode() == ISD::FNEG ||
10172        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10173     SDLoc SL(N);
10174     EVT EltVT = N->getValueType(0);
10175     SDValue Idx = N->getOperand(1);
10176     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10177                               Vec.getOperand(0), Idx);
10178     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10179   }
10180 
10181   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10182   //    =>
10183   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10184   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10185   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10186   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10187     SDLoc SL(N);
10188     EVT EltVT = N->getValueType(0);
10189     SDValue Idx = N->getOperand(1);
10190     unsigned Opc = Vec.getOpcode();
10191 
10192     switch(Opc) {
10193     default:
10194       break;
10195       // TODO: Support other binary operations.
10196     case ISD::FADD:
10197     case ISD::FSUB:
10198     case ISD::FMUL:
10199     case ISD::ADD:
10200     case ISD::UMIN:
10201     case ISD::UMAX:
10202     case ISD::SMIN:
10203     case ISD::SMAX:
10204     case ISD::FMAXNUM:
10205     case ISD::FMINNUM:
10206     case ISD::FMAXNUM_IEEE:
10207     case ISD::FMINNUM_IEEE: {
10208       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10209                                  Vec.getOperand(0), Idx);
10210       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10211                                  Vec.getOperand(1), Idx);
10212 
10213       DCI.AddToWorklist(Elt0.getNode());
10214       DCI.AddToWorklist(Elt1.getNode());
10215       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10216     }
10217     }
10218   }
10219 
10220   unsigned VecSize = VecVT.getSizeInBits();
10221   unsigned EltSize = EltVT.getSizeInBits();
10222 
10223   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10224   if (::shouldExpandVectorDynExt(N)) {
10225     SDLoc SL(N);
10226     SDValue Idx = N->getOperand(1);
10227     SDValue V;
10228     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10229       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10230       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10231       if (I == 0)
10232         V = Elt;
10233       else
10234         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10235     }
10236     return V;
10237   }
10238 
10239   if (!DCI.isBeforeLegalize())
10240     return SDValue();
10241 
10242   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10243   // elements. This exposes more load reduction opportunities by replacing
10244   // multiple small extract_vector_elements with a single 32-bit extract.
10245   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10246   if (isa<MemSDNode>(Vec) &&
10247       EltSize <= 16 &&
10248       EltVT.isByteSized() &&
10249       VecSize > 32 &&
10250       VecSize % 32 == 0 &&
10251       Idx) {
10252     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10253 
10254     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10255     unsigned EltIdx = BitIndex / 32;
10256     unsigned LeftoverBitIdx = BitIndex % 32;
10257     SDLoc SL(N);
10258 
10259     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10260     DCI.AddToWorklist(Cast.getNode());
10261 
10262     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10263                               DAG.getConstant(EltIdx, SL, MVT::i32));
10264     DCI.AddToWorklist(Elt.getNode());
10265     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10266                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10267     DCI.AddToWorklist(Srl.getNode());
10268 
10269     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10270     DCI.AddToWorklist(Trunc.getNode());
10271     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10272   }
10273 
10274   return SDValue();
10275 }
10276 
10277 SDValue
10278 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10279                                                 DAGCombinerInfo &DCI) const {
10280   SDValue Vec = N->getOperand(0);
10281   SDValue Idx = N->getOperand(2);
10282   EVT VecVT = Vec.getValueType();
10283   EVT EltVT = VecVT.getVectorElementType();
10284 
10285   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10286   // => BUILD_VECTOR n x select (e, const-idx)
10287   if (!::shouldExpandVectorDynExt(N))
10288     return SDValue();
10289 
10290   SelectionDAG &DAG = DCI.DAG;
10291   SDLoc SL(N);
10292   SDValue Ins = N->getOperand(1);
10293   EVT IdxVT = Idx.getValueType();
10294 
10295   SmallVector<SDValue, 16> Ops;
10296   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10297     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10298     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10299     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10300     Ops.push_back(V);
10301   }
10302 
10303   return DAG.getBuildVector(VecVT, SL, Ops);
10304 }
10305 
10306 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10307                                           const SDNode *N0,
10308                                           const SDNode *N1) const {
10309   EVT VT = N0->getValueType(0);
10310 
10311   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10312   // support denormals ever.
10313   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10314        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10315         getSubtarget()->hasMadF16())) &&
10316        isOperationLegal(ISD::FMAD, VT))
10317     return ISD::FMAD;
10318 
10319   const TargetOptions &Options = DAG.getTarget().Options;
10320   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10321        (N0->getFlags().hasAllowContract() &&
10322         N1->getFlags().hasAllowContract())) &&
10323       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10324     return ISD::FMA;
10325   }
10326 
10327   return 0;
10328 }
10329 
10330 // For a reassociatable opcode perform:
10331 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10332 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10333                                                SelectionDAG &DAG) const {
10334   EVT VT = N->getValueType(0);
10335   if (VT != MVT::i32 && VT != MVT::i64)
10336     return SDValue();
10337 
10338   unsigned Opc = N->getOpcode();
10339   SDValue Op0 = N->getOperand(0);
10340   SDValue Op1 = N->getOperand(1);
10341 
10342   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10343     return SDValue();
10344 
10345   if (Op0->isDivergent())
10346     std::swap(Op0, Op1);
10347 
10348   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10349     return SDValue();
10350 
10351   SDValue Op2 = Op1.getOperand(1);
10352   Op1 = Op1.getOperand(0);
10353   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10354     return SDValue();
10355 
10356   if (Op1->isDivergent())
10357     std::swap(Op1, Op2);
10358 
10359   // If either operand is constant this will conflict with
10360   // DAGCombiner::ReassociateOps().
10361   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10362       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10363     return SDValue();
10364 
10365   SDLoc SL(N);
10366   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10367   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10368 }
10369 
10370 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10371                            EVT VT,
10372                            SDValue N0, SDValue N1, SDValue N2,
10373                            bool Signed) {
10374   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10375   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10376   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10377   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10378 }
10379 
10380 SDValue SITargetLowering::performAddCombine(SDNode *N,
10381                                             DAGCombinerInfo &DCI) const {
10382   SelectionDAG &DAG = DCI.DAG;
10383   EVT VT = N->getValueType(0);
10384   SDLoc SL(N);
10385   SDValue LHS = N->getOperand(0);
10386   SDValue RHS = N->getOperand(1);
10387 
10388   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10389       && Subtarget->hasMad64_32() &&
10390       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10391       VT.getScalarSizeInBits() <= 64) {
10392     if (LHS.getOpcode() != ISD::MUL)
10393       std::swap(LHS, RHS);
10394 
10395     SDValue MulLHS = LHS.getOperand(0);
10396     SDValue MulRHS = LHS.getOperand(1);
10397     SDValue AddRHS = RHS;
10398 
10399     // TODO: Maybe restrict if SGPR inputs.
10400     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10401         numBitsUnsigned(MulRHS, DAG) <= 32) {
10402       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10403       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10404       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10405       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10406     }
10407 
10408     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10409       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10410       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10411       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10412       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10413     }
10414 
10415     return SDValue();
10416   }
10417 
10418   if (SDValue V = reassociateScalarOps(N, DAG)) {
10419     return V;
10420   }
10421 
10422   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10423     return SDValue();
10424 
10425   // add x, zext (setcc) => addcarry x, 0, setcc
10426   // add x, sext (setcc) => subcarry x, 0, setcc
10427   unsigned Opc = LHS.getOpcode();
10428   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10429       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10430     std::swap(RHS, LHS);
10431 
10432   Opc = RHS.getOpcode();
10433   switch (Opc) {
10434   default: break;
10435   case ISD::ZERO_EXTEND:
10436   case ISD::SIGN_EXTEND:
10437   case ISD::ANY_EXTEND: {
10438     auto Cond = RHS.getOperand(0);
10439     // If this won't be a real VOPC output, we would still need to insert an
10440     // extra instruction anyway.
10441     if (!isBoolSGPR(Cond))
10442       break;
10443     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10444     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10445     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10446     return DAG.getNode(Opc, SL, VTList, Args);
10447   }
10448   case ISD::ADDCARRY: {
10449     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10450     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10451     if (!C || C->getZExtValue() != 0) break;
10452     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10453     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10454   }
10455   }
10456   return SDValue();
10457 }
10458 
10459 SDValue SITargetLowering::performSubCombine(SDNode *N,
10460                                             DAGCombinerInfo &DCI) const {
10461   SelectionDAG &DAG = DCI.DAG;
10462   EVT VT = N->getValueType(0);
10463 
10464   if (VT != MVT::i32)
10465     return SDValue();
10466 
10467   SDLoc SL(N);
10468   SDValue LHS = N->getOperand(0);
10469   SDValue RHS = N->getOperand(1);
10470 
10471   // sub x, zext (setcc) => subcarry x, 0, setcc
10472   // sub x, sext (setcc) => addcarry x, 0, setcc
10473   unsigned Opc = RHS.getOpcode();
10474   switch (Opc) {
10475   default: break;
10476   case ISD::ZERO_EXTEND:
10477   case ISD::SIGN_EXTEND:
10478   case ISD::ANY_EXTEND: {
10479     auto Cond = RHS.getOperand(0);
10480     // If this won't be a real VOPC output, we would still need to insert an
10481     // extra instruction anyway.
10482     if (!isBoolSGPR(Cond))
10483       break;
10484     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10485     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10486     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10487     return DAG.getNode(Opc, SL, VTList, Args);
10488   }
10489   }
10490 
10491   if (LHS.getOpcode() == ISD::SUBCARRY) {
10492     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10493     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10494     if (!C || !C->isNullValue())
10495       return SDValue();
10496     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10497     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10498   }
10499   return SDValue();
10500 }
10501 
10502 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10503   DAGCombinerInfo &DCI) const {
10504 
10505   if (N->getValueType(0) != MVT::i32)
10506     return SDValue();
10507 
10508   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10509   if (!C || C->getZExtValue() != 0)
10510     return SDValue();
10511 
10512   SelectionDAG &DAG = DCI.DAG;
10513   SDValue LHS = N->getOperand(0);
10514 
10515   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10516   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10517   unsigned LHSOpc = LHS.getOpcode();
10518   unsigned Opc = N->getOpcode();
10519   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10520       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10521     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10522     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10523   }
10524   return SDValue();
10525 }
10526 
10527 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10528                                              DAGCombinerInfo &DCI) const {
10529   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10530     return SDValue();
10531 
10532   SelectionDAG &DAG = DCI.DAG;
10533   EVT VT = N->getValueType(0);
10534 
10535   SDLoc SL(N);
10536   SDValue LHS = N->getOperand(0);
10537   SDValue RHS = N->getOperand(1);
10538 
10539   // These should really be instruction patterns, but writing patterns with
10540   // source modiifiers is a pain.
10541 
10542   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10543   if (LHS.getOpcode() == ISD::FADD) {
10544     SDValue A = LHS.getOperand(0);
10545     if (A == LHS.getOperand(1)) {
10546       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10547       if (FusedOp != 0) {
10548         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10549         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10550       }
10551     }
10552   }
10553 
10554   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10555   if (RHS.getOpcode() == ISD::FADD) {
10556     SDValue A = RHS.getOperand(0);
10557     if (A == RHS.getOperand(1)) {
10558       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10559       if (FusedOp != 0) {
10560         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10561         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10562       }
10563     }
10564   }
10565 
10566   return SDValue();
10567 }
10568 
10569 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10570                                              DAGCombinerInfo &DCI) const {
10571   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10572     return SDValue();
10573 
10574   SelectionDAG &DAG = DCI.DAG;
10575   SDLoc SL(N);
10576   EVT VT = N->getValueType(0);
10577   assert(!VT.isVector());
10578 
10579   // Try to get the fneg to fold into the source modifier. This undoes generic
10580   // DAG combines and folds them into the mad.
10581   //
10582   // Only do this if we are not trying to support denormals. v_mad_f32 does
10583   // not support denormals ever.
10584   SDValue LHS = N->getOperand(0);
10585   SDValue RHS = N->getOperand(1);
10586   if (LHS.getOpcode() == ISD::FADD) {
10587     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10588     SDValue A = LHS.getOperand(0);
10589     if (A == LHS.getOperand(1)) {
10590       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10591       if (FusedOp != 0){
10592         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10593         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10594 
10595         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10596       }
10597     }
10598   }
10599 
10600   if (RHS.getOpcode() == ISD::FADD) {
10601     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10602 
10603     SDValue A = RHS.getOperand(0);
10604     if (A == RHS.getOperand(1)) {
10605       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10606       if (FusedOp != 0){
10607         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10608         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10609       }
10610     }
10611   }
10612 
10613   return SDValue();
10614 }
10615 
10616 SDValue SITargetLowering::performFMACombine(SDNode *N,
10617                                             DAGCombinerInfo &DCI) const {
10618   SelectionDAG &DAG = DCI.DAG;
10619   EVT VT = N->getValueType(0);
10620   SDLoc SL(N);
10621 
10622   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10623     return SDValue();
10624 
10625   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10626   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10627   SDValue Op1 = N->getOperand(0);
10628   SDValue Op2 = N->getOperand(1);
10629   SDValue FMA = N->getOperand(2);
10630 
10631   if (FMA.getOpcode() != ISD::FMA ||
10632       Op1.getOpcode() != ISD::FP_EXTEND ||
10633       Op2.getOpcode() != ISD::FP_EXTEND)
10634     return SDValue();
10635 
10636   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10637   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10638   // is sufficient to allow generaing fdot2.
10639   const TargetOptions &Options = DAG.getTarget().Options;
10640   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10641       (N->getFlags().hasAllowContract() &&
10642        FMA->getFlags().hasAllowContract())) {
10643     Op1 = Op1.getOperand(0);
10644     Op2 = Op2.getOperand(0);
10645     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10646         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10647       return SDValue();
10648 
10649     SDValue Vec1 = Op1.getOperand(0);
10650     SDValue Idx1 = Op1.getOperand(1);
10651     SDValue Vec2 = Op2.getOperand(0);
10652 
10653     SDValue FMAOp1 = FMA.getOperand(0);
10654     SDValue FMAOp2 = FMA.getOperand(1);
10655     SDValue FMAAcc = FMA.getOperand(2);
10656 
10657     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10658         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10659       return SDValue();
10660 
10661     FMAOp1 = FMAOp1.getOperand(0);
10662     FMAOp2 = FMAOp2.getOperand(0);
10663     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10664         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10665       return SDValue();
10666 
10667     SDValue Vec3 = FMAOp1.getOperand(0);
10668     SDValue Vec4 = FMAOp2.getOperand(0);
10669     SDValue Idx2 = FMAOp1.getOperand(1);
10670 
10671     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10672         // Idx1 and Idx2 cannot be the same.
10673         Idx1 == Idx2)
10674       return SDValue();
10675 
10676     if (Vec1 == Vec2 || Vec3 == Vec4)
10677       return SDValue();
10678 
10679     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10680       return SDValue();
10681 
10682     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10683         (Vec1 == Vec4 && Vec2 == Vec3)) {
10684       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10685                          DAG.getTargetConstant(0, SL, MVT::i1));
10686     }
10687   }
10688   return SDValue();
10689 }
10690 
10691 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10692                                               DAGCombinerInfo &DCI) const {
10693   SelectionDAG &DAG = DCI.DAG;
10694   SDLoc SL(N);
10695 
10696   SDValue LHS = N->getOperand(0);
10697   SDValue RHS = N->getOperand(1);
10698   EVT VT = LHS.getValueType();
10699   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10700 
10701   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10702   if (!CRHS) {
10703     CRHS = dyn_cast<ConstantSDNode>(LHS);
10704     if (CRHS) {
10705       std::swap(LHS, RHS);
10706       CC = getSetCCSwappedOperands(CC);
10707     }
10708   }
10709 
10710   if (CRHS) {
10711     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10712         isBoolSGPR(LHS.getOperand(0))) {
10713       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10714       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10715       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10716       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10717       if ((CRHS->isAllOnesValue() &&
10718            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10719           (CRHS->isNullValue() &&
10720            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10721         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10722                            DAG.getConstant(-1, SL, MVT::i1));
10723       if ((CRHS->isAllOnesValue() &&
10724            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10725           (CRHS->isNullValue() &&
10726            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10727         return LHS.getOperand(0);
10728     }
10729 
10730     uint64_t CRHSVal = CRHS->getZExtValue();
10731     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10732         LHS.getOpcode() == ISD::SELECT &&
10733         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10734         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10735         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10736         isBoolSGPR(LHS.getOperand(0))) {
10737       // Given CT != FT:
10738       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10739       // setcc (select cc, CT, CF), CF, ne => cc
10740       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10741       // setcc (select cc, CT, CF), CT, eq => cc
10742       uint64_t CT = LHS.getConstantOperandVal(1);
10743       uint64_t CF = LHS.getConstantOperandVal(2);
10744 
10745       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10746           (CT == CRHSVal && CC == ISD::SETNE))
10747         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10748                            DAG.getConstant(-1, SL, MVT::i1));
10749       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10750           (CT == CRHSVal && CC == ISD::SETEQ))
10751         return LHS.getOperand(0);
10752     }
10753   }
10754 
10755   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10756                                            VT != MVT::f16))
10757     return SDValue();
10758 
10759   // Match isinf/isfinite pattern
10760   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10761   // (fcmp one (fabs x), inf) -> (fp_class x,
10762   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10763   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10764     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10765     if (!CRHS)
10766       return SDValue();
10767 
10768     const APFloat &APF = CRHS->getValueAPF();
10769     if (APF.isInfinity() && !APF.isNegative()) {
10770       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10771                                  SIInstrFlags::N_INFINITY;
10772       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10773                                     SIInstrFlags::P_ZERO |
10774                                     SIInstrFlags::N_NORMAL |
10775                                     SIInstrFlags::P_NORMAL |
10776                                     SIInstrFlags::N_SUBNORMAL |
10777                                     SIInstrFlags::P_SUBNORMAL;
10778       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10779       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10780                          DAG.getConstant(Mask, SL, MVT::i32));
10781     }
10782   }
10783 
10784   return SDValue();
10785 }
10786 
10787 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10788                                                      DAGCombinerInfo &DCI) const {
10789   SelectionDAG &DAG = DCI.DAG;
10790   SDLoc SL(N);
10791   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10792 
10793   SDValue Src = N->getOperand(0);
10794   SDValue Shift = N->getOperand(0);
10795 
10796   // TODO: Extend type shouldn't matter (assuming legal types).
10797   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10798     Shift = Shift.getOperand(0);
10799 
10800   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10801     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10802     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10803     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10804     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10805     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10806     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10807       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10808                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10809 
10810       unsigned ShiftOffset = 8 * Offset;
10811       if (Shift.getOpcode() == ISD::SHL)
10812         ShiftOffset -= C->getZExtValue();
10813       else
10814         ShiftOffset += C->getZExtValue();
10815 
10816       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10817         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10818                            MVT::f32, Shift);
10819       }
10820     }
10821   }
10822 
10823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10824   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10825   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10826     // We simplified Src. If this node is not dead, visit it again so it is
10827     // folded properly.
10828     if (N->getOpcode() != ISD::DELETED_NODE)
10829       DCI.AddToWorklist(N);
10830     return SDValue(N, 0);
10831   }
10832 
10833   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10834   if (SDValue DemandedSrc =
10835           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10836     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10837 
10838   return SDValue();
10839 }
10840 
10841 SDValue SITargetLowering::performClampCombine(SDNode *N,
10842                                               DAGCombinerInfo &DCI) const {
10843   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10844   if (!CSrc)
10845     return SDValue();
10846 
10847   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10848   const APFloat &F = CSrc->getValueAPF();
10849   APFloat Zero = APFloat::getZero(F.getSemantics());
10850   if (F < Zero ||
10851       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10852     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10853   }
10854 
10855   APFloat One(F.getSemantics(), "1.0");
10856   if (F > One)
10857     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10858 
10859   return SDValue(CSrc, 0);
10860 }
10861 
10862 
10863 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10864                                             DAGCombinerInfo &DCI) const {
10865   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10866     return SDValue();
10867   switch (N->getOpcode()) {
10868   case ISD::ADD:
10869     return performAddCombine(N, DCI);
10870   case ISD::SUB:
10871     return performSubCombine(N, DCI);
10872   case ISD::ADDCARRY:
10873   case ISD::SUBCARRY:
10874     return performAddCarrySubCarryCombine(N, DCI);
10875   case ISD::FADD:
10876     return performFAddCombine(N, DCI);
10877   case ISD::FSUB:
10878     return performFSubCombine(N, DCI);
10879   case ISD::SETCC:
10880     return performSetCCCombine(N, DCI);
10881   case ISD::FMAXNUM:
10882   case ISD::FMINNUM:
10883   case ISD::FMAXNUM_IEEE:
10884   case ISD::FMINNUM_IEEE:
10885   case ISD::SMAX:
10886   case ISD::SMIN:
10887   case ISD::UMAX:
10888   case ISD::UMIN:
10889   case AMDGPUISD::FMIN_LEGACY:
10890   case AMDGPUISD::FMAX_LEGACY:
10891     return performMinMaxCombine(N, DCI);
10892   case ISD::FMA:
10893     return performFMACombine(N, DCI);
10894   case ISD::AND:
10895     return performAndCombine(N, DCI);
10896   case ISD::OR:
10897     return performOrCombine(N, DCI);
10898   case ISD::XOR:
10899     return performXorCombine(N, DCI);
10900   case ISD::ZERO_EXTEND:
10901     return performZeroExtendCombine(N, DCI);
10902   case ISD::SIGN_EXTEND_INREG:
10903     return performSignExtendInRegCombine(N , DCI);
10904   case AMDGPUISD::FP_CLASS:
10905     return performClassCombine(N, DCI);
10906   case ISD::FCANONICALIZE:
10907     return performFCanonicalizeCombine(N, DCI);
10908   case AMDGPUISD::RCP:
10909     return performRcpCombine(N, DCI);
10910   case AMDGPUISD::FRACT:
10911   case AMDGPUISD::RSQ:
10912   case AMDGPUISD::RCP_LEGACY:
10913   case AMDGPUISD::RCP_IFLAG:
10914   case AMDGPUISD::RSQ_CLAMP:
10915   case AMDGPUISD::LDEXP: {
10916     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10917     SDValue Src = N->getOperand(0);
10918     if (Src.isUndef())
10919       return Src;
10920     break;
10921   }
10922   case ISD::SINT_TO_FP:
10923   case ISD::UINT_TO_FP:
10924     return performUCharToFloatCombine(N, DCI);
10925   case AMDGPUISD::CVT_F32_UBYTE0:
10926   case AMDGPUISD::CVT_F32_UBYTE1:
10927   case AMDGPUISD::CVT_F32_UBYTE2:
10928   case AMDGPUISD::CVT_F32_UBYTE3:
10929     return performCvtF32UByteNCombine(N, DCI);
10930   case AMDGPUISD::FMED3:
10931     return performFMed3Combine(N, DCI);
10932   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10933     return performCvtPkRTZCombine(N, DCI);
10934   case AMDGPUISD::CLAMP:
10935     return performClampCombine(N, DCI);
10936   case ISD::SCALAR_TO_VECTOR: {
10937     SelectionDAG &DAG = DCI.DAG;
10938     EVT VT = N->getValueType(0);
10939 
10940     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10941     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10942       SDLoc SL(N);
10943       SDValue Src = N->getOperand(0);
10944       EVT EltVT = Src.getValueType();
10945       if (EltVT == MVT::f16)
10946         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10947 
10948       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10949       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10950     }
10951 
10952     break;
10953   }
10954   case ISD::EXTRACT_VECTOR_ELT:
10955     return performExtractVectorEltCombine(N, DCI);
10956   case ISD::INSERT_VECTOR_ELT:
10957     return performInsertVectorEltCombine(N, DCI);
10958   case ISD::LOAD: {
10959     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10960       return Widended;
10961     LLVM_FALLTHROUGH;
10962   }
10963   default: {
10964     if (!DCI.isBeforeLegalize()) {
10965       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10966         return performMemSDNodeCombine(MemNode, DCI);
10967     }
10968 
10969     break;
10970   }
10971   }
10972 
10973   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10974 }
10975 
10976 /// Helper function for adjustWritemask
10977 static unsigned SubIdx2Lane(unsigned Idx) {
10978   switch (Idx) {
10979   default: return ~0u;
10980   case AMDGPU::sub0: return 0;
10981   case AMDGPU::sub1: return 1;
10982   case AMDGPU::sub2: return 2;
10983   case AMDGPU::sub3: return 3;
10984   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10985   }
10986 }
10987 
10988 /// Adjust the writemask of MIMG instructions
10989 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10990                                           SelectionDAG &DAG) const {
10991   unsigned Opcode = Node->getMachineOpcode();
10992 
10993   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10994   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10995   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10996     return Node; // not implemented for D16
10997 
10998   SDNode *Users[5] = { nullptr };
10999   unsigned Lane = 0;
11000   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11001   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11002   unsigned NewDmask = 0;
11003   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11004   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11005   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11006                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11007   unsigned TFCLane = 0;
11008   bool HasChain = Node->getNumValues() > 1;
11009 
11010   if (OldDmask == 0) {
11011     // These are folded out, but on the chance it happens don't assert.
11012     return Node;
11013   }
11014 
11015   unsigned OldBitsSet = countPopulation(OldDmask);
11016   // Work out which is the TFE/LWE lane if that is enabled.
11017   if (UsesTFC) {
11018     TFCLane = OldBitsSet;
11019   }
11020 
11021   // Try to figure out the used register components
11022   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11023        I != E; ++I) {
11024 
11025     // Don't look at users of the chain.
11026     if (I.getUse().getResNo() != 0)
11027       continue;
11028 
11029     // Abort if we can't understand the usage
11030     if (!I->isMachineOpcode() ||
11031         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11032       return Node;
11033 
11034     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11035     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11036     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11037     // set, etc.
11038     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11039     if (Lane == ~0u)
11040       return Node;
11041 
11042     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11043     if (UsesTFC && Lane == TFCLane) {
11044       Users[Lane] = *I;
11045     } else {
11046       // Set which texture component corresponds to the lane.
11047       unsigned Comp;
11048       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11049         Comp = countTrailingZeros(Dmask);
11050         Dmask &= ~(1 << Comp);
11051       }
11052 
11053       // Abort if we have more than one user per component.
11054       if (Users[Lane])
11055         return Node;
11056 
11057       Users[Lane] = *I;
11058       NewDmask |= 1 << Comp;
11059     }
11060   }
11061 
11062   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11063   bool NoChannels = !NewDmask;
11064   if (NoChannels) {
11065     if (!UsesTFC) {
11066       // No uses of the result and not using TFC. Then do nothing.
11067       return Node;
11068     }
11069     // If the original dmask has one channel - then nothing to do
11070     if (OldBitsSet == 1)
11071       return Node;
11072     // Use an arbitrary dmask - required for the instruction to work
11073     NewDmask = 1;
11074   }
11075   // Abort if there's no change
11076   if (NewDmask == OldDmask)
11077     return Node;
11078 
11079   unsigned BitsSet = countPopulation(NewDmask);
11080 
11081   // Check for TFE or LWE - increase the number of channels by one to account
11082   // for the extra return value
11083   // This will need adjustment for D16 if this is also included in
11084   // adjustWriteMask (this function) but at present D16 are excluded.
11085   unsigned NewChannels = BitsSet + UsesTFC;
11086 
11087   int NewOpcode =
11088       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11089   assert(NewOpcode != -1 &&
11090          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11091          "failed to find equivalent MIMG op");
11092 
11093   // Adjust the writemask in the node
11094   SmallVector<SDValue, 12> Ops;
11095   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11096   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11097   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11098 
11099   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11100 
11101   MVT ResultVT = NewChannels == 1 ?
11102     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11103                            NewChannels == 5 ? 8 : NewChannels);
11104   SDVTList NewVTList = HasChain ?
11105     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11106 
11107 
11108   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11109                                               NewVTList, Ops);
11110 
11111   if (HasChain) {
11112     // Update chain.
11113     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11114     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11115   }
11116 
11117   if (NewChannels == 1) {
11118     assert(Node->hasNUsesOfValue(1, 0));
11119     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11120                                       SDLoc(Node), Users[Lane]->getValueType(0),
11121                                       SDValue(NewNode, 0));
11122     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11123     return nullptr;
11124   }
11125 
11126   // Update the users of the node with the new indices
11127   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11128     SDNode *User = Users[i];
11129     if (!User) {
11130       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11131       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11132       if (i || !NoChannels)
11133         continue;
11134     } else {
11135       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11136       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11137     }
11138 
11139     switch (Idx) {
11140     default: break;
11141     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11142     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11143     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11144     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11145     }
11146   }
11147 
11148   DAG.RemoveDeadNode(Node);
11149   return nullptr;
11150 }
11151 
11152 static bool isFrameIndexOp(SDValue Op) {
11153   if (Op.getOpcode() == ISD::AssertZext)
11154     Op = Op.getOperand(0);
11155 
11156   return isa<FrameIndexSDNode>(Op);
11157 }
11158 
11159 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11160 /// with frame index operands.
11161 /// LLVM assumes that inputs are to these instructions are registers.
11162 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11163                                                         SelectionDAG &DAG) const {
11164   if (Node->getOpcode() == ISD::CopyToReg) {
11165     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11166     SDValue SrcVal = Node->getOperand(2);
11167 
11168     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11169     // to try understanding copies to physical registers.
11170     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11171       SDLoc SL(Node);
11172       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11173       SDValue VReg = DAG.getRegister(
11174         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11175 
11176       SDNode *Glued = Node->getGluedNode();
11177       SDValue ToVReg
11178         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11179                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11180       SDValue ToResultReg
11181         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11182                            VReg, ToVReg.getValue(1));
11183       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11184       DAG.RemoveDeadNode(Node);
11185       return ToResultReg.getNode();
11186     }
11187   }
11188 
11189   SmallVector<SDValue, 8> Ops;
11190   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11191     if (!isFrameIndexOp(Node->getOperand(i))) {
11192       Ops.push_back(Node->getOperand(i));
11193       continue;
11194     }
11195 
11196     SDLoc DL(Node);
11197     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11198                                      Node->getOperand(i).getValueType(),
11199                                      Node->getOperand(i)), 0));
11200   }
11201 
11202   return DAG.UpdateNodeOperands(Node, Ops);
11203 }
11204 
11205 /// Fold the instructions after selecting them.
11206 /// Returns null if users were already updated.
11207 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11208                                           SelectionDAG &DAG) const {
11209   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11210   unsigned Opcode = Node->getMachineOpcode();
11211 
11212   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11213       !TII->isGather4(Opcode) &&
11214       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11215     return adjustWritemask(Node, DAG);
11216   }
11217 
11218   if (Opcode == AMDGPU::INSERT_SUBREG ||
11219       Opcode == AMDGPU::REG_SEQUENCE) {
11220     legalizeTargetIndependentNode(Node, DAG);
11221     return Node;
11222   }
11223 
11224   switch (Opcode) {
11225   case AMDGPU::V_DIV_SCALE_F32_e64:
11226   case AMDGPU::V_DIV_SCALE_F64_e64: {
11227     // Satisfy the operand register constraint when one of the inputs is
11228     // undefined. Ordinarily each undef value will have its own implicit_def of
11229     // a vreg, so force these to use a single register.
11230     SDValue Src0 = Node->getOperand(1);
11231     SDValue Src1 = Node->getOperand(3);
11232     SDValue Src2 = Node->getOperand(5);
11233 
11234     if ((Src0.isMachineOpcode() &&
11235          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11236         (Src0 == Src1 || Src0 == Src2))
11237       break;
11238 
11239     MVT VT = Src0.getValueType().getSimpleVT();
11240     const TargetRegisterClass *RC =
11241         getRegClassFor(VT, Src0.getNode()->isDivergent());
11242 
11243     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11244     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11245 
11246     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11247                                       UndefReg, Src0, SDValue());
11248 
11249     // src0 must be the same register as src1 or src2, even if the value is
11250     // undefined, so make sure we don't violate this constraint.
11251     if (Src0.isMachineOpcode() &&
11252         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11253       if (Src1.isMachineOpcode() &&
11254           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11255         Src0 = Src1;
11256       else if (Src2.isMachineOpcode() &&
11257                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11258         Src0 = Src2;
11259       else {
11260         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11261         Src0 = UndefReg;
11262         Src1 = UndefReg;
11263       }
11264     } else
11265       break;
11266 
11267     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11268     Ops[1] = Src0;
11269     Ops[3] = Src1;
11270     Ops[5] = Src2;
11271     Ops.push_back(ImpDef.getValue(1));
11272     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11273   }
11274   default:
11275     break;
11276   }
11277 
11278   return Node;
11279 }
11280 
11281 // Any MIMG instructions that use tfe or lwe require an initialization of the
11282 // result register that will be written in the case of a memory access failure.
11283 // The required code is also added to tie this init code to the result of the
11284 // img instruction.
11285 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11286   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11287   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11288   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11289   MachineBasicBlock &MBB = *MI.getParent();
11290 
11291   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11292   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11293   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11294 
11295   if (!TFE && !LWE) // intersect_ray
11296     return;
11297 
11298   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11299   unsigned LWEVal = LWE->getImm();
11300   unsigned D16Val = D16 ? D16->getImm() : 0;
11301 
11302   if (!TFEVal && !LWEVal)
11303     return;
11304 
11305   // At least one of TFE or LWE are non-zero
11306   // We have to insert a suitable initialization of the result value and
11307   // tie this to the dest of the image instruction.
11308 
11309   const DebugLoc &DL = MI.getDebugLoc();
11310 
11311   int DstIdx =
11312       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11313 
11314   // Calculate which dword we have to initialize to 0.
11315   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11316 
11317   // check that dmask operand is found.
11318   assert(MO_Dmask && "Expected dmask operand in instruction");
11319 
11320   unsigned dmask = MO_Dmask->getImm();
11321   // Determine the number of active lanes taking into account the
11322   // Gather4 special case
11323   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11324 
11325   bool Packed = !Subtarget->hasUnpackedD16VMem();
11326 
11327   unsigned InitIdx =
11328       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11329 
11330   // Abandon attempt if the dst size isn't large enough
11331   // - this is in fact an error but this is picked up elsewhere and
11332   // reported correctly.
11333   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11334   if (DstSize < InitIdx)
11335     return;
11336 
11337   // Create a register for the intialization value.
11338   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11339   unsigned NewDst = 0; // Final initialized value will be in here
11340 
11341   // If PRTStrictNull feature is enabled (the default) then initialize
11342   // all the result registers to 0, otherwise just the error indication
11343   // register (VGPRn+1)
11344   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11345   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11346 
11347   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11348   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11349     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11350     // Initialize dword
11351     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11352     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11353       .addImm(0);
11354     // Insert into the super-reg
11355     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11356       .addReg(PrevDst)
11357       .addReg(SubReg)
11358       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11359 
11360     PrevDst = NewDst;
11361   }
11362 
11363   // Add as an implicit operand
11364   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11365 
11366   // Tie the just added implicit operand to the dst
11367   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11368 }
11369 
11370 /// Assign the register class depending on the number of
11371 /// bits set in the writemask
11372 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11373                                                      SDNode *Node) const {
11374   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11375 
11376   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11377 
11378   if (TII->isVOP3(MI.getOpcode())) {
11379     // Make sure constant bus requirements are respected.
11380     TII->legalizeOperandsVOP3(MRI, MI);
11381 
11382     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11383     // This saves a chain-copy of registers and better ballance register
11384     // use between vgpr and agpr as agpr tuples tend to be big.
11385     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11386       unsigned Opc = MI.getOpcode();
11387       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11388       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11389                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11390         if (I == -1)
11391           break;
11392         MachineOperand &Op = MI.getOperand(I);
11393         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11394              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11395             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11396           continue;
11397         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11398         if (!Src || !Src->isCopy() ||
11399             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11400           continue;
11401         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11402         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11403         // All uses of agpr64 and agpr32 can also accept vgpr except for
11404         // v_accvgpr_read, but we do not produce agpr reads during selection,
11405         // so no use checks are needed.
11406         MRI.setRegClass(Op.getReg(), NewRC);
11407       }
11408     }
11409 
11410     return;
11411   }
11412 
11413   // Replace unused atomics with the no return version.
11414   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11415   if (NoRetAtomicOp != -1) {
11416     if (!Node->hasAnyUseOfValue(0)) {
11417       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11418                                                AMDGPU::OpName::cpol);
11419       if (CPolIdx != -1) {
11420         MachineOperand &CPol = MI.getOperand(CPolIdx);
11421         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11422       }
11423       MI.RemoveOperand(0);
11424       MI.setDesc(TII->get(NoRetAtomicOp));
11425       return;
11426     }
11427 
11428     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11429     // instruction, because the return type of these instructions is a vec2 of
11430     // the memory type, so it can be tied to the input operand.
11431     // This means these instructions always have a use, so we need to add a
11432     // special case to check if the atomic has only one extract_subreg use,
11433     // which itself has no uses.
11434     if ((Node->hasNUsesOfValue(1, 0) &&
11435          Node->use_begin()->isMachineOpcode() &&
11436          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11437          !Node->use_begin()->hasAnyUseOfValue(0))) {
11438       Register Def = MI.getOperand(0).getReg();
11439 
11440       // Change this into a noret atomic.
11441       MI.setDesc(TII->get(NoRetAtomicOp));
11442       MI.RemoveOperand(0);
11443 
11444       // If we only remove the def operand from the atomic instruction, the
11445       // extract_subreg will be left with a use of a vreg without a def.
11446       // So we need to insert an implicit_def to avoid machine verifier
11447       // errors.
11448       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11449               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11450     }
11451     return;
11452   }
11453 
11454   if (TII->isMIMG(MI) && !MI.mayStore())
11455     AddIMGInit(MI);
11456 }
11457 
11458 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11459                               uint64_t Val) {
11460   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11461   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11462 }
11463 
11464 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11465                                                 const SDLoc &DL,
11466                                                 SDValue Ptr) const {
11467   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11468 
11469   // Build the half of the subregister with the constants before building the
11470   // full 128-bit register. If we are building multiple resource descriptors,
11471   // this will allow CSEing of the 2-component register.
11472   const SDValue Ops0[] = {
11473     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11474     buildSMovImm32(DAG, DL, 0),
11475     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11476     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11477     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11478   };
11479 
11480   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11481                                                 MVT::v2i32, Ops0), 0);
11482 
11483   // Combine the constants and the pointer.
11484   const SDValue Ops1[] = {
11485     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11486     Ptr,
11487     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11488     SubRegHi,
11489     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11490   };
11491 
11492   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11493 }
11494 
11495 /// Return a resource descriptor with the 'Add TID' bit enabled
11496 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11497 ///        of the resource descriptor) to create an offset, which is added to
11498 ///        the resource pointer.
11499 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11500                                            SDValue Ptr, uint32_t RsrcDword1,
11501                                            uint64_t RsrcDword2And3) const {
11502   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11503   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11504   if (RsrcDword1) {
11505     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11506                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11507                     0);
11508   }
11509 
11510   SDValue DataLo = buildSMovImm32(DAG, DL,
11511                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11512   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11513 
11514   const SDValue Ops[] = {
11515     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11516     PtrLo,
11517     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11518     PtrHi,
11519     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11520     DataLo,
11521     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11522     DataHi,
11523     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11524   };
11525 
11526   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11527 }
11528 
11529 //===----------------------------------------------------------------------===//
11530 //                         SI Inline Assembly Support
11531 //===----------------------------------------------------------------------===//
11532 
11533 std::pair<unsigned, const TargetRegisterClass *>
11534 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11535                                                StringRef Constraint,
11536                                                MVT VT) const {
11537   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11538 
11539   const TargetRegisterClass *RC = nullptr;
11540   if (Constraint.size() == 1) {
11541     const unsigned BitWidth = VT.getSizeInBits();
11542     switch (Constraint[0]) {
11543     default:
11544       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11545     case 's':
11546     case 'r':
11547       switch (BitWidth) {
11548       case 16:
11549         RC = &AMDGPU::SReg_32RegClass;
11550         break;
11551       case 64:
11552         RC = &AMDGPU::SGPR_64RegClass;
11553         break;
11554       default:
11555         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11556         if (!RC)
11557           return std::make_pair(0U, nullptr);
11558         break;
11559       }
11560       break;
11561     case 'v':
11562       switch (BitWidth) {
11563       case 16:
11564         RC = &AMDGPU::VGPR_32RegClass;
11565         break;
11566       default:
11567         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11568         if (!RC)
11569           return std::make_pair(0U, nullptr);
11570         break;
11571       }
11572       break;
11573     case 'a':
11574       if (!Subtarget->hasMAIInsts())
11575         break;
11576       switch (BitWidth) {
11577       case 16:
11578         RC = &AMDGPU::AGPR_32RegClass;
11579         break;
11580       default:
11581         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11582         if (!RC)
11583           return std::make_pair(0U, nullptr);
11584         break;
11585       }
11586       break;
11587     }
11588     // We actually support i128, i16 and f16 as inline parameters
11589     // even if they are not reported as legal
11590     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11591                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11592       return std::make_pair(0U, RC);
11593   }
11594 
11595   if (Constraint.size() > 1) {
11596     if (Constraint[1] == 'v') {
11597       RC = &AMDGPU::VGPR_32RegClass;
11598     } else if (Constraint[1] == 's') {
11599       RC = &AMDGPU::SGPR_32RegClass;
11600     } else if (Constraint[1] == 'a') {
11601       RC = &AMDGPU::AGPR_32RegClass;
11602     }
11603 
11604     if (RC) {
11605       uint32_t Idx;
11606       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11607       if (!Failed && Idx < RC->getNumRegs())
11608         return std::make_pair(RC->getRegister(Idx), RC);
11609     }
11610   }
11611 
11612   // FIXME: Returns VS_32 for physical SGPR constraints
11613   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11614 }
11615 
11616 static bool isImmConstraint(StringRef Constraint) {
11617   if (Constraint.size() == 1) {
11618     switch (Constraint[0]) {
11619     default: break;
11620     case 'I':
11621     case 'J':
11622     case 'A':
11623     case 'B':
11624     case 'C':
11625       return true;
11626     }
11627   } else if (Constraint == "DA" ||
11628              Constraint == "DB") {
11629     return true;
11630   }
11631   return false;
11632 }
11633 
11634 SITargetLowering::ConstraintType
11635 SITargetLowering::getConstraintType(StringRef Constraint) const {
11636   if (Constraint.size() == 1) {
11637     switch (Constraint[0]) {
11638     default: break;
11639     case 's':
11640     case 'v':
11641     case 'a':
11642       return C_RegisterClass;
11643     }
11644   }
11645   if (isImmConstraint(Constraint)) {
11646     return C_Other;
11647   }
11648   return TargetLowering::getConstraintType(Constraint);
11649 }
11650 
11651 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11652   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11653     Val = Val & maskTrailingOnes<uint64_t>(Size);
11654   }
11655   return Val;
11656 }
11657 
11658 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11659                                                     std::string &Constraint,
11660                                                     std::vector<SDValue> &Ops,
11661                                                     SelectionDAG &DAG) const {
11662   if (isImmConstraint(Constraint)) {
11663     uint64_t Val;
11664     if (getAsmOperandConstVal(Op, Val) &&
11665         checkAsmConstraintVal(Op, Constraint, Val)) {
11666       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11667       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11668     }
11669   } else {
11670     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11671   }
11672 }
11673 
11674 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11675   unsigned Size = Op.getScalarValueSizeInBits();
11676   if (Size > 64)
11677     return false;
11678 
11679   if (Size == 16 && !Subtarget->has16BitInsts())
11680     return false;
11681 
11682   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11683     Val = C->getSExtValue();
11684     return true;
11685   }
11686   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11687     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11688     return true;
11689   }
11690   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11691     if (Size != 16 || Op.getNumOperands() != 2)
11692       return false;
11693     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11694       return false;
11695     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11696       Val = C->getSExtValue();
11697       return true;
11698     }
11699     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11700       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11701       return true;
11702     }
11703   }
11704 
11705   return false;
11706 }
11707 
11708 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11709                                              const std::string &Constraint,
11710                                              uint64_t Val) const {
11711   if (Constraint.size() == 1) {
11712     switch (Constraint[0]) {
11713     case 'I':
11714       return AMDGPU::isInlinableIntLiteral(Val);
11715     case 'J':
11716       return isInt<16>(Val);
11717     case 'A':
11718       return checkAsmConstraintValA(Op, Val);
11719     case 'B':
11720       return isInt<32>(Val);
11721     case 'C':
11722       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11723              AMDGPU::isInlinableIntLiteral(Val);
11724     default:
11725       break;
11726     }
11727   } else if (Constraint.size() == 2) {
11728     if (Constraint == "DA") {
11729       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11730       int64_t LoBits = static_cast<int32_t>(Val);
11731       return checkAsmConstraintValA(Op, HiBits, 32) &&
11732              checkAsmConstraintValA(Op, LoBits, 32);
11733     }
11734     if (Constraint == "DB") {
11735       return true;
11736     }
11737   }
11738   llvm_unreachable("Invalid asm constraint");
11739 }
11740 
11741 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11742                                               uint64_t Val,
11743                                               unsigned MaxSize) const {
11744   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11745   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11746   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11747       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11748       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11749     return true;
11750   }
11751   return false;
11752 }
11753 
11754 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11755   switch (UnalignedClassID) {
11756   case AMDGPU::VReg_64RegClassID:
11757     return AMDGPU::VReg_64_Align2RegClassID;
11758   case AMDGPU::VReg_96RegClassID:
11759     return AMDGPU::VReg_96_Align2RegClassID;
11760   case AMDGPU::VReg_128RegClassID:
11761     return AMDGPU::VReg_128_Align2RegClassID;
11762   case AMDGPU::VReg_160RegClassID:
11763     return AMDGPU::VReg_160_Align2RegClassID;
11764   case AMDGPU::VReg_192RegClassID:
11765     return AMDGPU::VReg_192_Align2RegClassID;
11766   case AMDGPU::VReg_256RegClassID:
11767     return AMDGPU::VReg_256_Align2RegClassID;
11768   case AMDGPU::VReg_512RegClassID:
11769     return AMDGPU::VReg_512_Align2RegClassID;
11770   case AMDGPU::VReg_1024RegClassID:
11771     return AMDGPU::VReg_1024_Align2RegClassID;
11772   case AMDGPU::AReg_64RegClassID:
11773     return AMDGPU::AReg_64_Align2RegClassID;
11774   case AMDGPU::AReg_96RegClassID:
11775     return AMDGPU::AReg_96_Align2RegClassID;
11776   case AMDGPU::AReg_128RegClassID:
11777     return AMDGPU::AReg_128_Align2RegClassID;
11778   case AMDGPU::AReg_160RegClassID:
11779     return AMDGPU::AReg_160_Align2RegClassID;
11780   case AMDGPU::AReg_192RegClassID:
11781     return AMDGPU::AReg_192_Align2RegClassID;
11782   case AMDGPU::AReg_256RegClassID:
11783     return AMDGPU::AReg_256_Align2RegClassID;
11784   case AMDGPU::AReg_512RegClassID:
11785     return AMDGPU::AReg_512_Align2RegClassID;
11786   case AMDGPU::AReg_1024RegClassID:
11787     return AMDGPU::AReg_1024_Align2RegClassID;
11788   default:
11789     return -1;
11790   }
11791 }
11792 
11793 // Figure out which registers should be reserved for stack access. Only after
11794 // the function is legalized do we know all of the non-spill stack objects or if
11795 // calls are present.
11796 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11797   MachineRegisterInfo &MRI = MF.getRegInfo();
11798   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11799   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11800   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11801   const SIInstrInfo *TII = ST.getInstrInfo();
11802 
11803   if (Info->isEntryFunction()) {
11804     // Callable functions have fixed registers used for stack access.
11805     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11806   }
11807 
11808   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11809                              Info->getStackPtrOffsetReg()));
11810   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11811     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11812 
11813   // We need to worry about replacing the default register with itself in case
11814   // of MIR testcases missing the MFI.
11815   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11816     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11817 
11818   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11819     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11820 
11821   Info->limitOccupancy(MF);
11822 
11823   if (ST.isWave32() && !MF.empty()) {
11824     for (auto &MBB : MF) {
11825       for (auto &MI : MBB) {
11826         TII->fixImplicitOperands(MI);
11827       }
11828     }
11829   }
11830 
11831   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11832   // classes if required. Ideally the register class constraints would differ
11833   // per-subtarget, but there's no easy way to achieve that right now. This is
11834   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11835   // from using them as the register class for legal types.
11836   if (ST.needsAlignedVGPRs()) {
11837     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11838       const Register Reg = Register::index2VirtReg(I);
11839       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11840       if (!RC)
11841         continue;
11842       int NewClassID = getAlignedAGPRClassID(RC->getID());
11843       if (NewClassID != -1)
11844         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11845     }
11846   }
11847 
11848   TargetLoweringBase::finalizeLowering(MF);
11849 
11850   // Allocate a VGPR for future SGPR Spill if
11851   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11852   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11853   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11854       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11855     Info->reserveVGPRforSGPRSpills(MF);
11856 }
11857 
11858 void SITargetLowering::computeKnownBitsForFrameIndex(
11859   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11860   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11861 
11862   // Set the high bits to zero based on the maximum allowed scratch size per
11863   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11864   // calculation won't overflow, so assume the sign bit is never set.
11865   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11866 }
11867 
11868 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11869                                    KnownBits &Known, unsigned Dim) {
11870   unsigned MaxValue =
11871       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11872   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11873 }
11874 
11875 void SITargetLowering::computeKnownBitsForTargetInstr(
11876     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11877     const MachineRegisterInfo &MRI, unsigned Depth) const {
11878   const MachineInstr *MI = MRI.getVRegDef(R);
11879   switch (MI->getOpcode()) {
11880   case AMDGPU::G_INTRINSIC: {
11881     switch (MI->getIntrinsicID()) {
11882     case Intrinsic::amdgcn_workitem_id_x:
11883       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11884       break;
11885     case Intrinsic::amdgcn_workitem_id_y:
11886       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11887       break;
11888     case Intrinsic::amdgcn_workitem_id_z:
11889       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11890       break;
11891     case Intrinsic::amdgcn_mbcnt_lo:
11892     case Intrinsic::amdgcn_mbcnt_hi: {
11893       // These return at most the wavefront size - 1.
11894       unsigned Size = MRI.getType(R).getSizeInBits();
11895       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11896       break;
11897     }
11898     case Intrinsic::amdgcn_groupstaticsize: {
11899       // We can report everything over the maximum size as 0. We can't report
11900       // based on the actual size because we don't know if it's accurate or not
11901       // at any given point.
11902       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11903       break;
11904     }
11905     }
11906     break;
11907   }
11908   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11909     Known.Zero.setHighBits(24);
11910     break;
11911   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11912     Known.Zero.setHighBits(16);
11913     break;
11914   }
11915 }
11916 
11917 Align SITargetLowering::computeKnownAlignForTargetInstr(
11918   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11919   unsigned Depth) const {
11920   const MachineInstr *MI = MRI.getVRegDef(R);
11921   switch (MI->getOpcode()) {
11922   case AMDGPU::G_INTRINSIC:
11923   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11924     // FIXME: Can this move to generic code? What about the case where the call
11925     // site specifies a lower alignment?
11926     Intrinsic::ID IID = MI->getIntrinsicID();
11927     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11928     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11929     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11930       return *RetAlign;
11931     return Align(1);
11932   }
11933   default:
11934     return Align(1);
11935   }
11936 }
11937 
11938 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11939   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11940   const Align CacheLineAlign = Align(64);
11941 
11942   // Pre-GFX10 target did not benefit from loop alignment
11943   if (!ML || DisableLoopAlignment ||
11944       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11945       getSubtarget()->hasInstFwdPrefetchBug())
11946     return PrefAlign;
11947 
11948   // On GFX10 I$ is 4 x 64 bytes cache lines.
11949   // By default prefetcher keeps one cache line behind and reads two ahead.
11950   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11951   // behind and one ahead.
11952   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11953   // If loop fits 64 bytes it always spans no more than two cache lines and
11954   // does not need an alignment.
11955   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11956   // Else if loop is less or equal 192 bytes we need two lines behind.
11957 
11958   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11959   const MachineBasicBlock *Header = ML->getHeader();
11960   if (Header->getAlignment() != PrefAlign)
11961     return Header->getAlignment(); // Already processed.
11962 
11963   unsigned LoopSize = 0;
11964   for (const MachineBasicBlock *MBB : ML->blocks()) {
11965     // If inner loop block is aligned assume in average half of the alignment
11966     // size to be added as nops.
11967     if (MBB != Header)
11968       LoopSize += MBB->getAlignment().value() / 2;
11969 
11970     for (const MachineInstr &MI : *MBB) {
11971       LoopSize += TII->getInstSizeInBytes(MI);
11972       if (LoopSize > 192)
11973         return PrefAlign;
11974     }
11975   }
11976 
11977   if (LoopSize <= 64)
11978     return PrefAlign;
11979 
11980   if (LoopSize <= 128)
11981     return CacheLineAlign;
11982 
11983   // If any of parent loops is surrounded by prefetch instructions do not
11984   // insert new for inner loop, which would reset parent's settings.
11985   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11986     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11987       auto I = Exit->getFirstNonDebugInstr();
11988       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11989         return CacheLineAlign;
11990     }
11991   }
11992 
11993   MachineBasicBlock *Pre = ML->getLoopPreheader();
11994   MachineBasicBlock *Exit = ML->getExitBlock();
11995 
11996   if (Pre && Exit) {
11997     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11998             TII->get(AMDGPU::S_INST_PREFETCH))
11999       .addImm(1); // prefetch 2 lines behind PC
12000 
12001     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12002             TII->get(AMDGPU::S_INST_PREFETCH))
12003       .addImm(2); // prefetch 1 line behind PC
12004   }
12005 
12006   return CacheLineAlign;
12007 }
12008 
12009 LLVM_ATTRIBUTE_UNUSED
12010 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12011   assert(N->getOpcode() == ISD::CopyFromReg);
12012   do {
12013     // Follow the chain until we find an INLINEASM node.
12014     N = N->getOperand(0).getNode();
12015     if (N->getOpcode() == ISD::INLINEASM ||
12016         N->getOpcode() == ISD::INLINEASM_BR)
12017       return true;
12018   } while (N->getOpcode() == ISD::CopyFromReg);
12019   return false;
12020 }
12021 
12022 bool SITargetLowering::isSDNodeSourceOfDivergence(
12023     const SDNode *N, FunctionLoweringInfo *FLI,
12024     LegacyDivergenceAnalysis *KDA) const {
12025   switch (N->getOpcode()) {
12026   case ISD::CopyFromReg: {
12027     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12028     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12029     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12030     Register Reg = R->getReg();
12031 
12032     // FIXME: Why does this need to consider isLiveIn?
12033     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12034       return !TRI->isSGPRReg(MRI, Reg);
12035 
12036     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12037       return KDA->isDivergent(V);
12038 
12039     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12040     return !TRI->isSGPRReg(MRI, Reg);
12041   }
12042   case ISD::LOAD: {
12043     const LoadSDNode *L = cast<LoadSDNode>(N);
12044     unsigned AS = L->getAddressSpace();
12045     // A flat load may access private memory.
12046     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12047   }
12048   case ISD::CALLSEQ_END:
12049     return true;
12050   case ISD::INTRINSIC_WO_CHAIN:
12051     return AMDGPU::isIntrinsicSourceOfDivergence(
12052         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12053   case ISD::INTRINSIC_W_CHAIN:
12054     return AMDGPU::isIntrinsicSourceOfDivergence(
12055         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12056   case AMDGPUISD::ATOMIC_CMP_SWAP:
12057   case AMDGPUISD::ATOMIC_INC:
12058   case AMDGPUISD::ATOMIC_DEC:
12059   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12060   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12061   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12062   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12063   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12064   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12065   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12066   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12067   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12068   case AMDGPUISD::BUFFER_ATOMIC_AND:
12069   case AMDGPUISD::BUFFER_ATOMIC_OR:
12070   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12071   case AMDGPUISD::BUFFER_ATOMIC_INC:
12072   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12073   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12074   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12075   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12076   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12077   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12078     // Target-specific read-modify-write atomics are sources of divergence.
12079     return true;
12080   default:
12081     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12082       // Generic read-modify-write atomics are sources of divergence.
12083       return A->readMem() && A->writeMem();
12084     }
12085     return false;
12086   }
12087 }
12088 
12089 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12090                                                EVT VT) const {
12091   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12092   case MVT::f32:
12093     return hasFP32Denormals(DAG.getMachineFunction());
12094   case MVT::f64:
12095   case MVT::f16:
12096     return hasFP64FP16Denormals(DAG.getMachineFunction());
12097   default:
12098     return false;
12099   }
12100 }
12101 
12102 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12103                                                MachineFunction &MF) const {
12104   switch (Ty.getScalarSizeInBits()) {
12105   case 32:
12106     return hasFP32Denormals(MF);
12107   case 64:
12108   case 16:
12109     return hasFP64FP16Denormals(MF);
12110   default:
12111     return false;
12112   }
12113 }
12114 
12115 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12116                                                     const SelectionDAG &DAG,
12117                                                     bool SNaN,
12118                                                     unsigned Depth) const {
12119   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12120     const MachineFunction &MF = DAG.getMachineFunction();
12121     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12122 
12123     if (Info->getMode().DX10Clamp)
12124       return true; // Clamped to 0.
12125     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12126   }
12127 
12128   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12129                                                             SNaN, Depth);
12130 }
12131 
12132 // Global FP atomic instructions have a hardcoded FP mode and do not support
12133 // FP32 denormals, and only support v2f16 denormals.
12134 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12135   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12136   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12137   if (&Flt == &APFloat::IEEEsingle())
12138     return DenormMode == DenormalMode::getPreserveSign();
12139   return DenormMode == DenormalMode::getIEEE();
12140 }
12141 
12142 TargetLowering::AtomicExpansionKind
12143 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12144   switch (RMW->getOperation()) {
12145   case AtomicRMWInst::FAdd: {
12146     Type *Ty = RMW->getType();
12147 
12148     // We don't have a way to support 16-bit atomics now, so just leave them
12149     // as-is.
12150     if (Ty->isHalfTy())
12151       return AtomicExpansionKind::None;
12152 
12153     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12154       return AtomicExpansionKind::CmpXChg;
12155 
12156     unsigned AS = RMW->getPointerAddressSpace();
12157 
12158     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12159          Subtarget->hasAtomicFaddInsts()) {
12160       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12161       // floating point atomic instructions. May generate more efficient code,
12162       // but may not respect rounding and denormal modes, and may give incorrect
12163       // results for certain memory destinations.
12164       if (RMW->getFunction()
12165               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12166               .getValueAsString() != "true")
12167         return AtomicExpansionKind::CmpXChg;
12168 
12169       if (Subtarget->hasGFX90AInsts()) {
12170         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12171           return AtomicExpansionKind::CmpXChg;
12172 
12173         auto SSID = RMW->getSyncScopeID();
12174         if (SSID == SyncScope::System ||
12175             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12176           return AtomicExpansionKind::CmpXChg;
12177 
12178         return AtomicExpansionKind::None;
12179       }
12180 
12181       if (AS == AMDGPUAS::FLAT_ADDRESS)
12182         return AtomicExpansionKind::CmpXChg;
12183 
12184       return RMW->use_empty() ? AtomicExpansionKind::None
12185                               : AtomicExpansionKind::CmpXChg;
12186     }
12187 
12188     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12189     // to round-to-nearest-even.
12190     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12191     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
12192       if (!Ty->isDoubleTy())
12193         return AtomicExpansionKind::None;
12194 
12195       return (fpModeMatchesGlobalFPAtomicMode(RMW) ||
12196               RMW->getFunction()
12197                       ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12198                       .getValueAsString() == "true")
12199                  ? AtomicExpansionKind::None
12200                  : AtomicExpansionKind::CmpXChg;
12201     }
12202 
12203     return AtomicExpansionKind::CmpXChg;
12204   }
12205   default:
12206     break;
12207   }
12208 
12209   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12210 }
12211 
12212 const TargetRegisterClass *
12213 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12214   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12215   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12216   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12217     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12218                                                : &AMDGPU::SReg_32RegClass;
12219   if (!TRI->isSGPRClass(RC) && !isDivergent)
12220     return TRI->getEquivalentSGPRClass(RC);
12221   else if (TRI->isSGPRClass(RC) && isDivergent)
12222     return TRI->getEquivalentVGPRClass(RC);
12223 
12224   return RC;
12225 }
12226 
12227 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12228 // uniform values (as produced by the mask results of control flow intrinsics)
12229 // used outside of divergent blocks. The phi users need to also be treated as
12230 // always uniform.
12231 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12232                       unsigned WaveSize) {
12233   // FIXME: We asssume we never cast the mask results of a control flow
12234   // intrinsic.
12235   // Early exit if the type won't be consistent as a compile time hack.
12236   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12237   if (!IT || IT->getBitWidth() != WaveSize)
12238     return false;
12239 
12240   if (!isa<Instruction>(V))
12241     return false;
12242   if (!Visited.insert(V).second)
12243     return false;
12244   bool Result = false;
12245   for (auto U : V->users()) {
12246     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12247       if (V == U->getOperand(1)) {
12248         switch (Intrinsic->getIntrinsicID()) {
12249         default:
12250           Result = false;
12251           break;
12252         case Intrinsic::amdgcn_if_break:
12253         case Intrinsic::amdgcn_if:
12254         case Intrinsic::amdgcn_else:
12255           Result = true;
12256           break;
12257         }
12258       }
12259       if (V == U->getOperand(0)) {
12260         switch (Intrinsic->getIntrinsicID()) {
12261         default:
12262           Result = false;
12263           break;
12264         case Intrinsic::amdgcn_end_cf:
12265         case Intrinsic::amdgcn_loop:
12266           Result = true;
12267           break;
12268         }
12269       }
12270     } else {
12271       Result = hasCFUser(U, Visited, WaveSize);
12272     }
12273     if (Result)
12274       break;
12275   }
12276   return Result;
12277 }
12278 
12279 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12280                                                const Value *V) const {
12281   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12282     if (CI->isInlineAsm()) {
12283       // FIXME: This cannot give a correct answer. This should only trigger in
12284       // the case where inline asm returns mixed SGPR and VGPR results, used
12285       // outside the defining block. We don't have a specific result to
12286       // consider, so this assumes if any value is SGPR, the overall register
12287       // also needs to be SGPR.
12288       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12289       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12290           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12291       for (auto &TC : TargetConstraints) {
12292         if (TC.Type == InlineAsm::isOutput) {
12293           ComputeConstraintToUse(TC, SDValue());
12294           unsigned AssignedReg;
12295           const TargetRegisterClass *RC;
12296           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12297               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12298           if (RC) {
12299             MachineRegisterInfo &MRI = MF.getRegInfo();
12300             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12301               return true;
12302             else if (SIRI->isSGPRClass(RC))
12303               return true;
12304           }
12305         }
12306       }
12307     }
12308   }
12309   SmallPtrSet<const Value *, 16> Visited;
12310   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12311 }
12312 
12313 std::pair<InstructionCost, MVT>
12314 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12315                                           Type *Ty) const {
12316   std::pair<InstructionCost, MVT> Cost =
12317       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12318   auto Size = DL.getTypeSizeInBits(Ty);
12319   // Maximum load or store can handle 8 dwords for scalar and 4 for
12320   // vector ALU. Let's assume anything above 8 dwords is expensive
12321   // even if legal.
12322   if (Size <= 256)
12323     return Cost;
12324 
12325   Cost.first = (Size + 255) / 256;
12326   return Cost;
12327 }
12328