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/MachineFunction.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/IntrinsicsAMDGPU.h"
31 #include "llvm/IR/IntrinsicsR600.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/KnownBits.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "si-lower"
38 
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 
41 static cl::opt<bool> DisableLoopAlignment(
42   "amdgpu-disable-loop-alignment",
43   cl::desc("Do not align and prefetch loops"),
44   cl::init(false));
45 
46 static cl::opt<bool> VGPRReserveforSGPRSpill(
47     "amdgpu-reserve-vgpr-for-sgpr-spill",
48     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
49 
50 static cl::opt<bool> UseDivergentRegisterIndexing(
51   "amdgpu-use-divergent-register-indexing",
52   cl::Hidden,
53   cl::desc("Use indirect register addressing for divergent indexes"),
54   cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
57   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
58   return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
62   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
63   return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70       return AMDGPU::SGPR0 + Reg;
71     }
72   }
73   llvm_unreachable("Cannot allocate sgpr");
74 }
75 
76 SITargetLowering::SITargetLowering(const TargetMachine &TM,
77                                    const GCNSubtarget &STI)
78     : AMDGPUTargetLowering(TM, STI),
79       Subtarget(&STI) {
80   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88   const SIRegisterInfo *TRI = STI.getRegisterInfo();
89   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91   addRegisterClass(MVT::f64, V64RegClass);
92   addRegisterClass(MVT::v2f32, V64RegClass);
93 
94   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130   if (Subtarget->has16BitInsts()) {
131     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134     // Unless there are also VOP3P operations, not operations are really legal.
135     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139   }
140 
141   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
142   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
143 
144   computeRegisterProperties(Subtarget->getRegisterInfo());
145 
146   // The boolean content concept here is too inflexible. Compares only ever
147   // really produce a 1-bit result. Any copy/extend from these will turn into a
148   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
149   // it's what most targets use.
150   setBooleanContents(ZeroOrOneBooleanContent);
151   setBooleanVectorContents(ZeroOrOneBooleanContent);
152 
153   // We need to custom lower vector stores from local memory
154   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::i1, Custom);
163   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
164 
165   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
166   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
173   setOperationAction(ISD::STORE, MVT::i1, Custom);
174   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
175 
176   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
177   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
178   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
179   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
180   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
181   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
182   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
183   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
184   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
185   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
186   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
187   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
188   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
189   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
190   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
191   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
192 
193   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
194   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
195   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
196   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
199   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
200 
201   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
202   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
203 
204   setOperationAction(ISD::SELECT, MVT::i1, Promote);
205   setOperationAction(ISD::SELECT, MVT::i64, Custom);
206   setOperationAction(ISD::SELECT, MVT::f64, Promote);
207   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
208 
209   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
210   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
214 
215   setOperationAction(ISD::SETCC, MVT::i1, Promote);
216   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
217   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
218   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
219 
220   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
221   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
222   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
236 
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
245 
246   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
248   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
250   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
252 
253   setOperationAction(ISD::UADDO, MVT::i32, Legal);
254   setOperationAction(ISD::USUBO, MVT::i32, Legal);
255 
256   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
258 
259   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
260   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
262 
263 #if 0
264   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
265   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
266 #endif
267 
268   // We only support LOAD/STORE and vector manipulation ops for vectors
269   // with > 4 elements.
270   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
271                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
272                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
273                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
274                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
275     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
276       switch (Op) {
277       case ISD::LOAD:
278       case ISD::STORE:
279       case ISD::BUILD_VECTOR:
280       case ISD::BITCAST:
281       case ISD::EXTRACT_VECTOR_ELT:
282       case ISD::INSERT_VECTOR_ELT:
283       case ISD::EXTRACT_SUBVECTOR:
284       case ISD::SCALAR_TO_VECTOR:
285         break;
286       case ISD::INSERT_SUBVECTOR:
287       case ISD::CONCAT_VECTORS:
288         setOperationAction(Op, VT, Custom);
289         break;
290       default:
291         setOperationAction(Op, VT, Expand);
292         break;
293       }
294     }
295   }
296 
297   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
298 
299   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
300   // is expanded to avoid having two separate loops in case the index is a VGPR.
301 
302   // Most operations are naturally 32-bit vector operations. We only support
303   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
304   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
305     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
306     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
307 
308     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
309     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
310 
311     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
312     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
313 
314     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
315     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
316   }
317 
318   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
319     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
320     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
321 
322     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
323     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
324 
325     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
326     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
327 
328     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
329     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
330   }
331 
332   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
333     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
334     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
335 
336     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
337     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
338 
339     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
340     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
343     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
344   }
345 
346   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
347     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
348     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
349 
350     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
351     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
352 
353     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
354     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
357     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
358   }
359 
360   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
361     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
362     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
363 
364     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
365     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
366 
367     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
368     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
371     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
372   }
373 
374   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
378 
379   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
380   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
381 
382   // Avoid stack access for these.
383   // TODO: Generalize to more vector types.
384   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
385   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
386   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
387   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
388 
389   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
398   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
400 
401   // Deal with vec3 vector operations when widened to vec4.
402   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
406 
407   // Deal with vec5/6/7 vector operations when widened to vec8.
408   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
416 
417   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
418   // and output demarshalling
419   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
420   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
421 
422   // We can't return success/failure, only the old value,
423   // let LLVM add the comparison
424   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
425   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
426 
427   if (Subtarget->hasFlatAddressSpace()) {
428     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
429     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
430   }
431 
432   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
433   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
434 
435   // FIXME: This should be narrowed to i32, but that only happens if i64 is
436   // illegal.
437   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
438   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
439   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
440 
441   // On SI this is s_memtime and s_memrealtime on VI.
442   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
443   setOperationAction(ISD::TRAP, MVT::Other, Custom);
444   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
445 
446   if (Subtarget->has16BitInsts()) {
447     setOperationAction(ISD::FPOW, MVT::f16, Promote);
448     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
449     setOperationAction(ISD::FLOG, MVT::f16, Custom);
450     setOperationAction(ISD::FEXP, MVT::f16, Custom);
451     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
452   }
453 
454   if (Subtarget->hasMadMacF32Insts())
455     setOperationAction(ISD::FMAD, MVT::f32, Legal);
456 
457   if (!Subtarget->hasBFI()) {
458     // fcopysign can be done in a single instruction with BFI.
459     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
460     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
461   }
462 
463   if (!Subtarget->hasBCNT(32))
464     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
465 
466   if (!Subtarget->hasBCNT(64))
467     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
468 
469   if (Subtarget->hasFFBH()) {
470     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
471     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
472   }
473 
474   if (Subtarget->hasFFBL()) {
475     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
476     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
477   }
478 
479   // We only really have 32-bit BFE instructions (and 16-bit on VI).
480   //
481   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
482   // effort to match them now. We want this to be false for i64 cases when the
483   // extraction isn't restricted to the upper or lower half. Ideally we would
484   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
485   // span the midpoint are probably relatively rare, so don't worry about them
486   // for now.
487   if (Subtarget->hasBFE())
488     setHasExtractBitsInsn(true);
489 
490   // Clamp modifier on add/sub
491   if (Subtarget->hasIntClamp()) {
492     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
493     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
494   }
495 
496   if (Subtarget->hasAddNoCarry()) {
497     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
498     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
501   }
502 
503   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
504   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
507 
508 
509   // These are really only legal for ieee_mode functions. We should be avoiding
510   // them for functions that don't have ieee_mode enabled, so just say they are
511   // legal.
512   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
513   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
516 
517 
518   if (Subtarget->haveRoundOpsF64()) {
519     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
520     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
521     setOperationAction(ISD::FRINT, MVT::f64, Legal);
522   } else {
523     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
524     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
525     setOperationAction(ISD::FRINT, MVT::f64, Custom);
526     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
527   }
528 
529   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
530 
531   setOperationAction(ISD::FSIN, MVT::f32, Custom);
532   setOperationAction(ISD::FCOS, MVT::f32, Custom);
533   setOperationAction(ISD::FDIV, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f64, Custom);
535 
536   if (Subtarget->has16BitInsts()) {
537     setOperationAction(ISD::Constant, MVT::i16, Legal);
538 
539     setOperationAction(ISD::SMIN, MVT::i16, Legal);
540     setOperationAction(ISD::SMAX, MVT::i16, Legal);
541 
542     setOperationAction(ISD::UMIN, MVT::i16, Legal);
543     setOperationAction(ISD::UMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
546     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
547 
548     setOperationAction(ISD::ROTR, MVT::i16, Expand);
549     setOperationAction(ISD::ROTL, MVT::i16, Expand);
550 
551     setOperationAction(ISD::SDIV, MVT::i16, Promote);
552     setOperationAction(ISD::UDIV, MVT::i16, Promote);
553     setOperationAction(ISD::SREM, MVT::i16, Promote);
554     setOperationAction(ISD::UREM, MVT::i16, Promote);
555     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
556     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
557 
558     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
559 
560     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
562     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
565 
566     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
567 
568     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::LOAD, MVT::i16, Custom);
571 
572     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
573 
574     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
575     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
576     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
578 
579     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
580     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
581 
582     // F16 - Constant Actions.
583     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
584 
585     // F16 - Load/Store Actions.
586     setOperationAction(ISD::LOAD, MVT::f16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
588     setOperationAction(ISD::STORE, MVT::f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
590 
591     // F16 - VOP1 Actions.
592     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
593     setOperationAction(ISD::FCOS, MVT::f16, Custom);
594     setOperationAction(ISD::FSIN, MVT::f16, Custom);
595 
596     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
597     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
598 
599     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
600     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
601     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
602     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::FROUND, MVT::f16, Custom);
604 
605     // F16 - VOP2 Actions.
606     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
608 
609     setOperationAction(ISD::FDIV, MVT::f16, Custom);
610 
611     // F16 - VOP3 Actions.
612     setOperationAction(ISD::FMA, MVT::f16, Legal);
613     if (STI.hasMadF16())
614       setOperationAction(ISD::FMAD, MVT::f16, Legal);
615 
616     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
617       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
618         switch (Op) {
619         case ISD::LOAD:
620         case ISD::STORE:
621         case ISD::BUILD_VECTOR:
622         case ISD::BITCAST:
623         case ISD::EXTRACT_VECTOR_ELT:
624         case ISD::INSERT_VECTOR_ELT:
625         case ISD::INSERT_SUBVECTOR:
626         case ISD::EXTRACT_SUBVECTOR:
627         case ISD::SCALAR_TO_VECTOR:
628           break;
629         case ISD::CONCAT_VECTORS:
630           setOperationAction(Op, VT, Custom);
631           break;
632         default:
633           setOperationAction(Op, VT, Expand);
634           break;
635         }
636       }
637     }
638 
639     // v_perm_b32 can handle either of these.
640     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
641     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
643 
644     // XXX - Do these do anything? Vector constants turn into build_vector.
645     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
646     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
649     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
650 
651     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
653     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
655 
656     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::AND, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::OR, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
667 
668     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
669     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
670     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
672 
673     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
679     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
682 
683     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
684     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
686 
687     if (!Subtarget->hasVOP3PInsts()) {
688       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
690     }
691 
692     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
693     // This isn't really legal, but this avoids the legalizer unrolling it (and
694     // allows matching fneg (fabs x) patterns)
695     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
696 
697     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
698     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
701 
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
703     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
704 
705     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
706     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
707   }
708 
709   if (Subtarget->hasVOP3PInsts()) {
710     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
711     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
712     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
713     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
716     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
717     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
720 
721     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
722     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
725 
726     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
727     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
729 
730     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
731     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
732 
733     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
737 
738     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
740 
741     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
742     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
744     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
745     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
746     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
747 
748     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
749     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
750     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
754     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
757 
758     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
759     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
761 
762     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
763     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
764 
765     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
766     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
768 
769     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
770     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
772 
773     if (Subtarget->hasPackedFP32Ops()) {
774       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
775       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
776       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
777       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
778 
779       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
780         setOperationAction(ISD::FADD, VT, Custom);
781         setOperationAction(ISD::FMUL, VT, Custom);
782         setOperationAction(ISD::FMA, VT, Custom);
783       }
784     }
785   }
786 
787   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
788   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
789 
790   if (Subtarget->has16BitInsts()) {
791     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
792     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
793     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
794     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
795   } else {
796     // Legalization hack.
797     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
798     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
799 
800     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
801     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
802   }
803 
804   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
805     setOperationAction(ISD::SELECT, VT, Custom);
806   }
807 
808   setOperationAction(ISD::SMULO, MVT::i64, Custom);
809   setOperationAction(ISD::UMULO, MVT::i64, Custom);
810 
811   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
814   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
815   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
817   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
820   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
822   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
824   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
825   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
830 
831   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
832   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
833   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
834   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
835   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
836   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
837   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
841 
842   setTargetDAGCombine(ISD::ADD);
843   setTargetDAGCombine(ISD::ADDCARRY);
844   setTargetDAGCombine(ISD::SUB);
845   setTargetDAGCombine(ISD::SUBCARRY);
846   setTargetDAGCombine(ISD::FADD);
847   setTargetDAGCombine(ISD::FSUB);
848   setTargetDAGCombine(ISD::FMINNUM);
849   setTargetDAGCombine(ISD::FMAXNUM);
850   setTargetDAGCombine(ISD::FMINNUM_IEEE);
851   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
852   setTargetDAGCombine(ISD::FMA);
853   setTargetDAGCombine(ISD::SMIN);
854   setTargetDAGCombine(ISD::SMAX);
855   setTargetDAGCombine(ISD::UMIN);
856   setTargetDAGCombine(ISD::UMAX);
857   setTargetDAGCombine(ISD::SETCC);
858   setTargetDAGCombine(ISD::AND);
859   setTargetDAGCombine(ISD::OR);
860   setTargetDAGCombine(ISD::XOR);
861   setTargetDAGCombine(ISD::SINT_TO_FP);
862   setTargetDAGCombine(ISD::UINT_TO_FP);
863   setTargetDAGCombine(ISD::FCANONICALIZE);
864   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
865   setTargetDAGCombine(ISD::ZERO_EXTEND);
866   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
867   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
868   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
869 
870   // All memory operations. Some folding on the pointer operand is done to help
871   // matching the constant offsets in the addressing modes.
872   setTargetDAGCombine(ISD::LOAD);
873   setTargetDAGCombine(ISD::STORE);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD);
875   setTargetDAGCombine(ISD::ATOMIC_STORE);
876   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
877   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
878   setTargetDAGCombine(ISD::ATOMIC_SWAP);
879   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
880   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
881   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
882   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
883   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
884   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
885   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
890   setTargetDAGCombine(ISD::INTRINSIC_VOID);
891   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
892 
893   // FIXME: In other contexts we pretend this is a per-function property.
894   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
895 
896   setSchedulingPreference(Sched::RegPressure);
897 }
898 
899 const GCNSubtarget *SITargetLowering::getSubtarget() const {
900   return Subtarget;
901 }
902 
903 //===----------------------------------------------------------------------===//
904 // TargetLowering queries
905 //===----------------------------------------------------------------------===//
906 
907 // v_mad_mix* support a conversion from f16 to f32.
908 //
909 // There is only one special case when denormals are enabled we don't currently,
910 // where this is OK to use.
911 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
912                                        EVT DestVT, EVT SrcVT) const {
913   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
914           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
915     DestVT.getScalarType() == MVT::f32 &&
916     SrcVT.getScalarType() == MVT::f16 &&
917     // TODO: This probably only requires no input flushing?
918     !hasFP32Denormals(DAG.getMachineFunction());
919 }
920 
921 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
922   // SI has some legal vector types, but no legal vector operations. Say no
923   // shuffles are legal in order to prefer scalarizing some vector operations.
924   return false;
925 }
926 
927 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
928                                                     CallingConv::ID CC,
929                                                     EVT VT) const {
930   if (CC == CallingConv::AMDGPU_KERNEL)
931     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
932 
933   if (VT.isVector()) {
934     EVT ScalarVT = VT.getScalarType();
935     unsigned Size = ScalarVT.getSizeInBits();
936     if (Size == 16) {
937       if (Subtarget->has16BitInsts())
938         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
939       return VT.isInteger() ? MVT::i32 : MVT::f32;
940     }
941 
942     if (Size < 16)
943       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
944     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
945   }
946 
947   if (VT.getSizeInBits() > 32)
948     return MVT::i32;
949 
950   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
951 }
952 
953 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
954                                                          CallingConv::ID CC,
955                                                          EVT VT) const {
956   if (CC == CallingConv::AMDGPU_KERNEL)
957     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
958 
959   if (VT.isVector()) {
960     unsigned NumElts = VT.getVectorNumElements();
961     EVT ScalarVT = VT.getScalarType();
962     unsigned Size = ScalarVT.getSizeInBits();
963 
964     // FIXME: Should probably promote 8-bit vectors to i16.
965     if (Size == 16 && Subtarget->has16BitInsts())
966       return (NumElts + 1) / 2;
967 
968     if (Size <= 32)
969       return NumElts;
970 
971     if (Size > 32)
972       return NumElts * ((Size + 31) / 32);
973   } else if (VT.getSizeInBits() > 32)
974     return (VT.getSizeInBits() + 31) / 32;
975 
976   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
977 }
978 
979 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
980   LLVMContext &Context, CallingConv::ID CC,
981   EVT VT, EVT &IntermediateVT,
982   unsigned &NumIntermediates, MVT &RegisterVT) const {
983   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
984     unsigned NumElts = VT.getVectorNumElements();
985     EVT ScalarVT = VT.getScalarType();
986     unsigned Size = ScalarVT.getSizeInBits();
987     // FIXME: We should fix the ABI to be the same on targets without 16-bit
988     // support, but unless we can properly handle 3-vectors, it will be still be
989     // inconsistent.
990     if (Size == 16 && Subtarget->has16BitInsts()) {
991       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
992       IntermediateVT = RegisterVT;
993       NumIntermediates = (NumElts + 1) / 2;
994       return NumIntermediates;
995     }
996 
997     if (Size == 32) {
998       RegisterVT = ScalarVT.getSimpleVT();
999       IntermediateVT = RegisterVT;
1000       NumIntermediates = NumElts;
1001       return NumIntermediates;
1002     }
1003 
1004     if (Size < 16 && Subtarget->has16BitInsts()) {
1005       // FIXME: Should probably form v2i16 pieces
1006       RegisterVT = MVT::i16;
1007       IntermediateVT = ScalarVT;
1008       NumIntermediates = NumElts;
1009       return NumIntermediates;
1010     }
1011 
1012 
1013     if (Size != 16 && Size <= 32) {
1014       RegisterVT = MVT::i32;
1015       IntermediateVT = ScalarVT;
1016       NumIntermediates = NumElts;
1017       return NumIntermediates;
1018     }
1019 
1020     if (Size > 32) {
1021       RegisterVT = MVT::i32;
1022       IntermediateVT = RegisterVT;
1023       NumIntermediates = NumElts * ((Size + 31) / 32);
1024       return NumIntermediates;
1025     }
1026   }
1027 
1028   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1029     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1030 }
1031 
1032 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1033   assert(DMaskLanes != 0);
1034 
1035   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1036     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1037     return EVT::getVectorVT(Ty->getContext(),
1038                             EVT::getEVT(VT->getElementType()),
1039                             NumElts);
1040   }
1041 
1042   return EVT::getEVT(Ty);
1043 }
1044 
1045 // Peek through TFE struct returns to only use the data size.
1046 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1047   auto *ST = dyn_cast<StructType>(Ty);
1048   if (!ST)
1049     return memVTFromImageData(Ty, DMaskLanes);
1050 
1051   // Some intrinsics return an aggregate type - special case to work out the
1052   // correct memVT.
1053   //
1054   // Only limited forms of aggregate type currently expected.
1055   if (ST->getNumContainedTypes() != 2 ||
1056       !ST->getContainedType(1)->isIntegerTy(32))
1057     return EVT();
1058   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1059 }
1060 
1061 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1062                                           const CallInst &CI,
1063                                           MachineFunction &MF,
1064                                           unsigned IntrID) const {
1065   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1066           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1067     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1068                                                   (Intrinsic::ID)IntrID);
1069     if (Attr.hasFnAttribute(Attribute::ReadNone))
1070       return false;
1071 
1072     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1073 
1074     if (RsrcIntr->IsImage) {
1075       Info.ptrVal =
1076           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1077       Info.align.reset();
1078     } else {
1079       Info.ptrVal =
1080           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1081     }
1082 
1083     Info.flags = MachineMemOperand::MODereferenceable;
1084     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1085       unsigned DMaskLanes = 4;
1086 
1087       if (RsrcIntr->IsImage) {
1088         const AMDGPU::ImageDimIntrinsicInfo *Intr
1089           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1090         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1091           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1092 
1093         if (!BaseOpcode->Gather4) {
1094           // If this isn't a gather, we may have excess loaded elements in the
1095           // IR type. Check the dmask for the real number of elements loaded.
1096           unsigned DMask
1097             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1098           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1099         }
1100 
1101         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1102       } else
1103         Info.memVT = EVT::getEVT(CI.getType());
1104 
1105       // FIXME: What does alignment mean for an image?
1106       Info.opc = ISD::INTRINSIC_W_CHAIN;
1107       Info.flags |= MachineMemOperand::MOLoad;
1108     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1109       Info.opc = ISD::INTRINSIC_VOID;
1110 
1111       Type *DataTy = CI.getArgOperand(0)->getType();
1112       if (RsrcIntr->IsImage) {
1113         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1114         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1115         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1116       } else
1117         Info.memVT = EVT::getEVT(DataTy);
1118 
1119       Info.flags |= MachineMemOperand::MOStore;
1120     } else {
1121       // Atomic
1122       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1123                                             ISD::INTRINSIC_W_CHAIN;
1124       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1125       Info.flags = MachineMemOperand::MOLoad |
1126                    MachineMemOperand::MOStore |
1127                    MachineMemOperand::MODereferenceable;
1128 
1129       // XXX - Should this be volatile without known ordering?
1130       Info.flags |= MachineMemOperand::MOVolatile;
1131     }
1132     return true;
1133   }
1134 
1135   switch (IntrID) {
1136   case Intrinsic::amdgcn_atomic_inc:
1137   case Intrinsic::amdgcn_atomic_dec:
1138   case Intrinsic::amdgcn_ds_ordered_add:
1139   case Intrinsic::amdgcn_ds_ordered_swap:
1140   case Intrinsic::amdgcn_ds_fadd:
1141   case Intrinsic::amdgcn_ds_fmin:
1142   case Intrinsic::amdgcn_ds_fmax: {
1143     Info.opc = ISD::INTRINSIC_W_CHAIN;
1144     Info.memVT = MVT::getVT(CI.getType());
1145     Info.ptrVal = CI.getOperand(0);
1146     Info.align.reset();
1147     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1148 
1149     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1150     if (!Vol->isZero())
1151       Info.flags |= MachineMemOperand::MOVolatile;
1152 
1153     return true;
1154   }
1155   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1156     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1157 
1158     Info.opc = ISD::INTRINSIC_W_CHAIN;
1159     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1160     Info.ptrVal =
1161         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1162     Info.align.reset();
1163     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1164 
1165     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1166     if (!Vol || !Vol->isZero())
1167       Info.flags |= MachineMemOperand::MOVolatile;
1168 
1169     return true;
1170   }
1171   case Intrinsic::amdgcn_ds_append:
1172   case Intrinsic::amdgcn_ds_consume: {
1173     Info.opc = ISD::INTRINSIC_W_CHAIN;
1174     Info.memVT = MVT::getVT(CI.getType());
1175     Info.ptrVal = CI.getOperand(0);
1176     Info.align.reset();
1177     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1178 
1179     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1180     if (!Vol->isZero())
1181       Info.flags |= MachineMemOperand::MOVolatile;
1182 
1183     return true;
1184   }
1185   case Intrinsic::amdgcn_global_atomic_csub: {
1186     Info.opc = ISD::INTRINSIC_W_CHAIN;
1187     Info.memVT = MVT::getVT(CI.getType());
1188     Info.ptrVal = CI.getOperand(0);
1189     Info.align.reset();
1190     Info.flags = MachineMemOperand::MOLoad |
1191                  MachineMemOperand::MOStore |
1192                  MachineMemOperand::MOVolatile;
1193     return true;
1194   }
1195   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1196     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1197     Info.opc = ISD::INTRINSIC_W_CHAIN;
1198     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1199     Info.ptrVal =
1200         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1201     Info.align.reset();
1202     Info.flags = MachineMemOperand::MOLoad |
1203                  MachineMemOperand::MODereferenceable;
1204     return true;
1205   }
1206   case Intrinsic::amdgcn_global_atomic_fadd:
1207   case Intrinsic::amdgcn_global_atomic_fmin:
1208   case Intrinsic::amdgcn_global_atomic_fmax:
1209   case Intrinsic::amdgcn_flat_atomic_fadd:
1210   case Intrinsic::amdgcn_flat_atomic_fmin:
1211   case Intrinsic::amdgcn_flat_atomic_fmax: {
1212     Info.opc = ISD::INTRINSIC_W_CHAIN;
1213     Info.memVT = MVT::getVT(CI.getType());
1214     Info.ptrVal = CI.getOperand(0);
1215     Info.align.reset();
1216     Info.flags = MachineMemOperand::MOLoad |
1217                  MachineMemOperand::MOStore |
1218                  MachineMemOperand::MODereferenceable |
1219                  MachineMemOperand::MOVolatile;
1220     return true;
1221   }
1222   case Intrinsic::amdgcn_ds_gws_init:
1223   case Intrinsic::amdgcn_ds_gws_barrier:
1224   case Intrinsic::amdgcn_ds_gws_sema_v:
1225   case Intrinsic::amdgcn_ds_gws_sema_br:
1226   case Intrinsic::amdgcn_ds_gws_sema_p:
1227   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1228     Info.opc = ISD::INTRINSIC_VOID;
1229 
1230     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1231     Info.ptrVal =
1232         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1233 
1234     // This is an abstract access, but we need to specify a type and size.
1235     Info.memVT = MVT::i32;
1236     Info.size = 4;
1237     Info.align = Align(4);
1238 
1239     Info.flags = MachineMemOperand::MOStore;
1240     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1241       Info.flags = MachineMemOperand::MOLoad;
1242     return true;
1243   }
1244   default:
1245     return false;
1246   }
1247 }
1248 
1249 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1250                                             SmallVectorImpl<Value*> &Ops,
1251                                             Type *&AccessTy) const {
1252   switch (II->getIntrinsicID()) {
1253   case Intrinsic::amdgcn_atomic_inc:
1254   case Intrinsic::amdgcn_atomic_dec:
1255   case Intrinsic::amdgcn_ds_ordered_add:
1256   case Intrinsic::amdgcn_ds_ordered_swap:
1257   case Intrinsic::amdgcn_ds_append:
1258   case Intrinsic::amdgcn_ds_consume:
1259   case Intrinsic::amdgcn_ds_fadd:
1260   case Intrinsic::amdgcn_ds_fmin:
1261   case Intrinsic::amdgcn_ds_fmax:
1262   case Intrinsic::amdgcn_global_atomic_fadd:
1263   case Intrinsic::amdgcn_flat_atomic_fadd:
1264   case Intrinsic::amdgcn_flat_atomic_fmin:
1265   case Intrinsic::amdgcn_flat_atomic_fmax:
1266   case Intrinsic::amdgcn_global_atomic_csub: {
1267     Value *Ptr = II->getArgOperand(0);
1268     AccessTy = II->getType();
1269     Ops.push_back(Ptr);
1270     return true;
1271   }
1272   default:
1273     return false;
1274   }
1275 }
1276 
1277 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1278   if (!Subtarget->hasFlatInstOffsets()) {
1279     // Flat instructions do not have offsets, and only have the register
1280     // address.
1281     return AM.BaseOffs == 0 && AM.Scale == 0;
1282   }
1283 
1284   return AM.Scale == 0 &&
1285          (AM.BaseOffs == 0 ||
1286           Subtarget->getInstrInfo()->isLegalFLATOffset(
1287               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1288 }
1289 
1290 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1291   if (Subtarget->hasFlatGlobalInsts())
1292     return AM.Scale == 0 &&
1293            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1294                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1295                                     SIInstrFlags::FlatGlobal));
1296 
1297   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1298       // Assume the we will use FLAT for all global memory accesses
1299       // on VI.
1300       // FIXME: This assumption is currently wrong.  On VI we still use
1301       // MUBUF instructions for the r + i addressing mode.  As currently
1302       // implemented, the MUBUF instructions only work on buffer < 4GB.
1303       // It may be possible to support > 4GB buffers with MUBUF instructions,
1304       // by setting the stride value in the resource descriptor which would
1305       // increase the size limit to (stride * 4GB).  However, this is risky,
1306       // because it has never been validated.
1307     return isLegalFlatAddressingMode(AM);
1308   }
1309 
1310   return isLegalMUBUFAddressingMode(AM);
1311 }
1312 
1313 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1314   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1315   // additionally can do r + r + i with addr64. 32-bit has more addressing
1316   // mode options. Depending on the resource constant, it can also do
1317   // (i64 r0) + (i32 r1) * (i14 i).
1318   //
1319   // Private arrays end up using a scratch buffer most of the time, so also
1320   // assume those use MUBUF instructions. Scratch loads / stores are currently
1321   // implemented as mubuf instructions with offen bit set, so slightly
1322   // different than the normal addr64.
1323   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1324     return false;
1325 
1326   // FIXME: Since we can split immediate into soffset and immediate offset,
1327   // would it make sense to allow any immediate?
1328 
1329   switch (AM.Scale) {
1330   case 0: // r + i or just i, depending on HasBaseReg.
1331     return true;
1332   case 1:
1333     return true; // We have r + r or r + i.
1334   case 2:
1335     if (AM.HasBaseReg) {
1336       // Reject 2 * r + r.
1337       return false;
1338     }
1339 
1340     // Allow 2 * r as r + r
1341     // Or  2 * r + i is allowed as r + r + i.
1342     return true;
1343   default: // Don't allow n * r
1344     return false;
1345   }
1346 }
1347 
1348 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1349                                              const AddrMode &AM, Type *Ty,
1350                                              unsigned AS, Instruction *I) const {
1351   // No global is ever allowed as a base.
1352   if (AM.BaseGV)
1353     return false;
1354 
1355   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1356     return isLegalGlobalAddressingMode(AM);
1357 
1358   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1359       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1360       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1361     // If the offset isn't a multiple of 4, it probably isn't going to be
1362     // correctly aligned.
1363     // FIXME: Can we get the real alignment here?
1364     if (AM.BaseOffs % 4 != 0)
1365       return isLegalMUBUFAddressingMode(AM);
1366 
1367     // There are no SMRD extloads, so if we have to do a small type access we
1368     // will use a MUBUF load.
1369     // FIXME?: We also need to do this if unaligned, but we don't know the
1370     // alignment here.
1371     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1372       return isLegalGlobalAddressingMode(AM);
1373 
1374     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1375       // SMRD instructions have an 8-bit, dword offset on SI.
1376       if (!isUInt<8>(AM.BaseOffs / 4))
1377         return false;
1378     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1379       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1380       // in 8-bits, it can use a smaller encoding.
1381       if (!isUInt<32>(AM.BaseOffs / 4))
1382         return false;
1383     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1384       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1385       if (!isUInt<20>(AM.BaseOffs))
1386         return false;
1387     } else
1388       llvm_unreachable("unhandled generation");
1389 
1390     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1391       return true;
1392 
1393     if (AM.Scale == 1 && AM.HasBaseReg)
1394       return true;
1395 
1396     return false;
1397 
1398   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1399     return isLegalMUBUFAddressingMode(AM);
1400   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1401              AS == AMDGPUAS::REGION_ADDRESS) {
1402     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1403     // field.
1404     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1405     // an 8-bit dword offset but we don't know the alignment here.
1406     if (!isUInt<16>(AM.BaseOffs))
1407       return false;
1408 
1409     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1410       return true;
1411 
1412     if (AM.Scale == 1 && AM.HasBaseReg)
1413       return true;
1414 
1415     return false;
1416   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1417              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1418     // For an unknown address space, this usually means that this is for some
1419     // reason being used for pure arithmetic, and not based on some addressing
1420     // computation. We don't have instructions that compute pointers with any
1421     // addressing modes, so treat them as having no offset like flat
1422     // instructions.
1423     return isLegalFlatAddressingMode(AM);
1424   }
1425 
1426   // Assume a user alias of global for unknown address spaces.
1427   return isLegalGlobalAddressingMode(AM);
1428 }
1429 
1430 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1431                                         const MachineFunction &MF) const {
1432   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1433     return (MemVT.getSizeInBits() <= 4 * 32);
1434   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1435     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1436     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1437   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1438     return (MemVT.getSizeInBits() <= 2 * 32);
1439   }
1440   return true;
1441 }
1442 
1443 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1444     unsigned Size, unsigned AddrSpace, Align Alignment,
1445     MachineMemOperand::Flags Flags, bool *IsFast) const {
1446   if (IsFast)
1447     *IsFast = false;
1448 
1449   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1450       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1451     // Check if alignment requirements for ds_read/write instructions are
1452     // disabled.
1453     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1454         !Subtarget->hasLDSMisalignedBug()) {
1455       if (IsFast)
1456         *IsFast = Alignment != Align(2);
1457       return true;
1458     }
1459 
1460     // Either, the alignment requirements are "enabled", or there is an
1461     // unaligned LDS access related hardware bug though alignment requirements
1462     // are "disabled". In either case, we need to check for proper alignment
1463     // requirements.
1464     //
1465     if (Size == 64) {
1466       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1467       // can do a 4 byte aligned, 8 byte access in a single operation using
1468       // ds_read2/write2_b32 with adjacent offsets.
1469       bool AlignedBy4 = Alignment >= Align(4);
1470       if (IsFast)
1471         *IsFast = AlignedBy4;
1472 
1473       return AlignedBy4;
1474     }
1475     if (Size == 96) {
1476       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1477       // gfx8 and older.
1478       bool AlignedBy16 = Alignment >= Align(16);
1479       if (IsFast)
1480         *IsFast = AlignedBy16;
1481 
1482       return AlignedBy16;
1483     }
1484     if (Size == 128) {
1485       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1486       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1487       // single operation using ds_read2/write2_b64.
1488       bool AlignedBy8 = Alignment >= Align(8);
1489       if (IsFast)
1490         *IsFast = AlignedBy8;
1491 
1492       return AlignedBy8;
1493     }
1494   }
1495 
1496   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1497     bool AlignedBy4 = Alignment >= Align(4);
1498     if (IsFast)
1499       *IsFast = AlignedBy4;
1500 
1501     return AlignedBy4 ||
1502            Subtarget->enableFlatScratch() ||
1503            Subtarget->hasUnalignedScratchAccess();
1504   }
1505 
1506   // FIXME: We have to be conservative here and assume that flat operations
1507   // will access scratch.  If we had access to the IR function, then we
1508   // could determine if any private memory was used in the function.
1509   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1510       !Subtarget->hasUnalignedScratchAccess()) {
1511     bool AlignedBy4 = Alignment >= Align(4);
1512     if (IsFast)
1513       *IsFast = AlignedBy4;
1514 
1515     return AlignedBy4;
1516   }
1517 
1518   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1519       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1520         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1521     // If we have an uniform constant load, it still requires using a slow
1522     // buffer instruction if unaligned.
1523     if (IsFast) {
1524       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1525       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1526       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1527                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1528         Alignment >= Align(4) : Alignment != Align(2);
1529     }
1530 
1531     return true;
1532   }
1533 
1534   // Smaller than dword value must be aligned.
1535   if (Size < 32)
1536     return false;
1537 
1538   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1539   // byte-address are ignored, thus forcing Dword alignment.
1540   // This applies to private, global, and constant memory.
1541   if (IsFast)
1542     *IsFast = true;
1543 
1544   return Size >= 32 && Alignment >= Align(4);
1545 }
1546 
1547 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1548     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1549     bool *IsFast) const {
1550   if (IsFast)
1551     *IsFast = false;
1552 
1553   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1554   // which isn't a simple VT.
1555   // Until MVT is extended to handle this, simply check for the size and
1556   // rely on the condition below: allow accesses if the size is a multiple of 4.
1557   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1558                            VT.getStoreSize() > 16)) {
1559     return false;
1560   }
1561 
1562   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1563                                             Alignment, Flags, IsFast);
1564 }
1565 
1566 EVT SITargetLowering::getOptimalMemOpType(
1567     const MemOp &Op, const AttributeList &FuncAttributes) const {
1568   // FIXME: Should account for address space here.
1569 
1570   // The default fallback uses the private pointer size as a guess for a type to
1571   // use. Make sure we switch these to 64-bit accesses.
1572 
1573   if (Op.size() >= 16 &&
1574       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1575     return MVT::v4i32;
1576 
1577   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1578     return MVT::v2i32;
1579 
1580   // Use the default.
1581   return MVT::Other;
1582 }
1583 
1584 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1585   const MemSDNode *MemNode = cast<MemSDNode>(N);
1586   const Value *Ptr = MemNode->getMemOperand()->getValue();
1587   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1588   return I && I->getMetadata("amdgpu.noclobber");
1589 }
1590 
1591 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1592   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1593          AS == AMDGPUAS::PRIVATE_ADDRESS;
1594 }
1595 
1596 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1597                                            unsigned DestAS) const {
1598   // Flat -> private/local is a simple truncate.
1599   // Flat -> global is no-op
1600   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1601     return true;
1602 
1603   const GCNTargetMachine &TM =
1604       static_cast<const GCNTargetMachine &>(getTargetMachine());
1605   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1606 }
1607 
1608 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1609   const MemSDNode *MemNode = cast<MemSDNode>(N);
1610 
1611   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1612 }
1613 
1614 TargetLoweringBase::LegalizeTypeAction
1615 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1616   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1617       VT.getScalarType().bitsLE(MVT::i16))
1618     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1619   return TargetLoweringBase::getPreferredVectorAction(VT);
1620 }
1621 
1622 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1623                                                          Type *Ty) const {
1624   // FIXME: Could be smarter if called for vector constants.
1625   return true;
1626 }
1627 
1628 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1629   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1630     switch (Op) {
1631     case ISD::LOAD:
1632     case ISD::STORE:
1633 
1634     // These operations are done with 32-bit instructions anyway.
1635     case ISD::AND:
1636     case ISD::OR:
1637     case ISD::XOR:
1638     case ISD::SELECT:
1639       // TODO: Extensions?
1640       return true;
1641     default:
1642       return false;
1643     }
1644   }
1645 
1646   // SimplifySetCC uses this function to determine whether or not it should
1647   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1648   if (VT == MVT::i1 && Op == ISD::SETCC)
1649     return false;
1650 
1651   return TargetLowering::isTypeDesirableForOp(Op, VT);
1652 }
1653 
1654 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1655                                                    const SDLoc &SL,
1656                                                    SDValue Chain,
1657                                                    uint64_t Offset) const {
1658   const DataLayout &DL = DAG.getDataLayout();
1659   MachineFunction &MF = DAG.getMachineFunction();
1660   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1661 
1662   const ArgDescriptor *InputPtrReg;
1663   const TargetRegisterClass *RC;
1664   LLT ArgTy;
1665 
1666   std::tie(InputPtrReg, RC, ArgTy) =
1667       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1668 
1669   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1670   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1671   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1672     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1673 
1674   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1675 }
1676 
1677 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1678                                             const SDLoc &SL) const {
1679   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1680                                                FIRST_IMPLICIT);
1681   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1682 }
1683 
1684 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1685                                          const SDLoc &SL, SDValue Val,
1686                                          bool Signed,
1687                                          const ISD::InputArg *Arg) const {
1688   // First, if it is a widened vector, narrow it.
1689   if (VT.isVector() &&
1690       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1691     EVT NarrowedVT =
1692         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1693                          VT.getVectorNumElements());
1694     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1695                       DAG.getConstant(0, SL, MVT::i32));
1696   }
1697 
1698   // Then convert the vector elements or scalar value.
1699   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1700       VT.bitsLT(MemVT)) {
1701     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1702     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1703   }
1704 
1705   if (MemVT.isFloatingPoint())
1706     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1707   else if (Signed)
1708     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1709   else
1710     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1711 
1712   return Val;
1713 }
1714 
1715 SDValue SITargetLowering::lowerKernargMemParameter(
1716     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1717     uint64_t Offset, Align Alignment, bool Signed,
1718     const ISD::InputArg *Arg) const {
1719   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1720 
1721   // Try to avoid using an extload by loading earlier than the argument address,
1722   // and extracting the relevant bits. The load should hopefully be merged with
1723   // the previous argument.
1724   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1725     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1726     int64_t AlignDownOffset = alignDown(Offset, 4);
1727     int64_t OffsetDiff = Offset - AlignDownOffset;
1728 
1729     EVT IntVT = MemVT.changeTypeToInteger();
1730 
1731     // TODO: If we passed in the base kernel offset we could have a better
1732     // alignment than 4, but we don't really need it.
1733     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1734     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1735                                MachineMemOperand::MODereferenceable |
1736                                    MachineMemOperand::MOInvariant);
1737 
1738     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1739     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1740 
1741     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1742     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1743     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1744 
1745 
1746     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1747   }
1748 
1749   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1750   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1751                              MachineMemOperand::MODereferenceable |
1752                                  MachineMemOperand::MOInvariant);
1753 
1754   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1755   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1756 }
1757 
1758 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1759                                               const SDLoc &SL, SDValue Chain,
1760                                               const ISD::InputArg &Arg) const {
1761   MachineFunction &MF = DAG.getMachineFunction();
1762   MachineFrameInfo &MFI = MF.getFrameInfo();
1763 
1764   if (Arg.Flags.isByVal()) {
1765     unsigned Size = Arg.Flags.getByValSize();
1766     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1767     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1768   }
1769 
1770   unsigned ArgOffset = VA.getLocMemOffset();
1771   unsigned ArgSize = VA.getValVT().getStoreSize();
1772 
1773   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1774 
1775   // Create load nodes to retrieve arguments from the stack.
1776   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1777   SDValue ArgValue;
1778 
1779   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1780   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1781   MVT MemVT = VA.getValVT();
1782 
1783   switch (VA.getLocInfo()) {
1784   default:
1785     break;
1786   case CCValAssign::BCvt:
1787     MemVT = VA.getLocVT();
1788     break;
1789   case CCValAssign::SExt:
1790     ExtType = ISD::SEXTLOAD;
1791     break;
1792   case CCValAssign::ZExt:
1793     ExtType = ISD::ZEXTLOAD;
1794     break;
1795   case CCValAssign::AExt:
1796     ExtType = ISD::EXTLOAD;
1797     break;
1798   }
1799 
1800   ArgValue = DAG.getExtLoad(
1801     ExtType, SL, VA.getLocVT(), Chain, FIN,
1802     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1803     MemVT);
1804   return ArgValue;
1805 }
1806 
1807 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1808   const SIMachineFunctionInfo &MFI,
1809   EVT VT,
1810   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1811   const ArgDescriptor *Reg;
1812   const TargetRegisterClass *RC;
1813   LLT Ty;
1814 
1815   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1816   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1817 }
1818 
1819 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1820                                CallingConv::ID CallConv,
1821                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1822                                FunctionType *FType,
1823                                SIMachineFunctionInfo *Info) {
1824   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1825     const ISD::InputArg *Arg = &Ins[I];
1826 
1827     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1828            "vector type argument should have been split");
1829 
1830     // First check if it's a PS input addr.
1831     if (CallConv == CallingConv::AMDGPU_PS &&
1832         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1833       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1834 
1835       // Inconveniently only the first part of the split is marked as isSplit,
1836       // so skip to the end. We only want to increment PSInputNum once for the
1837       // entire split argument.
1838       if (Arg->Flags.isSplit()) {
1839         while (!Arg->Flags.isSplitEnd()) {
1840           assert((!Arg->VT.isVector() ||
1841                   Arg->VT.getScalarSizeInBits() == 16) &&
1842                  "unexpected vector split in ps argument type");
1843           if (!SkipArg)
1844             Splits.push_back(*Arg);
1845           Arg = &Ins[++I];
1846         }
1847       }
1848 
1849       if (SkipArg) {
1850         // We can safely skip PS inputs.
1851         Skipped.set(Arg->getOrigArgIndex());
1852         ++PSInputNum;
1853         continue;
1854       }
1855 
1856       Info->markPSInputAllocated(PSInputNum);
1857       if (Arg->Used)
1858         Info->markPSInputEnabled(PSInputNum);
1859 
1860       ++PSInputNum;
1861     }
1862 
1863     Splits.push_back(*Arg);
1864   }
1865 }
1866 
1867 // Allocate special inputs passed in VGPRs.
1868 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1869                                                       MachineFunction &MF,
1870                                                       const SIRegisterInfo &TRI,
1871                                                       SIMachineFunctionInfo &Info) const {
1872   const LLT S32 = LLT::scalar(32);
1873   MachineRegisterInfo &MRI = MF.getRegInfo();
1874 
1875   if (Info.hasWorkItemIDX()) {
1876     Register Reg = AMDGPU::VGPR0;
1877     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1878 
1879     CCInfo.AllocateReg(Reg);
1880     unsigned Mask = (Subtarget->hasPackedTID() &&
1881                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1882     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1883   }
1884 
1885   if (Info.hasWorkItemIDY()) {
1886     assert(Info.hasWorkItemIDX());
1887     if (Subtarget->hasPackedTID()) {
1888       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1889                                                         0x3ff << 10));
1890     } else {
1891       unsigned Reg = AMDGPU::VGPR1;
1892       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1893 
1894       CCInfo.AllocateReg(Reg);
1895       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1896     }
1897   }
1898 
1899   if (Info.hasWorkItemIDZ()) {
1900     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1901     if (Subtarget->hasPackedTID()) {
1902       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1903                                                         0x3ff << 20));
1904     } else {
1905       unsigned Reg = AMDGPU::VGPR2;
1906       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1907 
1908       CCInfo.AllocateReg(Reg);
1909       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1910     }
1911   }
1912 }
1913 
1914 // Try to allocate a VGPR at the end of the argument list, or if no argument
1915 // VGPRs are left allocating a stack slot.
1916 // If \p Mask is is given it indicates bitfield position in the register.
1917 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1918 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1919                                          ArgDescriptor Arg = ArgDescriptor()) {
1920   if (Arg.isSet())
1921     return ArgDescriptor::createArg(Arg, Mask);
1922 
1923   ArrayRef<MCPhysReg> ArgVGPRs
1924     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1925   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1926   if (RegIdx == ArgVGPRs.size()) {
1927     // Spill to stack required.
1928     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1929 
1930     return ArgDescriptor::createStack(Offset, Mask);
1931   }
1932 
1933   unsigned Reg = ArgVGPRs[RegIdx];
1934   Reg = CCInfo.AllocateReg(Reg);
1935   assert(Reg != AMDGPU::NoRegister);
1936 
1937   MachineFunction &MF = CCInfo.getMachineFunction();
1938   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1939   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1940   return ArgDescriptor::createRegister(Reg, Mask);
1941 }
1942 
1943 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1944                                              const TargetRegisterClass *RC,
1945                                              unsigned NumArgRegs) {
1946   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1947   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1948   if (RegIdx == ArgSGPRs.size())
1949     report_fatal_error("ran out of SGPRs for arguments");
1950 
1951   unsigned Reg = ArgSGPRs[RegIdx];
1952   Reg = CCInfo.AllocateReg(Reg);
1953   assert(Reg != AMDGPU::NoRegister);
1954 
1955   MachineFunction &MF = CCInfo.getMachineFunction();
1956   MF.addLiveIn(Reg, RC);
1957   return ArgDescriptor::createRegister(Reg);
1958 }
1959 
1960 // If this has a fixed position, we still should allocate the register in the
1961 // CCInfo state. Technically we could get away with this for values passed
1962 // outside of the normal argument range.
1963 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1964                                        const TargetRegisterClass *RC,
1965                                        MCRegister Reg) {
1966   Reg = CCInfo.AllocateReg(Reg);
1967   assert(Reg != AMDGPU::NoRegister);
1968   MachineFunction &MF = CCInfo.getMachineFunction();
1969   MF.addLiveIn(Reg, RC);
1970 }
1971 
1972 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1973   if (Arg) {
1974     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1975                                Arg.getRegister());
1976   } else
1977     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1978 }
1979 
1980 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1981   if (Arg) {
1982     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1983                                Arg.getRegister());
1984   } else
1985     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1986 }
1987 
1988 /// Allocate implicit function VGPR arguments at the end of allocated user
1989 /// arguments.
1990 void SITargetLowering::allocateSpecialInputVGPRs(
1991   CCState &CCInfo, MachineFunction &MF,
1992   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1993   const unsigned Mask = 0x3ff;
1994   ArgDescriptor Arg;
1995 
1996   if (Info.hasWorkItemIDX()) {
1997     Arg = allocateVGPR32Input(CCInfo, Mask);
1998     Info.setWorkItemIDX(Arg);
1999   }
2000 
2001   if (Info.hasWorkItemIDY()) {
2002     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2003     Info.setWorkItemIDY(Arg);
2004   }
2005 
2006   if (Info.hasWorkItemIDZ())
2007     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2008 }
2009 
2010 /// Allocate implicit function VGPR arguments in fixed registers.
2011 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2012   CCState &CCInfo, MachineFunction &MF,
2013   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2014   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2015   if (!Reg)
2016     report_fatal_error("failed to allocated VGPR for implicit arguments");
2017 
2018   const unsigned Mask = 0x3ff;
2019   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2020   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2021   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2022 }
2023 
2024 void SITargetLowering::allocateSpecialInputSGPRs(
2025   CCState &CCInfo,
2026   MachineFunction &MF,
2027   const SIRegisterInfo &TRI,
2028   SIMachineFunctionInfo &Info) const {
2029   auto &ArgInfo = Info.getArgInfo();
2030 
2031   // TODO: Unify handling with private memory pointers.
2032 
2033   if (Info.hasDispatchPtr())
2034     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2035 
2036   if (Info.hasQueuePtr())
2037     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2038 
2039   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2040   // constant offset from the kernarg segment.
2041   if (Info.hasImplicitArgPtr())
2042     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2043 
2044   if (Info.hasDispatchID())
2045     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2046 
2047   // flat_scratch_init is not applicable for non-kernel functions.
2048 
2049   if (Info.hasWorkGroupIDX())
2050     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2051 
2052   if (Info.hasWorkGroupIDY())
2053     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2054 
2055   if (Info.hasWorkGroupIDZ())
2056     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2057 }
2058 
2059 // Allocate special inputs passed in user SGPRs.
2060 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2061                                             MachineFunction &MF,
2062                                             const SIRegisterInfo &TRI,
2063                                             SIMachineFunctionInfo &Info) const {
2064   if (Info.hasImplicitBufferPtr()) {
2065     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2066     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2067     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2068   }
2069 
2070   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2071   if (Info.hasPrivateSegmentBuffer()) {
2072     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2073     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2074     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2075   }
2076 
2077   if (Info.hasDispatchPtr()) {
2078     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2079     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2080     CCInfo.AllocateReg(DispatchPtrReg);
2081   }
2082 
2083   if (Info.hasQueuePtr()) {
2084     Register QueuePtrReg = Info.addQueuePtr(TRI);
2085     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2086     CCInfo.AllocateReg(QueuePtrReg);
2087   }
2088 
2089   if (Info.hasKernargSegmentPtr()) {
2090     MachineRegisterInfo &MRI = MF.getRegInfo();
2091     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2092     CCInfo.AllocateReg(InputPtrReg);
2093 
2094     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2095     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2096   }
2097 
2098   if (Info.hasDispatchID()) {
2099     Register DispatchIDReg = Info.addDispatchID(TRI);
2100     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2101     CCInfo.AllocateReg(DispatchIDReg);
2102   }
2103 
2104   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2105     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2106     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2107     CCInfo.AllocateReg(FlatScratchInitReg);
2108   }
2109 
2110   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2111   // these from the dispatch pointer.
2112 }
2113 
2114 // Allocate special input registers that are initialized per-wave.
2115 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2116                                            MachineFunction &MF,
2117                                            SIMachineFunctionInfo &Info,
2118                                            CallingConv::ID CallConv,
2119                                            bool IsShader) const {
2120   if (Info.hasWorkGroupIDX()) {
2121     Register Reg = Info.addWorkGroupIDX();
2122     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2123     CCInfo.AllocateReg(Reg);
2124   }
2125 
2126   if (Info.hasWorkGroupIDY()) {
2127     Register Reg = Info.addWorkGroupIDY();
2128     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2129     CCInfo.AllocateReg(Reg);
2130   }
2131 
2132   if (Info.hasWorkGroupIDZ()) {
2133     Register Reg = Info.addWorkGroupIDZ();
2134     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2135     CCInfo.AllocateReg(Reg);
2136   }
2137 
2138   if (Info.hasWorkGroupInfo()) {
2139     Register Reg = Info.addWorkGroupInfo();
2140     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2141     CCInfo.AllocateReg(Reg);
2142   }
2143 
2144   if (Info.hasPrivateSegmentWaveByteOffset()) {
2145     // Scratch wave offset passed in system SGPR.
2146     unsigned PrivateSegmentWaveByteOffsetReg;
2147 
2148     if (IsShader) {
2149       PrivateSegmentWaveByteOffsetReg =
2150         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2151 
2152       // This is true if the scratch wave byte offset doesn't have a fixed
2153       // location.
2154       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2155         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2156         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2157       }
2158     } else
2159       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2160 
2161     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2162     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2163   }
2164 }
2165 
2166 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2167                                      MachineFunction &MF,
2168                                      const SIRegisterInfo &TRI,
2169                                      SIMachineFunctionInfo &Info) {
2170   // Now that we've figured out where the scratch register inputs are, see if
2171   // should reserve the arguments and use them directly.
2172   MachineFrameInfo &MFI = MF.getFrameInfo();
2173   bool HasStackObjects = MFI.hasStackObjects();
2174   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2175 
2176   // Record that we know we have non-spill stack objects so we don't need to
2177   // check all stack objects later.
2178   if (HasStackObjects)
2179     Info.setHasNonSpillStackObjects(true);
2180 
2181   // Everything live out of a block is spilled with fast regalloc, so it's
2182   // almost certain that spilling will be required.
2183   if (TM.getOptLevel() == CodeGenOpt::None)
2184     HasStackObjects = true;
2185 
2186   // For now assume stack access is needed in any callee functions, so we need
2187   // the scratch registers to pass in.
2188   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2189 
2190   if (!ST.enableFlatScratch()) {
2191     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2192       // If we have stack objects, we unquestionably need the private buffer
2193       // resource. For the Code Object V2 ABI, this will be the first 4 user
2194       // SGPR inputs. We can reserve those and use them directly.
2195 
2196       Register PrivateSegmentBufferReg =
2197           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2198       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2199     } else {
2200       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2201       // We tentatively reserve the last registers (skipping the last registers
2202       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2203       // we'll replace these with the ones immediately after those which were
2204       // really allocated. In the prologue copies will be inserted from the
2205       // argument to these reserved registers.
2206 
2207       // Without HSA, relocations are used for the scratch pointer and the
2208       // buffer resource setup is always inserted in the prologue. Scratch wave
2209       // offset is still in an input SGPR.
2210       Info.setScratchRSrcReg(ReservedBufferReg);
2211     }
2212   }
2213 
2214   MachineRegisterInfo &MRI = MF.getRegInfo();
2215 
2216   // For entry functions we have to set up the stack pointer if we use it,
2217   // whereas non-entry functions get this "for free". This means there is no
2218   // intrinsic advantage to using S32 over S34 in cases where we do not have
2219   // calls but do need a frame pointer (i.e. if we are requested to have one
2220   // because frame pointer elimination is disabled). To keep things simple we
2221   // only ever use S32 as the call ABI stack pointer, and so using it does not
2222   // imply we need a separate frame pointer.
2223   //
2224   // Try to use s32 as the SP, but move it if it would interfere with input
2225   // arguments. This won't work with calls though.
2226   //
2227   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2228   // registers.
2229   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2230     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2231   } else {
2232     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2233 
2234     if (MFI.hasCalls())
2235       report_fatal_error("call in graphics shader with too many input SGPRs");
2236 
2237     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2238       if (!MRI.isLiveIn(Reg)) {
2239         Info.setStackPtrOffsetReg(Reg);
2240         break;
2241       }
2242     }
2243 
2244     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2245       report_fatal_error("failed to find register for SP");
2246   }
2247 
2248   // hasFP should be accurate for entry functions even before the frame is
2249   // finalized, because it does not rely on the known stack size, only
2250   // properties like whether variable sized objects are present.
2251   if (ST.getFrameLowering()->hasFP(MF)) {
2252     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2253   }
2254 }
2255 
2256 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2257   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2258   return !Info->isEntryFunction();
2259 }
2260 
2261 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2262 
2263 }
2264 
2265 void SITargetLowering::insertCopiesSplitCSR(
2266   MachineBasicBlock *Entry,
2267   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2268   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2269 
2270   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2271   if (!IStart)
2272     return;
2273 
2274   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2275   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2276   MachineBasicBlock::iterator MBBI = Entry->begin();
2277   for (const MCPhysReg *I = IStart; *I; ++I) {
2278     const TargetRegisterClass *RC = nullptr;
2279     if (AMDGPU::SReg_64RegClass.contains(*I))
2280       RC = &AMDGPU::SGPR_64RegClass;
2281     else if (AMDGPU::SReg_32RegClass.contains(*I))
2282       RC = &AMDGPU::SGPR_32RegClass;
2283     else
2284       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2285 
2286     Register NewVR = MRI->createVirtualRegister(RC);
2287     // Create copy from CSR to a virtual register.
2288     Entry->addLiveIn(*I);
2289     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2290       .addReg(*I);
2291 
2292     // Insert the copy-back instructions right before the terminator.
2293     for (auto *Exit : Exits)
2294       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2295               TII->get(TargetOpcode::COPY), *I)
2296         .addReg(NewVR);
2297   }
2298 }
2299 
2300 SDValue SITargetLowering::LowerFormalArguments(
2301     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2302     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2303     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2304   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2305 
2306   MachineFunction &MF = DAG.getMachineFunction();
2307   const Function &Fn = MF.getFunction();
2308   FunctionType *FType = MF.getFunction().getFunctionType();
2309   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2310 
2311   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2312     DiagnosticInfoUnsupported NoGraphicsHSA(
2313         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2314     DAG.getContext()->diagnose(NoGraphicsHSA);
2315     return DAG.getEntryNode();
2316   }
2317 
2318   Info->allocateModuleLDSGlobal(Fn.getParent());
2319 
2320   SmallVector<ISD::InputArg, 16> Splits;
2321   SmallVector<CCValAssign, 16> ArgLocs;
2322   BitVector Skipped(Ins.size());
2323   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2324                  *DAG.getContext());
2325 
2326   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2327   bool IsKernel = AMDGPU::isKernel(CallConv);
2328   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2329 
2330   if (IsGraphics) {
2331     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2332            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2333            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2334            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2335            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2336            !Info->hasWorkItemIDZ());
2337   }
2338 
2339   if (CallConv == CallingConv::AMDGPU_PS) {
2340     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2341 
2342     // At least one interpolation mode must be enabled or else the GPU will
2343     // hang.
2344     //
2345     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2346     // set PSInputAddr, the user wants to enable some bits after the compilation
2347     // based on run-time states. Since we can't know what the final PSInputEna
2348     // will look like, so we shouldn't do anything here and the user should take
2349     // responsibility for the correct programming.
2350     //
2351     // Otherwise, the following restrictions apply:
2352     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2353     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2354     //   enabled too.
2355     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2356         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2357       CCInfo.AllocateReg(AMDGPU::VGPR0);
2358       CCInfo.AllocateReg(AMDGPU::VGPR1);
2359       Info->markPSInputAllocated(0);
2360       Info->markPSInputEnabled(0);
2361     }
2362     if (Subtarget->isAmdPalOS()) {
2363       // For isAmdPalOS, the user does not enable some bits after compilation
2364       // based on run-time states; the register values being generated here are
2365       // the final ones set in hardware. Therefore we need to apply the
2366       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2367       // a bit is set in PSInputAddr but not PSInputEnable is where the
2368       // frontend set up an input arg for a particular interpolation mode, but
2369       // nothing uses that input arg. Really we should have an earlier pass
2370       // that removes such an arg.)
2371       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2372       if ((PsInputBits & 0x7F) == 0 ||
2373           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2374         Info->markPSInputEnabled(
2375             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2376     }
2377   } else if (IsKernel) {
2378     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2379   } else {
2380     Splits.append(Ins.begin(), Ins.end());
2381   }
2382 
2383   if (IsEntryFunc) {
2384     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2385     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2386   } else {
2387     // For the fixed ABI, pass workitem IDs in the last argument register.
2388     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2389       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2390   }
2391 
2392   if (IsKernel) {
2393     analyzeFormalArgumentsCompute(CCInfo, Ins);
2394   } else {
2395     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2396     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2397   }
2398 
2399   SmallVector<SDValue, 16> Chains;
2400 
2401   // FIXME: This is the minimum kernel argument alignment. We should improve
2402   // this to the maximum alignment of the arguments.
2403   //
2404   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2405   // kern arg offset.
2406   const Align KernelArgBaseAlign = Align(16);
2407 
2408   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2409     const ISD::InputArg &Arg = Ins[i];
2410     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2411       InVals.push_back(DAG.getUNDEF(Arg.VT));
2412       continue;
2413     }
2414 
2415     CCValAssign &VA = ArgLocs[ArgIdx++];
2416     MVT VT = VA.getLocVT();
2417 
2418     if (IsEntryFunc && VA.isMemLoc()) {
2419       VT = Ins[i].VT;
2420       EVT MemVT = VA.getLocVT();
2421 
2422       const uint64_t Offset = VA.getLocMemOffset();
2423       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2424 
2425       if (Arg.Flags.isByRef()) {
2426         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2427 
2428         const GCNTargetMachine &TM =
2429             static_cast<const GCNTargetMachine &>(getTargetMachine());
2430         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2431                                     Arg.Flags.getPointerAddrSpace())) {
2432           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2433                                      Arg.Flags.getPointerAddrSpace());
2434         }
2435 
2436         InVals.push_back(Ptr);
2437         continue;
2438       }
2439 
2440       SDValue Arg = lowerKernargMemParameter(
2441         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2442       Chains.push_back(Arg.getValue(1));
2443 
2444       auto *ParamTy =
2445         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2446       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2447           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2448                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2449         // On SI local pointers are just offsets into LDS, so they are always
2450         // less than 16-bits.  On CI and newer they could potentially be
2451         // real pointers, so we can't guarantee their size.
2452         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2453                           DAG.getValueType(MVT::i16));
2454       }
2455 
2456       InVals.push_back(Arg);
2457       continue;
2458     } else if (!IsEntryFunc && VA.isMemLoc()) {
2459       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2460       InVals.push_back(Val);
2461       if (!Arg.Flags.isByVal())
2462         Chains.push_back(Val.getValue(1));
2463       continue;
2464     }
2465 
2466     assert(VA.isRegLoc() && "Parameter must be in a register!");
2467 
2468     Register Reg = VA.getLocReg();
2469     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2470     EVT ValVT = VA.getValVT();
2471 
2472     Reg = MF.addLiveIn(Reg, RC);
2473     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2474 
2475     if (Arg.Flags.isSRet()) {
2476       // The return object should be reasonably addressable.
2477 
2478       // FIXME: This helps when the return is a real sret. If it is a
2479       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2480       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2481       unsigned NumBits
2482         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2483       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2484         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2485     }
2486 
2487     // If this is an 8 or 16-bit value, it is really passed promoted
2488     // to 32 bits. Insert an assert[sz]ext to capture this, then
2489     // truncate to the right size.
2490     switch (VA.getLocInfo()) {
2491     case CCValAssign::Full:
2492       break;
2493     case CCValAssign::BCvt:
2494       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2495       break;
2496     case CCValAssign::SExt:
2497       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2498                         DAG.getValueType(ValVT));
2499       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2500       break;
2501     case CCValAssign::ZExt:
2502       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2503                         DAG.getValueType(ValVT));
2504       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2505       break;
2506     case CCValAssign::AExt:
2507       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2508       break;
2509     default:
2510       llvm_unreachable("Unknown loc info!");
2511     }
2512 
2513     InVals.push_back(Val);
2514   }
2515 
2516   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2517     // Special inputs come after user arguments.
2518     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2519   }
2520 
2521   // Start adding system SGPRs.
2522   if (IsEntryFunc) {
2523     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2524   } else {
2525     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2526     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2527   }
2528 
2529   auto &ArgUsageInfo =
2530     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2531   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2532 
2533   unsigned StackArgSize = CCInfo.getNextStackOffset();
2534   Info->setBytesInStackArgArea(StackArgSize);
2535 
2536   return Chains.empty() ? Chain :
2537     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2538 }
2539 
2540 // TODO: If return values can't fit in registers, we should return as many as
2541 // possible in registers before passing on stack.
2542 bool SITargetLowering::CanLowerReturn(
2543   CallingConv::ID CallConv,
2544   MachineFunction &MF, bool IsVarArg,
2545   const SmallVectorImpl<ISD::OutputArg> &Outs,
2546   LLVMContext &Context) const {
2547   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2548   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2549   // for shaders. Vector types should be explicitly handled by CC.
2550   if (AMDGPU::isEntryFunctionCC(CallConv))
2551     return true;
2552 
2553   SmallVector<CCValAssign, 16> RVLocs;
2554   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2555   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2556 }
2557 
2558 SDValue
2559 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2560                               bool isVarArg,
2561                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2562                               const SmallVectorImpl<SDValue> &OutVals,
2563                               const SDLoc &DL, SelectionDAG &DAG) const {
2564   MachineFunction &MF = DAG.getMachineFunction();
2565   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2566 
2567   if (AMDGPU::isKernel(CallConv)) {
2568     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2569                                              OutVals, DL, DAG);
2570   }
2571 
2572   bool IsShader = AMDGPU::isShader(CallConv);
2573 
2574   Info->setIfReturnsVoid(Outs.empty());
2575   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2576 
2577   // CCValAssign - represent the assignment of the return value to a location.
2578   SmallVector<CCValAssign, 48> RVLocs;
2579   SmallVector<ISD::OutputArg, 48> Splits;
2580 
2581   // CCState - Info about the registers and stack slots.
2582   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2583                  *DAG.getContext());
2584 
2585   // Analyze outgoing return values.
2586   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2587 
2588   SDValue Flag;
2589   SmallVector<SDValue, 48> RetOps;
2590   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2591 
2592   // Add return address for callable functions.
2593   if (!Info->isEntryFunction()) {
2594     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2595     SDValue ReturnAddrReg = CreateLiveInRegister(
2596       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2597 
2598     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2599         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2600         MVT::i64);
2601     Chain =
2602         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2603     Flag = Chain.getValue(1);
2604     RetOps.push_back(ReturnAddrVirtualReg);
2605   }
2606 
2607   // Copy the result values into the output registers.
2608   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2609        ++I, ++RealRVLocIdx) {
2610     CCValAssign &VA = RVLocs[I];
2611     assert(VA.isRegLoc() && "Can only return in registers!");
2612     // TODO: Partially return in registers if return values don't fit.
2613     SDValue Arg = OutVals[RealRVLocIdx];
2614 
2615     // Copied from other backends.
2616     switch (VA.getLocInfo()) {
2617     case CCValAssign::Full:
2618       break;
2619     case CCValAssign::BCvt:
2620       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2621       break;
2622     case CCValAssign::SExt:
2623       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2624       break;
2625     case CCValAssign::ZExt:
2626       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2627       break;
2628     case CCValAssign::AExt:
2629       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2630       break;
2631     default:
2632       llvm_unreachable("Unknown loc info!");
2633     }
2634 
2635     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2636     Flag = Chain.getValue(1);
2637     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2638   }
2639 
2640   // FIXME: Does sret work properly?
2641   if (!Info->isEntryFunction()) {
2642     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2643     const MCPhysReg *I =
2644       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2645     if (I) {
2646       for (; *I; ++I) {
2647         if (AMDGPU::SReg_64RegClass.contains(*I))
2648           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2649         else if (AMDGPU::SReg_32RegClass.contains(*I))
2650           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2651         else
2652           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2653       }
2654     }
2655   }
2656 
2657   // Update chain and glue.
2658   RetOps[0] = Chain;
2659   if (Flag.getNode())
2660     RetOps.push_back(Flag);
2661 
2662   unsigned Opc = AMDGPUISD::ENDPGM;
2663   if (!IsWaveEnd)
2664     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2665   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2666 }
2667 
2668 SDValue SITargetLowering::LowerCallResult(
2669     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2670     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2671     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2672     SDValue ThisVal) const {
2673   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2674 
2675   // Assign locations to each value returned by this call.
2676   SmallVector<CCValAssign, 16> RVLocs;
2677   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2678                  *DAG.getContext());
2679   CCInfo.AnalyzeCallResult(Ins, RetCC);
2680 
2681   // Copy all of the result registers out of their specified physreg.
2682   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2683     CCValAssign VA = RVLocs[i];
2684     SDValue Val;
2685 
2686     if (VA.isRegLoc()) {
2687       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2688       Chain = Val.getValue(1);
2689       InFlag = Val.getValue(2);
2690     } else if (VA.isMemLoc()) {
2691       report_fatal_error("TODO: return values in memory");
2692     } else
2693       llvm_unreachable("unknown argument location type");
2694 
2695     switch (VA.getLocInfo()) {
2696     case CCValAssign::Full:
2697       break;
2698     case CCValAssign::BCvt:
2699       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2700       break;
2701     case CCValAssign::ZExt:
2702       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2703                         DAG.getValueType(VA.getValVT()));
2704       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2705       break;
2706     case CCValAssign::SExt:
2707       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2708                         DAG.getValueType(VA.getValVT()));
2709       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2710       break;
2711     case CCValAssign::AExt:
2712       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2713       break;
2714     default:
2715       llvm_unreachable("Unknown loc info!");
2716     }
2717 
2718     InVals.push_back(Val);
2719   }
2720 
2721   return Chain;
2722 }
2723 
2724 // Add code to pass special inputs required depending on used features separate
2725 // from the explicit user arguments present in the IR.
2726 void SITargetLowering::passSpecialInputs(
2727     CallLoweringInfo &CLI,
2728     CCState &CCInfo,
2729     const SIMachineFunctionInfo &Info,
2730     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2731     SmallVectorImpl<SDValue> &MemOpChains,
2732     SDValue Chain) const {
2733   // If we don't have a call site, this was a call inserted by
2734   // legalization. These can never use special inputs.
2735   if (!CLI.CB)
2736     return;
2737 
2738   SelectionDAG &DAG = CLI.DAG;
2739   const SDLoc &DL = CLI.DL;
2740 
2741   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2742   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2743 
2744   const AMDGPUFunctionArgInfo *CalleeArgInfo
2745     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2746   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2747     auto &ArgUsageInfo =
2748       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2749     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2750   }
2751 
2752   // TODO: Unify with private memory register handling. This is complicated by
2753   // the fact that at least in kernels, the input argument is not necessarily
2754   // in the same location as the input.
2755   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2756     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2757     AMDGPUFunctionArgInfo::QUEUE_PTR,
2758     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2759     AMDGPUFunctionArgInfo::DISPATCH_ID,
2760     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2761     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2762     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2763   };
2764 
2765   for (auto InputID : InputRegs) {
2766     const ArgDescriptor *OutgoingArg;
2767     const TargetRegisterClass *ArgRC;
2768     LLT ArgTy;
2769 
2770     std::tie(OutgoingArg, ArgRC, ArgTy) =
2771         CalleeArgInfo->getPreloadedValue(InputID);
2772     if (!OutgoingArg)
2773       continue;
2774 
2775     const ArgDescriptor *IncomingArg;
2776     const TargetRegisterClass *IncomingArgRC;
2777     LLT Ty;
2778     std::tie(IncomingArg, IncomingArgRC, Ty) =
2779         CallerArgInfo.getPreloadedValue(InputID);
2780     assert(IncomingArgRC == ArgRC);
2781 
2782     // All special arguments are ints for now.
2783     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2784     SDValue InputReg;
2785 
2786     if (IncomingArg) {
2787       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2788     } else {
2789       // The implicit arg ptr is special because it doesn't have a corresponding
2790       // input for kernels, and is computed from the kernarg segment pointer.
2791       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2792       InputReg = getImplicitArgPtr(DAG, DL);
2793     }
2794 
2795     if (OutgoingArg->isRegister()) {
2796       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2797       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2798         report_fatal_error("failed to allocate implicit input argument");
2799     } else {
2800       unsigned SpecialArgOffset =
2801           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2802       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2803                                               SpecialArgOffset);
2804       MemOpChains.push_back(ArgStore);
2805     }
2806   }
2807 
2808   // Pack workitem IDs into a single register or pass it as is if already
2809   // packed.
2810   const ArgDescriptor *OutgoingArg;
2811   const TargetRegisterClass *ArgRC;
2812   LLT Ty;
2813 
2814   std::tie(OutgoingArg, ArgRC, Ty) =
2815       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2816   if (!OutgoingArg)
2817     std::tie(OutgoingArg, ArgRC, Ty) =
2818         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2819   if (!OutgoingArg)
2820     std::tie(OutgoingArg, ArgRC, Ty) =
2821         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2822   if (!OutgoingArg)
2823     return;
2824 
2825   const ArgDescriptor *IncomingArgX = std::get<0>(
2826       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2827   const ArgDescriptor *IncomingArgY = std::get<0>(
2828       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2829   const ArgDescriptor *IncomingArgZ = std::get<0>(
2830       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2831 
2832   SDValue InputReg;
2833   SDLoc SL;
2834 
2835   // If incoming ids are not packed we need to pack them.
2836   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2837     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2838 
2839   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2840     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2841     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2842                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2843     InputReg = InputReg.getNode() ?
2844                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2845   }
2846 
2847   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2848     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2849     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2850                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2851     InputReg = InputReg.getNode() ?
2852                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2853   }
2854 
2855   if (!InputReg.getNode()) {
2856     // Workitem ids are already packed, any of present incoming arguments
2857     // will carry all required fields.
2858     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2859       IncomingArgX ? *IncomingArgX :
2860       IncomingArgY ? *IncomingArgY :
2861                      *IncomingArgZ, ~0u);
2862     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2863   }
2864 
2865   if (OutgoingArg->isRegister()) {
2866     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2867     CCInfo.AllocateReg(OutgoingArg->getRegister());
2868   } else {
2869     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2870     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2871                                             SpecialArgOffset);
2872     MemOpChains.push_back(ArgStore);
2873   }
2874 }
2875 
2876 static bool canGuaranteeTCO(CallingConv::ID CC) {
2877   return CC == CallingConv::Fast;
2878 }
2879 
2880 /// Return true if we might ever do TCO for calls with this calling convention.
2881 static bool mayTailCallThisCC(CallingConv::ID CC) {
2882   switch (CC) {
2883   case CallingConv::C:
2884   case CallingConv::AMDGPU_Gfx:
2885     return true;
2886   default:
2887     return canGuaranteeTCO(CC);
2888   }
2889 }
2890 
2891 bool SITargetLowering::isEligibleForTailCallOptimization(
2892     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2893     const SmallVectorImpl<ISD::OutputArg> &Outs,
2894     const SmallVectorImpl<SDValue> &OutVals,
2895     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2896   if (!mayTailCallThisCC(CalleeCC))
2897     return false;
2898 
2899   // For a divergent call target, we need to do a waterfall loop over the
2900   // possible callees which precludes us from using a simple jump.
2901   if (Callee->isDivergent())
2902     return false;
2903 
2904   MachineFunction &MF = DAG.getMachineFunction();
2905   const Function &CallerF = MF.getFunction();
2906   CallingConv::ID CallerCC = CallerF.getCallingConv();
2907   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2908   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2909 
2910   // Kernels aren't callable, and don't have a live in return address so it
2911   // doesn't make sense to do a tail call with entry functions.
2912   if (!CallerPreserved)
2913     return false;
2914 
2915   bool CCMatch = CallerCC == CalleeCC;
2916 
2917   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2918     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2919       return true;
2920     return false;
2921   }
2922 
2923   // TODO: Can we handle var args?
2924   if (IsVarArg)
2925     return false;
2926 
2927   for (const Argument &Arg : CallerF.args()) {
2928     if (Arg.hasByValAttr())
2929       return false;
2930   }
2931 
2932   LLVMContext &Ctx = *DAG.getContext();
2933 
2934   // Check that the call results are passed in the same way.
2935   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2936                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2937                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2938     return false;
2939 
2940   // The callee has to preserve all registers the caller needs to preserve.
2941   if (!CCMatch) {
2942     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2943     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2944       return false;
2945   }
2946 
2947   // Nothing more to check if the callee is taking no arguments.
2948   if (Outs.empty())
2949     return true;
2950 
2951   SmallVector<CCValAssign, 16> ArgLocs;
2952   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2953 
2954   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2955 
2956   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2957   // If the stack arguments for this call do not fit into our own save area then
2958   // the call cannot be made tail.
2959   // TODO: Is this really necessary?
2960   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2961     return false;
2962 
2963   const MachineRegisterInfo &MRI = MF.getRegInfo();
2964   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2965 }
2966 
2967 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2968   if (!CI->isTailCall())
2969     return false;
2970 
2971   const Function *ParentFn = CI->getParent()->getParent();
2972   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2973     return false;
2974   return true;
2975 }
2976 
2977 // The wave scratch offset register is used as the global base pointer.
2978 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2979                                     SmallVectorImpl<SDValue> &InVals) const {
2980   SelectionDAG &DAG = CLI.DAG;
2981   const SDLoc &DL = CLI.DL;
2982   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2983   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2984   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2985   SDValue Chain = CLI.Chain;
2986   SDValue Callee = CLI.Callee;
2987   bool &IsTailCall = CLI.IsTailCall;
2988   CallingConv::ID CallConv = CLI.CallConv;
2989   bool IsVarArg = CLI.IsVarArg;
2990   bool IsSibCall = false;
2991   bool IsThisReturn = false;
2992   MachineFunction &MF = DAG.getMachineFunction();
2993 
2994   if (Callee.isUndef() || isNullConstant(Callee)) {
2995     if (!CLI.IsTailCall) {
2996       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2997         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2998     }
2999 
3000     return Chain;
3001   }
3002 
3003   if (IsVarArg) {
3004     return lowerUnhandledCall(CLI, InVals,
3005                               "unsupported call to variadic function ");
3006   }
3007 
3008   if (!CLI.CB)
3009     report_fatal_error("unsupported libcall legalization");
3010 
3011   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3012     return lowerUnhandledCall(CLI, InVals,
3013                               "unsupported required tail call to function ");
3014   }
3015 
3016   if (AMDGPU::isShader(CallConv)) {
3017     // Note the issue is with the CC of the called function, not of the call
3018     // itself.
3019     return lowerUnhandledCall(CLI, InVals,
3020                               "unsupported call to a shader function ");
3021   }
3022 
3023   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3024       CallConv != CallingConv::AMDGPU_Gfx) {
3025     // Only allow calls with specific calling conventions.
3026     return lowerUnhandledCall(CLI, InVals,
3027                               "unsupported calling convention for call from "
3028                               "graphics shader of function ");
3029   }
3030 
3031   if (IsTailCall) {
3032     IsTailCall = isEligibleForTailCallOptimization(
3033       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3034     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3035       report_fatal_error("failed to perform tail call elimination on a call "
3036                          "site marked musttail");
3037     }
3038 
3039     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3040 
3041     // A sibling call is one where we're under the usual C ABI and not planning
3042     // to change that but can still do a tail call:
3043     if (!TailCallOpt && IsTailCall)
3044       IsSibCall = true;
3045 
3046     if (IsTailCall)
3047       ++NumTailCalls;
3048   }
3049 
3050   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3051   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3052   SmallVector<SDValue, 8> MemOpChains;
3053 
3054   // Analyze operands of the call, assigning locations to each operand.
3055   SmallVector<CCValAssign, 16> ArgLocs;
3056   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3057   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3058 
3059   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3060       CallConv != CallingConv::AMDGPU_Gfx) {
3061     // With a fixed ABI, allocate fixed registers before user arguments.
3062     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3063   }
3064 
3065   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3066 
3067   // Get a count of how many bytes are to be pushed on the stack.
3068   unsigned NumBytes = CCInfo.getNextStackOffset();
3069 
3070   if (IsSibCall) {
3071     // Since we're not changing the ABI to make this a tail call, the memory
3072     // operands are already available in the caller's incoming argument space.
3073     NumBytes = 0;
3074   }
3075 
3076   // FPDiff is the byte offset of the call's argument area from the callee's.
3077   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3078   // by this amount for a tail call. In a sibling call it must be 0 because the
3079   // caller will deallocate the entire stack and the callee still expects its
3080   // arguments to begin at SP+0. Completely unused for non-tail calls.
3081   int32_t FPDiff = 0;
3082   MachineFrameInfo &MFI = MF.getFrameInfo();
3083 
3084   // Adjust the stack pointer for the new arguments...
3085   // These operations are automatically eliminated by the prolog/epilog pass
3086   if (!IsSibCall) {
3087     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3088 
3089     if (!Subtarget->enableFlatScratch()) {
3090       SmallVector<SDValue, 4> CopyFromChains;
3091 
3092       // In the HSA case, this should be an identity copy.
3093       SDValue ScratchRSrcReg
3094         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3095       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3096       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3097       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3098     }
3099   }
3100 
3101   MVT PtrVT = MVT::i32;
3102 
3103   // Walk the register/memloc assignments, inserting copies/loads.
3104   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3105     CCValAssign &VA = ArgLocs[i];
3106     SDValue Arg = OutVals[i];
3107 
3108     // Promote the value if needed.
3109     switch (VA.getLocInfo()) {
3110     case CCValAssign::Full:
3111       break;
3112     case CCValAssign::BCvt:
3113       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3114       break;
3115     case CCValAssign::ZExt:
3116       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3117       break;
3118     case CCValAssign::SExt:
3119       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3120       break;
3121     case CCValAssign::AExt:
3122       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3123       break;
3124     case CCValAssign::FPExt:
3125       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3126       break;
3127     default:
3128       llvm_unreachable("Unknown loc info!");
3129     }
3130 
3131     if (VA.isRegLoc()) {
3132       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3133     } else {
3134       assert(VA.isMemLoc());
3135 
3136       SDValue DstAddr;
3137       MachinePointerInfo DstInfo;
3138 
3139       unsigned LocMemOffset = VA.getLocMemOffset();
3140       int32_t Offset = LocMemOffset;
3141 
3142       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3143       MaybeAlign Alignment;
3144 
3145       if (IsTailCall) {
3146         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3147         unsigned OpSize = Flags.isByVal() ?
3148           Flags.getByValSize() : VA.getValVT().getStoreSize();
3149 
3150         // FIXME: We can have better than the minimum byval required alignment.
3151         Alignment =
3152             Flags.isByVal()
3153                 ? Flags.getNonZeroByValAlign()
3154                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3155 
3156         Offset = Offset + FPDiff;
3157         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3158 
3159         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3160         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3161 
3162         // Make sure any stack arguments overlapping with where we're storing
3163         // are loaded before this eventual operation. Otherwise they'll be
3164         // clobbered.
3165 
3166         // FIXME: Why is this really necessary? This seems to just result in a
3167         // lot of code to copy the stack and write them back to the same
3168         // locations, which are supposed to be immutable?
3169         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3170       } else {
3171         // Stores to the argument stack area are relative to the stack pointer.
3172         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3173                                         MVT::i32);
3174         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3175         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3176         Alignment =
3177             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3178       }
3179 
3180       if (Outs[i].Flags.isByVal()) {
3181         SDValue SizeNode =
3182             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3183         SDValue Cpy =
3184             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3185                           Outs[i].Flags.getNonZeroByValAlign(),
3186                           /*isVol = */ false, /*AlwaysInline = */ true,
3187                           /*isTailCall = */ false, DstInfo,
3188                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3189 
3190         MemOpChains.push_back(Cpy);
3191       } else {
3192         SDValue Store =
3193             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3194         MemOpChains.push_back(Store);
3195       }
3196     }
3197   }
3198 
3199   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3200       CallConv != CallingConv::AMDGPU_Gfx) {
3201     // Copy special input registers after user input arguments.
3202     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3203   }
3204 
3205   if (!MemOpChains.empty())
3206     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3207 
3208   // Build a sequence of copy-to-reg nodes chained together with token chain
3209   // and flag operands which copy the outgoing args into the appropriate regs.
3210   SDValue InFlag;
3211   for (auto &RegToPass : RegsToPass) {
3212     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3213                              RegToPass.second, InFlag);
3214     InFlag = Chain.getValue(1);
3215   }
3216 
3217 
3218   SDValue PhysReturnAddrReg;
3219   if (IsTailCall) {
3220     // Since the return is being combined with the call, we need to pass on the
3221     // return address.
3222 
3223     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3224     SDValue ReturnAddrReg = CreateLiveInRegister(
3225       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3226 
3227     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3228                                         MVT::i64);
3229     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3230     InFlag = Chain.getValue(1);
3231   }
3232 
3233   // We don't usually want to end the call-sequence here because we would tidy
3234   // the frame up *after* the call, however in the ABI-changing tail-call case
3235   // we've carefully laid out the parameters so that when sp is reset they'll be
3236   // in the correct location.
3237   if (IsTailCall && !IsSibCall) {
3238     Chain = DAG.getCALLSEQ_END(Chain,
3239                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3240                                DAG.getTargetConstant(0, DL, MVT::i32),
3241                                InFlag, DL);
3242     InFlag = Chain.getValue(1);
3243   }
3244 
3245   std::vector<SDValue> Ops;
3246   Ops.push_back(Chain);
3247   Ops.push_back(Callee);
3248   // Add a redundant copy of the callee global which will not be legalized, as
3249   // we need direct access to the callee later.
3250   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3251     const GlobalValue *GV = GSD->getGlobal();
3252     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3253   } else {
3254     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3255   }
3256 
3257   if (IsTailCall) {
3258     // Each tail call may have to adjust the stack by a different amount, so
3259     // this information must travel along with the operation for eventual
3260     // consumption by emitEpilogue.
3261     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3262 
3263     Ops.push_back(PhysReturnAddrReg);
3264   }
3265 
3266   // Add argument registers to the end of the list so that they are known live
3267   // into the call.
3268   for (auto &RegToPass : RegsToPass) {
3269     Ops.push_back(DAG.getRegister(RegToPass.first,
3270                                   RegToPass.second.getValueType()));
3271   }
3272 
3273   // Add a register mask operand representing the call-preserved registers.
3274 
3275   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3276   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3277   assert(Mask && "Missing call preserved mask for calling convention");
3278   Ops.push_back(DAG.getRegisterMask(Mask));
3279 
3280   if (InFlag.getNode())
3281     Ops.push_back(InFlag);
3282 
3283   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3284 
3285   // If we're doing a tall call, use a TC_RETURN here rather than an
3286   // actual call instruction.
3287   if (IsTailCall) {
3288     MFI.setHasTailCall();
3289     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3290   }
3291 
3292   // Returns a chain and a flag for retval copy to use.
3293   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3294   Chain = Call.getValue(0);
3295   InFlag = Call.getValue(1);
3296 
3297   uint64_t CalleePopBytes = NumBytes;
3298   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3299                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3300                              InFlag, DL);
3301   if (!Ins.empty())
3302     InFlag = Chain.getValue(1);
3303 
3304   // Handle result values, copying them out of physregs into vregs that we
3305   // return.
3306   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3307                          InVals, IsThisReturn,
3308                          IsThisReturn ? OutVals[0] : SDValue());
3309 }
3310 
3311 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3312 // except for applying the wave size scale to the increment amount.
3313 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3314     SDValue Op, SelectionDAG &DAG) const {
3315   const MachineFunction &MF = DAG.getMachineFunction();
3316   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3317 
3318   SDLoc dl(Op);
3319   EVT VT = Op.getValueType();
3320   SDValue Tmp1 = Op;
3321   SDValue Tmp2 = Op.getValue(1);
3322   SDValue Tmp3 = Op.getOperand(2);
3323   SDValue Chain = Tmp1.getOperand(0);
3324 
3325   Register SPReg = Info->getStackPtrOffsetReg();
3326 
3327   // Chain the dynamic stack allocation so that it doesn't modify the stack
3328   // pointer when other instructions are using the stack.
3329   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3330 
3331   SDValue Size  = Tmp2.getOperand(1);
3332   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3333   Chain = SP.getValue(1);
3334   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3335   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3336   const TargetFrameLowering *TFL = ST.getFrameLowering();
3337   unsigned Opc =
3338     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3339     ISD::ADD : ISD::SUB;
3340 
3341   SDValue ScaledSize = DAG.getNode(
3342       ISD::SHL, dl, VT, Size,
3343       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3344 
3345   Align StackAlign = TFL->getStackAlign();
3346   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3347   if (Alignment && *Alignment > StackAlign) {
3348     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3349                        DAG.getConstant(-(uint64_t)Alignment->value()
3350                                            << ST.getWavefrontSizeLog2(),
3351                                        dl, VT));
3352   }
3353 
3354   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3355   Tmp2 = DAG.getCALLSEQ_END(
3356       Chain, DAG.getIntPtrConstant(0, dl, true),
3357       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3358 
3359   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3360 }
3361 
3362 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3363                                                   SelectionDAG &DAG) const {
3364   // We only handle constant sizes here to allow non-entry block, static sized
3365   // allocas. A truly dynamic value is more difficult to support because we
3366   // don't know if the size value is uniform or not. If the size isn't uniform,
3367   // we would need to do a wave reduction to get the maximum size to know how
3368   // much to increment the uniform stack pointer.
3369   SDValue Size = Op.getOperand(1);
3370   if (isa<ConstantSDNode>(Size))
3371       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3372 
3373   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3374 }
3375 
3376 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3377                                              const MachineFunction &MF) const {
3378   Register Reg = StringSwitch<Register>(RegName)
3379     .Case("m0", AMDGPU::M0)
3380     .Case("exec", AMDGPU::EXEC)
3381     .Case("exec_lo", AMDGPU::EXEC_LO)
3382     .Case("exec_hi", AMDGPU::EXEC_HI)
3383     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3384     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3385     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3386     .Default(Register());
3387 
3388   if (Reg == AMDGPU::NoRegister) {
3389     report_fatal_error(Twine("invalid register name \""
3390                              + StringRef(RegName)  + "\"."));
3391 
3392   }
3393 
3394   if (!Subtarget->hasFlatScrRegister() &&
3395        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3396     report_fatal_error(Twine("invalid register \""
3397                              + StringRef(RegName)  + "\" for subtarget."));
3398   }
3399 
3400   switch (Reg) {
3401   case AMDGPU::M0:
3402   case AMDGPU::EXEC_LO:
3403   case AMDGPU::EXEC_HI:
3404   case AMDGPU::FLAT_SCR_LO:
3405   case AMDGPU::FLAT_SCR_HI:
3406     if (VT.getSizeInBits() == 32)
3407       return Reg;
3408     break;
3409   case AMDGPU::EXEC:
3410   case AMDGPU::FLAT_SCR:
3411     if (VT.getSizeInBits() == 64)
3412       return Reg;
3413     break;
3414   default:
3415     llvm_unreachable("missing register type checking");
3416   }
3417 
3418   report_fatal_error(Twine("invalid type for register \""
3419                            + StringRef(RegName) + "\"."));
3420 }
3421 
3422 // If kill is not the last instruction, split the block so kill is always a
3423 // proper terminator.
3424 MachineBasicBlock *
3425 SITargetLowering::splitKillBlock(MachineInstr &MI,
3426                                  MachineBasicBlock *BB) const {
3427   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3428   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3429   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3430   return SplitBB;
3431 }
3432 
3433 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3434 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3435 // be the first instruction in the remainder block.
3436 //
3437 /// \returns { LoopBody, Remainder }
3438 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3439 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3440   MachineFunction *MF = MBB.getParent();
3441   MachineBasicBlock::iterator I(&MI);
3442 
3443   // To insert the loop we need to split the block. Move everything after this
3444   // point to a new block, and insert a new empty block between the two.
3445   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3446   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3447   MachineFunction::iterator MBBI(MBB);
3448   ++MBBI;
3449 
3450   MF->insert(MBBI, LoopBB);
3451   MF->insert(MBBI, RemainderBB);
3452 
3453   LoopBB->addSuccessor(LoopBB);
3454   LoopBB->addSuccessor(RemainderBB);
3455 
3456   // Move the rest of the block into a new block.
3457   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3458 
3459   if (InstInLoop) {
3460     auto Next = std::next(I);
3461 
3462     // Move instruction to loop body.
3463     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3464 
3465     // Move the rest of the block.
3466     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3467   } else {
3468     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3469   }
3470 
3471   MBB.addSuccessor(LoopBB);
3472 
3473   return std::make_pair(LoopBB, RemainderBB);
3474 }
3475 
3476 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3477 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3478   MachineBasicBlock *MBB = MI.getParent();
3479   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3480   auto I = MI.getIterator();
3481   auto E = std::next(I);
3482 
3483   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3484     .addImm(0);
3485 
3486   MIBundleBuilder Bundler(*MBB, I, E);
3487   finalizeBundle(*MBB, Bundler.begin());
3488 }
3489 
3490 MachineBasicBlock *
3491 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3492                                          MachineBasicBlock *BB) const {
3493   const DebugLoc &DL = MI.getDebugLoc();
3494 
3495   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3496 
3497   MachineBasicBlock *LoopBB;
3498   MachineBasicBlock *RemainderBB;
3499   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3500 
3501   // Apparently kill flags are only valid if the def is in the same block?
3502   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3503     Src->setIsKill(false);
3504 
3505   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3506 
3507   MachineBasicBlock::iterator I = LoopBB->end();
3508 
3509   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3510     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3511 
3512   // Clear TRAP_STS.MEM_VIOL
3513   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3514     .addImm(0)
3515     .addImm(EncodedReg);
3516 
3517   bundleInstWithWaitcnt(MI);
3518 
3519   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3520 
3521   // Load and check TRAP_STS.MEM_VIOL
3522   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3523     .addImm(EncodedReg);
3524 
3525   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3526   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3527     .addReg(Reg, RegState::Kill)
3528     .addImm(0);
3529   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3530     .addMBB(LoopBB);
3531 
3532   return RemainderBB;
3533 }
3534 
3535 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3536 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3537 // will only do one iteration. In the worst case, this will loop 64 times.
3538 //
3539 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3540 static MachineBasicBlock::iterator
3541 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3542                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3543                        const DebugLoc &DL, const MachineOperand &Idx,
3544                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3545                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3546                        Register &SGPRIdxReg) {
3547 
3548   MachineFunction *MF = OrigBB.getParent();
3549   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3550   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3551   MachineBasicBlock::iterator I = LoopBB.begin();
3552 
3553   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3554   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3555   Register NewExec = MRI.createVirtualRegister(BoolRC);
3556   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3557   Register CondReg = MRI.createVirtualRegister(BoolRC);
3558 
3559   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3560     .addReg(InitReg)
3561     .addMBB(&OrigBB)
3562     .addReg(ResultReg)
3563     .addMBB(&LoopBB);
3564 
3565   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3566     .addReg(InitSaveExecReg)
3567     .addMBB(&OrigBB)
3568     .addReg(NewExec)
3569     .addMBB(&LoopBB);
3570 
3571   // Read the next variant <- also loop target.
3572   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3573       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3574 
3575   // Compare the just read M0 value to all possible Idx values.
3576   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3577       .addReg(CurrentIdxReg)
3578       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3579 
3580   // Update EXEC, save the original EXEC value to VCC.
3581   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3582                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3583           NewExec)
3584     .addReg(CondReg, RegState::Kill);
3585 
3586   MRI.setSimpleHint(NewExec, CondReg);
3587 
3588   if (UseGPRIdxMode) {
3589     if (Offset == 0) {
3590       SGPRIdxReg = CurrentIdxReg;
3591     } else {
3592       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3593       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3594           .addReg(CurrentIdxReg, RegState::Kill)
3595           .addImm(Offset);
3596     }
3597   } else {
3598     // Move index from VCC into M0
3599     if (Offset == 0) {
3600       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3601         .addReg(CurrentIdxReg, RegState::Kill);
3602     } else {
3603       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3604         .addReg(CurrentIdxReg, RegState::Kill)
3605         .addImm(Offset);
3606     }
3607   }
3608 
3609   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3610   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3611   MachineInstr *InsertPt =
3612     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3613                                                   : AMDGPU::S_XOR_B64_term), Exec)
3614       .addReg(Exec)
3615       .addReg(NewExec);
3616 
3617   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3618   // s_cbranch_scc0?
3619 
3620   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3621   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3622     .addMBB(&LoopBB);
3623 
3624   return InsertPt->getIterator();
3625 }
3626 
3627 // This has slightly sub-optimal regalloc when the source vector is killed by
3628 // the read. The register allocator does not understand that the kill is
3629 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3630 // subregister from it, using 1 more VGPR than necessary. This was saved when
3631 // this was expanded after register allocation.
3632 static MachineBasicBlock::iterator
3633 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3634                unsigned InitResultReg, unsigned PhiReg, int Offset,
3635                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3636   MachineFunction *MF = MBB.getParent();
3637   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3638   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3639   MachineRegisterInfo &MRI = MF->getRegInfo();
3640   const DebugLoc &DL = MI.getDebugLoc();
3641   MachineBasicBlock::iterator I(&MI);
3642 
3643   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3644   Register DstReg = MI.getOperand(0).getReg();
3645   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3646   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3647   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3648   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3649 
3650   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3651 
3652   // Save the EXEC mask
3653   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3654     .addReg(Exec);
3655 
3656   MachineBasicBlock *LoopBB;
3657   MachineBasicBlock *RemainderBB;
3658   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3659 
3660   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3661 
3662   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3663                                       InitResultReg, DstReg, PhiReg, TmpExec,
3664                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3665 
3666   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3667   MachineFunction::iterator MBBI(LoopBB);
3668   ++MBBI;
3669   MF->insert(MBBI, LandingPad);
3670   LoopBB->removeSuccessor(RemainderBB);
3671   LandingPad->addSuccessor(RemainderBB);
3672   LoopBB->addSuccessor(LandingPad);
3673   MachineBasicBlock::iterator First = LandingPad->begin();
3674   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3675     .addReg(SaveExec);
3676 
3677   return InsPt;
3678 }
3679 
3680 // Returns subreg index, offset
3681 static std::pair<unsigned, int>
3682 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3683                             const TargetRegisterClass *SuperRC,
3684                             unsigned VecReg,
3685                             int Offset) {
3686   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3687 
3688   // Skip out of bounds offsets, or else we would end up using an undefined
3689   // register.
3690   if (Offset >= NumElts || Offset < 0)
3691     return std::make_pair(AMDGPU::sub0, Offset);
3692 
3693   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3694 }
3695 
3696 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3697                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3698                                  int Offset) {
3699   MachineBasicBlock *MBB = MI.getParent();
3700   const DebugLoc &DL = MI.getDebugLoc();
3701   MachineBasicBlock::iterator I(&MI);
3702 
3703   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3704 
3705   assert(Idx->getReg() != AMDGPU::NoRegister);
3706 
3707   if (Offset == 0) {
3708     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3709   } else {
3710     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3711         .add(*Idx)
3712         .addImm(Offset);
3713   }
3714 }
3715 
3716 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3717                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3718                                    int Offset) {
3719   MachineBasicBlock *MBB = MI.getParent();
3720   const DebugLoc &DL = MI.getDebugLoc();
3721   MachineBasicBlock::iterator I(&MI);
3722 
3723   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3724 
3725   if (Offset == 0)
3726     return Idx->getReg();
3727 
3728   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3729   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3730       .add(*Idx)
3731       .addImm(Offset);
3732   return Tmp;
3733 }
3734 
3735 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3736                                           MachineBasicBlock &MBB,
3737                                           const GCNSubtarget &ST) {
3738   const SIInstrInfo *TII = ST.getInstrInfo();
3739   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3740   MachineFunction *MF = MBB.getParent();
3741   MachineRegisterInfo &MRI = MF->getRegInfo();
3742 
3743   Register Dst = MI.getOperand(0).getReg();
3744   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3745   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3746   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3747 
3748   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3749   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3750 
3751   unsigned SubReg;
3752   std::tie(SubReg, Offset)
3753     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3754 
3755   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3756 
3757   // Check for a SGPR index.
3758   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3759     MachineBasicBlock::iterator I(&MI);
3760     const DebugLoc &DL = MI.getDebugLoc();
3761 
3762     if (UseGPRIdxMode) {
3763       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3764       // to avoid interfering with other uses, so probably requires a new
3765       // optimization pass.
3766       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3767 
3768       const MCInstrDesc &GPRIDXDesc =
3769           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3770       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3771           .addReg(SrcReg)
3772           .addReg(Idx)
3773           .addImm(SubReg);
3774     } else {
3775       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3776 
3777       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3778         .addReg(SrcReg, 0, SubReg)
3779         .addReg(SrcReg, RegState::Implicit);
3780     }
3781 
3782     MI.eraseFromParent();
3783 
3784     return &MBB;
3785   }
3786 
3787   // Control flow needs to be inserted if indexing with a VGPR.
3788   const DebugLoc &DL = MI.getDebugLoc();
3789   MachineBasicBlock::iterator I(&MI);
3790 
3791   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3792   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3793 
3794   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3795 
3796   Register SGPRIdxReg;
3797   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3798                               UseGPRIdxMode, SGPRIdxReg);
3799 
3800   MachineBasicBlock *LoopBB = InsPt->getParent();
3801 
3802   if (UseGPRIdxMode) {
3803     const MCInstrDesc &GPRIDXDesc =
3804         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3805 
3806     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3807         .addReg(SrcReg)
3808         .addReg(SGPRIdxReg)
3809         .addImm(SubReg);
3810   } else {
3811     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3812       .addReg(SrcReg, 0, SubReg)
3813       .addReg(SrcReg, RegState::Implicit);
3814   }
3815 
3816   MI.eraseFromParent();
3817 
3818   return LoopBB;
3819 }
3820 
3821 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3822                                           MachineBasicBlock &MBB,
3823                                           const GCNSubtarget &ST) {
3824   const SIInstrInfo *TII = ST.getInstrInfo();
3825   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3826   MachineFunction *MF = MBB.getParent();
3827   MachineRegisterInfo &MRI = MF->getRegInfo();
3828 
3829   Register Dst = MI.getOperand(0).getReg();
3830   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3831   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3832   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3833   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3834   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3835   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3836 
3837   // This can be an immediate, but will be folded later.
3838   assert(Val->getReg());
3839 
3840   unsigned SubReg;
3841   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3842                                                          SrcVec->getReg(),
3843                                                          Offset);
3844   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3845 
3846   if (Idx->getReg() == AMDGPU::NoRegister) {
3847     MachineBasicBlock::iterator I(&MI);
3848     const DebugLoc &DL = MI.getDebugLoc();
3849 
3850     assert(Offset == 0);
3851 
3852     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3853         .add(*SrcVec)
3854         .add(*Val)
3855         .addImm(SubReg);
3856 
3857     MI.eraseFromParent();
3858     return &MBB;
3859   }
3860 
3861   // Check for a SGPR index.
3862   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3863     MachineBasicBlock::iterator I(&MI);
3864     const DebugLoc &DL = MI.getDebugLoc();
3865 
3866     if (UseGPRIdxMode) {
3867       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3868 
3869       const MCInstrDesc &GPRIDXDesc =
3870           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3871       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3872           .addReg(SrcVec->getReg())
3873           .add(*Val)
3874           .addReg(Idx)
3875           .addImm(SubReg);
3876     } else {
3877       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3878 
3879       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3880           TRI.getRegSizeInBits(*VecRC), 32, false);
3881       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3882           .addReg(SrcVec->getReg())
3883           .add(*Val)
3884           .addImm(SubReg);
3885     }
3886     MI.eraseFromParent();
3887     return &MBB;
3888   }
3889 
3890   // Control flow needs to be inserted if indexing with a VGPR.
3891   if (Val->isReg())
3892     MRI.clearKillFlags(Val->getReg());
3893 
3894   const DebugLoc &DL = MI.getDebugLoc();
3895 
3896   Register PhiReg = MRI.createVirtualRegister(VecRC);
3897 
3898   Register SGPRIdxReg;
3899   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3900                               UseGPRIdxMode, SGPRIdxReg);
3901   MachineBasicBlock *LoopBB = InsPt->getParent();
3902 
3903   if (UseGPRIdxMode) {
3904     const MCInstrDesc &GPRIDXDesc =
3905         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3906 
3907     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3908         .addReg(PhiReg)
3909         .add(*Val)
3910         .addReg(SGPRIdxReg)
3911         .addImm(AMDGPU::sub0);
3912   } else {
3913     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3914         TRI.getRegSizeInBits(*VecRC), 32, false);
3915     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3916         .addReg(PhiReg)
3917         .add(*Val)
3918         .addImm(AMDGPU::sub0);
3919   }
3920 
3921   MI.eraseFromParent();
3922   return LoopBB;
3923 }
3924 
3925 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3926   MachineInstr &MI, MachineBasicBlock *BB) const {
3927 
3928   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3929   MachineFunction *MF = BB->getParent();
3930   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3931 
3932   switch (MI.getOpcode()) {
3933   case AMDGPU::S_UADDO_PSEUDO:
3934   case AMDGPU::S_USUBO_PSEUDO: {
3935     const DebugLoc &DL = MI.getDebugLoc();
3936     MachineOperand &Dest0 = MI.getOperand(0);
3937     MachineOperand &Dest1 = MI.getOperand(1);
3938     MachineOperand &Src0 = MI.getOperand(2);
3939     MachineOperand &Src1 = MI.getOperand(3);
3940 
3941     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3942                        ? AMDGPU::S_ADD_I32
3943                        : AMDGPU::S_SUB_I32;
3944     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3945 
3946     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3947         .addImm(1)
3948         .addImm(0);
3949 
3950     MI.eraseFromParent();
3951     return BB;
3952   }
3953   case AMDGPU::S_ADD_U64_PSEUDO:
3954   case AMDGPU::S_SUB_U64_PSEUDO: {
3955     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3956     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3957     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3958     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3959     const DebugLoc &DL = MI.getDebugLoc();
3960 
3961     MachineOperand &Dest = MI.getOperand(0);
3962     MachineOperand &Src0 = MI.getOperand(1);
3963     MachineOperand &Src1 = MI.getOperand(2);
3964 
3965     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3966     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3967 
3968     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3969         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3970     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3971         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3972 
3973     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3974         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3975     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3976         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3977 
3978     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3979 
3980     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3981     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3982     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3983     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3984     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3985         .addReg(DestSub0)
3986         .addImm(AMDGPU::sub0)
3987         .addReg(DestSub1)
3988         .addImm(AMDGPU::sub1);
3989     MI.eraseFromParent();
3990     return BB;
3991   }
3992   case AMDGPU::V_ADD_U64_PSEUDO:
3993   case AMDGPU::V_SUB_U64_PSEUDO: {
3994     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3995     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3996     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3997     const DebugLoc &DL = MI.getDebugLoc();
3998 
3999     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4000 
4001     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4002 
4003     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4004     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4005 
4006     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4007     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4008 
4009     MachineOperand &Dest = MI.getOperand(0);
4010     MachineOperand &Src0 = MI.getOperand(1);
4011     MachineOperand &Src1 = MI.getOperand(2);
4012 
4013     const TargetRegisterClass *Src0RC = Src0.isReg()
4014                                             ? MRI.getRegClass(Src0.getReg())
4015                                             : &AMDGPU::VReg_64RegClass;
4016     const TargetRegisterClass *Src1RC = Src1.isReg()
4017                                             ? MRI.getRegClass(Src1.getReg())
4018                                             : &AMDGPU::VReg_64RegClass;
4019 
4020     const TargetRegisterClass *Src0SubRC =
4021         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4022     const TargetRegisterClass *Src1SubRC =
4023         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4024 
4025     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4026         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4027     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4028         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4029 
4030     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4031         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4032     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4033         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4034 
4035     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4036     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4037                                .addReg(CarryReg, RegState::Define)
4038                                .add(SrcReg0Sub0)
4039                                .add(SrcReg1Sub0)
4040                                .addImm(0); // clamp bit
4041 
4042     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4043     MachineInstr *HiHalf =
4044         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4045             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4046             .add(SrcReg0Sub1)
4047             .add(SrcReg1Sub1)
4048             .addReg(CarryReg, RegState::Kill)
4049             .addImm(0); // clamp bit
4050 
4051     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4052         .addReg(DestSub0)
4053         .addImm(AMDGPU::sub0)
4054         .addReg(DestSub1)
4055         .addImm(AMDGPU::sub1);
4056     TII->legalizeOperands(*LoHalf);
4057     TII->legalizeOperands(*HiHalf);
4058     MI.eraseFromParent();
4059     return BB;
4060   }
4061   case AMDGPU::S_ADD_CO_PSEUDO:
4062   case AMDGPU::S_SUB_CO_PSEUDO: {
4063     // This pseudo has a chance to be selected
4064     // only from uniform add/subcarry node. All the VGPR operands
4065     // therefore assumed to be splat vectors.
4066     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4067     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4068     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4069     MachineBasicBlock::iterator MII = MI;
4070     const DebugLoc &DL = MI.getDebugLoc();
4071     MachineOperand &Dest = MI.getOperand(0);
4072     MachineOperand &CarryDest = MI.getOperand(1);
4073     MachineOperand &Src0 = MI.getOperand(2);
4074     MachineOperand &Src1 = MI.getOperand(3);
4075     MachineOperand &Src2 = MI.getOperand(4);
4076     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4077                        ? AMDGPU::S_ADDC_U32
4078                        : AMDGPU::S_SUBB_U32;
4079     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4080       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4081       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4082           .addReg(Src0.getReg());
4083       Src0.setReg(RegOp0);
4084     }
4085     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4086       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4087       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4088           .addReg(Src1.getReg());
4089       Src1.setReg(RegOp1);
4090     }
4091     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4092     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4093       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4094           .addReg(Src2.getReg());
4095       Src2.setReg(RegOp2);
4096     }
4097 
4098     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4099     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4100       if (ST.hasScalarCompareEq64()) {
4101         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4102             .addReg(Src2.getReg())
4103             .addImm(0);
4104       } else {
4105         const TargetRegisterClass *SubRC =
4106             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4107         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4108             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4109         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4110             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4111         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4112 
4113         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4114             .add(Src2Sub0)
4115             .add(Src2Sub1);
4116 
4117         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4118             .addReg(Src2_32, RegState::Kill)
4119             .addImm(0);
4120       }
4121     } else {
4122       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4123           .addReg(Src2.getReg())
4124           .addImm(0);
4125     }
4126 
4127     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4128 
4129     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4130       .addReg(AMDGPU::SCC);
4131     MI.eraseFromParent();
4132     return BB;
4133   }
4134   case AMDGPU::SI_INIT_M0: {
4135     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4136             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4137         .add(MI.getOperand(0));
4138     MI.eraseFromParent();
4139     return BB;
4140   }
4141   case AMDGPU::GET_GROUPSTATICSIZE: {
4142     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4143            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4144     DebugLoc DL = MI.getDebugLoc();
4145     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4146         .add(MI.getOperand(0))
4147         .addImm(MFI->getLDSSize());
4148     MI.eraseFromParent();
4149     return BB;
4150   }
4151   case AMDGPU::SI_INDIRECT_SRC_V1:
4152   case AMDGPU::SI_INDIRECT_SRC_V2:
4153   case AMDGPU::SI_INDIRECT_SRC_V4:
4154   case AMDGPU::SI_INDIRECT_SRC_V8:
4155   case AMDGPU::SI_INDIRECT_SRC_V16:
4156   case AMDGPU::SI_INDIRECT_SRC_V32:
4157     return emitIndirectSrc(MI, *BB, *getSubtarget());
4158   case AMDGPU::SI_INDIRECT_DST_V1:
4159   case AMDGPU::SI_INDIRECT_DST_V2:
4160   case AMDGPU::SI_INDIRECT_DST_V4:
4161   case AMDGPU::SI_INDIRECT_DST_V8:
4162   case AMDGPU::SI_INDIRECT_DST_V16:
4163   case AMDGPU::SI_INDIRECT_DST_V32:
4164     return emitIndirectDst(MI, *BB, *getSubtarget());
4165   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4166   case AMDGPU::SI_KILL_I1_PSEUDO:
4167     return splitKillBlock(MI, BB);
4168   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4169     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4170     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4171     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4172 
4173     Register Dst = MI.getOperand(0).getReg();
4174     Register Src0 = MI.getOperand(1).getReg();
4175     Register Src1 = MI.getOperand(2).getReg();
4176     const DebugLoc &DL = MI.getDebugLoc();
4177     Register SrcCond = MI.getOperand(3).getReg();
4178 
4179     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4180     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4181     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4182     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4183 
4184     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4185       .addReg(SrcCond);
4186     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4187       .addImm(0)
4188       .addReg(Src0, 0, AMDGPU::sub0)
4189       .addImm(0)
4190       .addReg(Src1, 0, AMDGPU::sub0)
4191       .addReg(SrcCondCopy);
4192     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4193       .addImm(0)
4194       .addReg(Src0, 0, AMDGPU::sub1)
4195       .addImm(0)
4196       .addReg(Src1, 0, AMDGPU::sub1)
4197       .addReg(SrcCondCopy);
4198 
4199     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4200       .addReg(DstLo)
4201       .addImm(AMDGPU::sub0)
4202       .addReg(DstHi)
4203       .addImm(AMDGPU::sub1);
4204     MI.eraseFromParent();
4205     return BB;
4206   }
4207   case AMDGPU::SI_BR_UNDEF: {
4208     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4209     const DebugLoc &DL = MI.getDebugLoc();
4210     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4211                            .add(MI.getOperand(0));
4212     Br->getOperand(1).setIsUndef(true); // read undef SCC
4213     MI.eraseFromParent();
4214     return BB;
4215   }
4216   case AMDGPU::ADJCALLSTACKUP:
4217   case AMDGPU::ADJCALLSTACKDOWN: {
4218     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4219     MachineInstrBuilder MIB(*MF, &MI);
4220     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4221        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4222     return BB;
4223   }
4224   case AMDGPU::SI_CALL_ISEL: {
4225     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4226     const DebugLoc &DL = MI.getDebugLoc();
4227 
4228     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4229 
4230     MachineInstrBuilder MIB;
4231     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4232 
4233     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4234       MIB.add(MI.getOperand(I));
4235 
4236     MIB.cloneMemRefs(MI);
4237     MI.eraseFromParent();
4238     return BB;
4239   }
4240   case AMDGPU::V_ADD_CO_U32_e32:
4241   case AMDGPU::V_SUB_CO_U32_e32:
4242   case AMDGPU::V_SUBREV_CO_U32_e32: {
4243     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4244     const DebugLoc &DL = MI.getDebugLoc();
4245     unsigned Opc = MI.getOpcode();
4246 
4247     bool NeedClampOperand = false;
4248     if (TII->pseudoToMCOpcode(Opc) == -1) {
4249       Opc = AMDGPU::getVOPe64(Opc);
4250       NeedClampOperand = true;
4251     }
4252 
4253     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4254     if (TII->isVOP3(*I)) {
4255       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4256       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4257       I.addReg(TRI->getVCC(), RegState::Define);
4258     }
4259     I.add(MI.getOperand(1))
4260      .add(MI.getOperand(2));
4261     if (NeedClampOperand)
4262       I.addImm(0); // clamp bit for e64 encoding
4263 
4264     TII->legalizeOperands(*I);
4265 
4266     MI.eraseFromParent();
4267     return BB;
4268   }
4269   case AMDGPU::V_ADDC_U32_e32:
4270   case AMDGPU::V_SUBB_U32_e32:
4271   case AMDGPU::V_SUBBREV_U32_e32:
4272     // These instructions have an implicit use of vcc which counts towards the
4273     // constant bus limit.
4274     TII->legalizeOperands(MI);
4275     return BB;
4276   case AMDGPU::DS_GWS_INIT:
4277   case AMDGPU::DS_GWS_SEMA_BR:
4278   case AMDGPU::DS_GWS_BARRIER:
4279     if (Subtarget->needsAlignedVGPRs()) {
4280       // Add implicit aligned super-reg to force alignment on the data operand.
4281       const DebugLoc &DL = MI.getDebugLoc();
4282       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4283       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4284       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4285       Register DataReg = Op->getReg();
4286       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4287       Register Undef = MRI.createVirtualRegister(
4288           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4289       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4290       Register NewVR =
4291           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4292                                            : &AMDGPU::VReg_64_Align2RegClass);
4293       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4294           .addReg(DataReg, 0, Op->getSubReg())
4295           .addImm(AMDGPU::sub0)
4296           .addReg(Undef)
4297           .addImm(AMDGPU::sub1);
4298       Op->setReg(NewVR);
4299       Op->setSubReg(AMDGPU::sub0);
4300       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4301     }
4302     LLVM_FALLTHROUGH;
4303   case AMDGPU::DS_GWS_SEMA_V:
4304   case AMDGPU::DS_GWS_SEMA_P:
4305   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4306     // A s_waitcnt 0 is required to be the instruction immediately following.
4307     if (getSubtarget()->hasGWSAutoReplay()) {
4308       bundleInstWithWaitcnt(MI);
4309       return BB;
4310     }
4311 
4312     return emitGWSMemViolTestLoop(MI, BB);
4313   case AMDGPU::S_SETREG_B32: {
4314     // Try to optimize cases that only set the denormal mode or rounding mode.
4315     //
4316     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4317     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4318     // instead.
4319     //
4320     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4321     // allow you to have a no side effect instruction in the output of a
4322     // sideeffecting pattern.
4323     unsigned ID, Offset, Width;
4324     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4325     if (ID != AMDGPU::Hwreg::ID_MODE)
4326       return BB;
4327 
4328     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4329     const unsigned SetMask = WidthMask << Offset;
4330 
4331     if (getSubtarget()->hasDenormModeInst()) {
4332       unsigned SetDenormOp = 0;
4333       unsigned SetRoundOp = 0;
4334 
4335       // The dedicated instructions can only set the whole denorm or round mode
4336       // at once, not a subset of bits in either.
4337       if (SetMask ==
4338           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4339         // If this fully sets both the round and denorm mode, emit the two
4340         // dedicated instructions for these.
4341         SetRoundOp = AMDGPU::S_ROUND_MODE;
4342         SetDenormOp = AMDGPU::S_DENORM_MODE;
4343       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4344         SetRoundOp = AMDGPU::S_ROUND_MODE;
4345       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4346         SetDenormOp = AMDGPU::S_DENORM_MODE;
4347       }
4348 
4349       if (SetRoundOp || SetDenormOp) {
4350         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4351         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4352         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4353           unsigned ImmVal = Def->getOperand(1).getImm();
4354           if (SetRoundOp) {
4355             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4356                 .addImm(ImmVal & 0xf);
4357 
4358             // If we also have the denorm mode, get just the denorm mode bits.
4359             ImmVal >>= 4;
4360           }
4361 
4362           if (SetDenormOp) {
4363             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4364                 .addImm(ImmVal & 0xf);
4365           }
4366 
4367           MI.eraseFromParent();
4368           return BB;
4369         }
4370       }
4371     }
4372 
4373     // If only FP bits are touched, used the no side effects pseudo.
4374     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4375                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4376       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4377 
4378     return BB;
4379   }
4380   default:
4381     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4382   }
4383 }
4384 
4385 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4386   return isTypeLegal(VT.getScalarType());
4387 }
4388 
4389 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4390   // This currently forces unfolding various combinations of fsub into fma with
4391   // free fneg'd operands. As long as we have fast FMA (controlled by
4392   // isFMAFasterThanFMulAndFAdd), we should perform these.
4393 
4394   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4395   // most of these combines appear to be cycle neutral but save on instruction
4396   // count / code size.
4397   return true;
4398 }
4399 
4400 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4401                                          EVT VT) const {
4402   if (!VT.isVector()) {
4403     return MVT::i1;
4404   }
4405   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4406 }
4407 
4408 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4409   // TODO: Should i16 be used always if legal? For now it would force VALU
4410   // shifts.
4411   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4412 }
4413 
4414 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4415   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4416              ? Ty.changeElementSize(16)
4417              : Ty.changeElementSize(32);
4418 }
4419 
4420 // Answering this is somewhat tricky and depends on the specific device which
4421 // have different rates for fma or all f64 operations.
4422 //
4423 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4424 // regardless of which device (although the number of cycles differs between
4425 // devices), so it is always profitable for f64.
4426 //
4427 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4428 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4429 // which we can always do even without fused FP ops since it returns the same
4430 // result as the separate operations and since it is always full
4431 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4432 // however does not support denormals, so we do report fma as faster if we have
4433 // a fast fma device and require denormals.
4434 //
4435 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4436                                                   EVT VT) const {
4437   VT = VT.getScalarType();
4438 
4439   switch (VT.getSimpleVT().SimpleTy) {
4440   case MVT::f32: {
4441     // If mad is not available this depends only on if f32 fma is full rate.
4442     if (!Subtarget->hasMadMacF32Insts())
4443       return Subtarget->hasFastFMAF32();
4444 
4445     // Otherwise f32 mad is always full rate and returns the same result as
4446     // the separate operations so should be preferred over fma.
4447     // However does not support denomals.
4448     if (hasFP32Denormals(MF))
4449       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4450 
4451     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4452     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4453   }
4454   case MVT::f64:
4455     return true;
4456   case MVT::f16:
4457     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4458   default:
4459     break;
4460   }
4461 
4462   return false;
4463 }
4464 
4465 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4466                                    const SDNode *N) const {
4467   // TODO: Check future ftz flag
4468   // v_mad_f32/v_mac_f32 do not support denormals.
4469   EVT VT = N->getValueType(0);
4470   if (VT == MVT::f32)
4471     return Subtarget->hasMadMacF32Insts() &&
4472            !hasFP32Denormals(DAG.getMachineFunction());
4473   if (VT == MVT::f16) {
4474     return Subtarget->hasMadF16() &&
4475            !hasFP64FP16Denormals(DAG.getMachineFunction());
4476   }
4477 
4478   return false;
4479 }
4480 
4481 //===----------------------------------------------------------------------===//
4482 // Custom DAG Lowering Operations
4483 //===----------------------------------------------------------------------===//
4484 
4485 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4486 // wider vector type is legal.
4487 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4488                                              SelectionDAG &DAG) const {
4489   unsigned Opc = Op.getOpcode();
4490   EVT VT = Op.getValueType();
4491   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4492 
4493   SDValue Lo, Hi;
4494   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4495 
4496   SDLoc SL(Op);
4497   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4498                              Op->getFlags());
4499   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4500                              Op->getFlags());
4501 
4502   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4503 }
4504 
4505 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4506 // wider vector type is legal.
4507 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4508                                               SelectionDAG &DAG) const {
4509   unsigned Opc = Op.getOpcode();
4510   EVT VT = Op.getValueType();
4511   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4512          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4513 
4514   SDValue Lo0, Hi0;
4515   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4516   SDValue Lo1, Hi1;
4517   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4518 
4519   SDLoc SL(Op);
4520 
4521   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4522                              Op->getFlags());
4523   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4524                              Op->getFlags());
4525 
4526   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4527 }
4528 
4529 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4530                                               SelectionDAG &DAG) const {
4531   unsigned Opc = Op.getOpcode();
4532   EVT VT = Op.getValueType();
4533   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4534          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4535 
4536   SDValue Lo0, Hi0;
4537   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4538   SDValue Lo1, Hi1;
4539   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4540   SDValue Lo2, Hi2;
4541   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4542 
4543   SDLoc SL(Op);
4544 
4545   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4546                              Op->getFlags());
4547   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4548                              Op->getFlags());
4549 
4550   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4551 }
4552 
4553 
4554 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4555   switch (Op.getOpcode()) {
4556   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4557   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4558   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4559   case ISD::LOAD: {
4560     SDValue Result = LowerLOAD(Op, DAG);
4561     assert((!Result.getNode() ||
4562             Result.getNode()->getNumValues() == 2) &&
4563            "Load should return a value and a chain");
4564     return Result;
4565   }
4566 
4567   case ISD::FSIN:
4568   case ISD::FCOS:
4569     return LowerTrig(Op, DAG);
4570   case ISD::SELECT: return LowerSELECT(Op, DAG);
4571   case ISD::FDIV: return LowerFDIV(Op, DAG);
4572   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4573   case ISD::STORE: return LowerSTORE(Op, DAG);
4574   case ISD::GlobalAddress: {
4575     MachineFunction &MF = DAG.getMachineFunction();
4576     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4577     return LowerGlobalAddress(MFI, Op, DAG);
4578   }
4579   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4580   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4581   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4582   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4583   case ISD::INSERT_SUBVECTOR:
4584     return lowerINSERT_SUBVECTOR(Op, DAG);
4585   case ISD::INSERT_VECTOR_ELT:
4586     return lowerINSERT_VECTOR_ELT(Op, DAG);
4587   case ISD::EXTRACT_VECTOR_ELT:
4588     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4589   case ISD::VECTOR_SHUFFLE:
4590     return lowerVECTOR_SHUFFLE(Op, DAG);
4591   case ISD::BUILD_VECTOR:
4592     return lowerBUILD_VECTOR(Op, DAG);
4593   case ISD::FP_ROUND:
4594     return lowerFP_ROUND(Op, DAG);
4595   case ISD::TRAP:
4596     return lowerTRAP(Op, DAG);
4597   case ISD::DEBUGTRAP:
4598     return lowerDEBUGTRAP(Op, DAG);
4599   case ISD::FABS:
4600   case ISD::FNEG:
4601   case ISD::FCANONICALIZE:
4602   case ISD::BSWAP:
4603     return splitUnaryVectorOp(Op, DAG);
4604   case ISD::FMINNUM:
4605   case ISD::FMAXNUM:
4606     return lowerFMINNUM_FMAXNUM(Op, DAG);
4607   case ISD::FMA:
4608     return splitTernaryVectorOp(Op, DAG);
4609   case ISD::FP_TO_SINT:
4610   case ISD::FP_TO_UINT:
4611     return LowerFP_TO_INT(Op, DAG);
4612   case ISD::SHL:
4613   case ISD::SRA:
4614   case ISD::SRL:
4615   case ISD::ADD:
4616   case ISD::SUB:
4617   case ISD::MUL:
4618   case ISD::SMIN:
4619   case ISD::SMAX:
4620   case ISD::UMIN:
4621   case ISD::UMAX:
4622   case ISD::FADD:
4623   case ISD::FMUL:
4624   case ISD::FMINNUM_IEEE:
4625   case ISD::FMAXNUM_IEEE:
4626   case ISD::UADDSAT:
4627   case ISD::USUBSAT:
4628   case ISD::SADDSAT:
4629   case ISD::SSUBSAT:
4630     return splitBinaryVectorOp(Op, DAG);
4631   case ISD::SMULO:
4632   case ISD::UMULO:
4633     return lowerXMULO(Op, DAG);
4634   case ISD::DYNAMIC_STACKALLOC:
4635     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4636   }
4637   return SDValue();
4638 }
4639 
4640 // Used for D16: Casts the result of an instruction into the right vector,
4641 // packs values if loads return unpacked values.
4642 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4643                                        const SDLoc &DL,
4644                                        SelectionDAG &DAG, bool Unpacked) {
4645   if (!LoadVT.isVector())
4646     return Result;
4647 
4648   // Cast back to the original packed type or to a larger type that is a
4649   // multiple of 32 bit for D16. Widening the return type is a required for
4650   // legalization.
4651   EVT FittingLoadVT = LoadVT;
4652   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4653     FittingLoadVT =
4654         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4655                          LoadVT.getVectorNumElements() + 1);
4656   }
4657 
4658   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4659     // Truncate to v2i16/v4i16.
4660     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4661 
4662     // Workaround legalizer not scalarizing truncate after vector op
4663     // legalization but not creating intermediate vector trunc.
4664     SmallVector<SDValue, 4> Elts;
4665     DAG.ExtractVectorElements(Result, Elts);
4666     for (SDValue &Elt : Elts)
4667       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4668 
4669     // Pad illegal v1i16/v3fi6 to v4i16
4670     if ((LoadVT.getVectorNumElements() % 2) == 1)
4671       Elts.push_back(DAG.getUNDEF(MVT::i16));
4672 
4673     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4674 
4675     // Bitcast to original type (v2f16/v4f16).
4676     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4677   }
4678 
4679   // Cast back to the original packed type.
4680   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4681 }
4682 
4683 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4684                                               MemSDNode *M,
4685                                               SelectionDAG &DAG,
4686                                               ArrayRef<SDValue> Ops,
4687                                               bool IsIntrinsic) const {
4688   SDLoc DL(M);
4689 
4690   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4691   EVT LoadVT = M->getValueType(0);
4692 
4693   EVT EquivLoadVT = LoadVT;
4694   if (LoadVT.isVector()) {
4695     if (Unpacked) {
4696       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4697                                      LoadVT.getVectorNumElements());
4698     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4699       // Widen v3f16 to legal type
4700       EquivLoadVT =
4701           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4702                            LoadVT.getVectorNumElements() + 1);
4703     }
4704   }
4705 
4706   // Change from v4f16/v2f16 to EquivLoadVT.
4707   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4708 
4709   SDValue Load
4710     = DAG.getMemIntrinsicNode(
4711       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4712       VTList, Ops, M->getMemoryVT(),
4713       M->getMemOperand());
4714 
4715   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4716 
4717   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4718 }
4719 
4720 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4721                                              SelectionDAG &DAG,
4722                                              ArrayRef<SDValue> Ops) const {
4723   SDLoc DL(M);
4724   EVT LoadVT = M->getValueType(0);
4725   EVT EltType = LoadVT.getScalarType();
4726   EVT IntVT = LoadVT.changeTypeToInteger();
4727 
4728   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4729 
4730   unsigned Opc =
4731       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4732 
4733   if (IsD16) {
4734     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4735   }
4736 
4737   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4738   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4739     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4740 
4741   if (isTypeLegal(LoadVT)) {
4742     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4743                                M->getMemOperand(), DAG);
4744   }
4745 
4746   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4747   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4748   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4749                                         M->getMemOperand(), DAG);
4750   return DAG.getMergeValues(
4751       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4752       DL);
4753 }
4754 
4755 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4756                                   SDNode *N, SelectionDAG &DAG) {
4757   EVT VT = N->getValueType(0);
4758   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4759   unsigned CondCode = CD->getZExtValue();
4760   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4761     return DAG.getUNDEF(VT);
4762 
4763   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4764 
4765   SDValue LHS = N->getOperand(1);
4766   SDValue RHS = N->getOperand(2);
4767 
4768   SDLoc DL(N);
4769 
4770   EVT CmpVT = LHS.getValueType();
4771   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4772     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4773       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4774     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4775     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4776   }
4777 
4778   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4779 
4780   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4781   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4782 
4783   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4784                               DAG.getCondCode(CCOpcode));
4785   if (VT.bitsEq(CCVT))
4786     return SetCC;
4787   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4788 }
4789 
4790 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4791                                   SDNode *N, SelectionDAG &DAG) {
4792   EVT VT = N->getValueType(0);
4793   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4794 
4795   unsigned CondCode = CD->getZExtValue();
4796   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4797     return DAG.getUNDEF(VT);
4798 
4799   SDValue Src0 = N->getOperand(1);
4800   SDValue Src1 = N->getOperand(2);
4801   EVT CmpVT = Src0.getValueType();
4802   SDLoc SL(N);
4803 
4804   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4805     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4806     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4807   }
4808 
4809   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4810   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4811   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4812   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4813   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4814                               Src1, DAG.getCondCode(CCOpcode));
4815   if (VT.bitsEq(CCVT))
4816     return SetCC;
4817   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4818 }
4819 
4820 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4821                                     SelectionDAG &DAG) {
4822   EVT VT = N->getValueType(0);
4823   SDValue Src = N->getOperand(1);
4824   SDLoc SL(N);
4825 
4826   if (Src.getOpcode() == ISD::SETCC) {
4827     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4828     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4829                        Src.getOperand(1), Src.getOperand(2));
4830   }
4831   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4832     // (ballot 0) -> 0
4833     if (Arg->isNullValue())
4834       return DAG.getConstant(0, SL, VT);
4835 
4836     // (ballot 1) -> EXEC/EXEC_LO
4837     if (Arg->isOne()) {
4838       Register Exec;
4839       if (VT.getScalarSizeInBits() == 32)
4840         Exec = AMDGPU::EXEC_LO;
4841       else if (VT.getScalarSizeInBits() == 64)
4842         Exec = AMDGPU::EXEC;
4843       else
4844         return SDValue();
4845 
4846       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4847     }
4848   }
4849 
4850   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4851   // ISD::SETNE)
4852   return DAG.getNode(
4853       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4854       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4855 }
4856 
4857 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4858                                           SmallVectorImpl<SDValue> &Results,
4859                                           SelectionDAG &DAG) const {
4860   switch (N->getOpcode()) {
4861   case ISD::INSERT_VECTOR_ELT: {
4862     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4863       Results.push_back(Res);
4864     return;
4865   }
4866   case ISD::EXTRACT_VECTOR_ELT: {
4867     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4868       Results.push_back(Res);
4869     return;
4870   }
4871   case ISD::INTRINSIC_WO_CHAIN: {
4872     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4873     switch (IID) {
4874     case Intrinsic::amdgcn_cvt_pkrtz: {
4875       SDValue Src0 = N->getOperand(1);
4876       SDValue Src1 = N->getOperand(2);
4877       SDLoc SL(N);
4878       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4879                                 Src0, Src1);
4880       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4881       return;
4882     }
4883     case Intrinsic::amdgcn_cvt_pknorm_i16:
4884     case Intrinsic::amdgcn_cvt_pknorm_u16:
4885     case Intrinsic::amdgcn_cvt_pk_i16:
4886     case Intrinsic::amdgcn_cvt_pk_u16: {
4887       SDValue Src0 = N->getOperand(1);
4888       SDValue Src1 = N->getOperand(2);
4889       SDLoc SL(N);
4890       unsigned Opcode;
4891 
4892       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4893         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4894       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4895         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4896       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4897         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4898       else
4899         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4900 
4901       EVT VT = N->getValueType(0);
4902       if (isTypeLegal(VT))
4903         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4904       else {
4905         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4906         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4907       }
4908       return;
4909     }
4910     }
4911     break;
4912   }
4913   case ISD::INTRINSIC_W_CHAIN: {
4914     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4915       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4916         // FIXME: Hacky
4917         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4918           Results.push_back(Res.getOperand(I));
4919         }
4920       } else {
4921         Results.push_back(Res);
4922         Results.push_back(Res.getValue(1));
4923       }
4924       return;
4925     }
4926 
4927     break;
4928   }
4929   case ISD::SELECT: {
4930     SDLoc SL(N);
4931     EVT VT = N->getValueType(0);
4932     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4933     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4934     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4935 
4936     EVT SelectVT = NewVT;
4937     if (NewVT.bitsLT(MVT::i32)) {
4938       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4939       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4940       SelectVT = MVT::i32;
4941     }
4942 
4943     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4944                                     N->getOperand(0), LHS, RHS);
4945 
4946     if (NewVT != SelectVT)
4947       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4948     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4949     return;
4950   }
4951   case ISD::FNEG: {
4952     if (N->getValueType(0) != MVT::v2f16)
4953       break;
4954 
4955     SDLoc SL(N);
4956     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4957 
4958     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4959                              BC,
4960                              DAG.getConstant(0x80008000, SL, MVT::i32));
4961     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4962     return;
4963   }
4964   case ISD::FABS: {
4965     if (N->getValueType(0) != MVT::v2f16)
4966       break;
4967 
4968     SDLoc SL(N);
4969     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4970 
4971     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4972                              BC,
4973                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4974     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4975     return;
4976   }
4977   default:
4978     break;
4979   }
4980 }
4981 
4982 /// Helper function for LowerBRCOND
4983 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4984 
4985   SDNode *Parent = Value.getNode();
4986   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4987        I != E; ++I) {
4988 
4989     if (I.getUse().get() != Value)
4990       continue;
4991 
4992     if (I->getOpcode() == Opcode)
4993       return *I;
4994   }
4995   return nullptr;
4996 }
4997 
4998 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4999   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5000     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5001     case Intrinsic::amdgcn_if:
5002       return AMDGPUISD::IF;
5003     case Intrinsic::amdgcn_else:
5004       return AMDGPUISD::ELSE;
5005     case Intrinsic::amdgcn_loop:
5006       return AMDGPUISD::LOOP;
5007     case Intrinsic::amdgcn_end_cf:
5008       llvm_unreachable("should not occur");
5009     default:
5010       return 0;
5011     }
5012   }
5013 
5014   // break, if_break, else_break are all only used as inputs to loop, not
5015   // directly as branch conditions.
5016   return 0;
5017 }
5018 
5019 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5020   const Triple &TT = getTargetMachine().getTargetTriple();
5021   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5022           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5023          AMDGPU::shouldEmitConstantsToTextSection(TT);
5024 }
5025 
5026 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5027   // FIXME: Either avoid relying on address space here or change the default
5028   // address space for functions to avoid the explicit check.
5029   return (GV->getValueType()->isFunctionTy() ||
5030           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5031          !shouldEmitFixup(GV) &&
5032          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5033 }
5034 
5035 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5036   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5037 }
5038 
5039 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5040   if (!GV->hasExternalLinkage())
5041     return true;
5042 
5043   const auto OS = getTargetMachine().getTargetTriple().getOS();
5044   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5045 }
5046 
5047 /// This transforms the control flow intrinsics to get the branch destination as
5048 /// last parameter, also switches branch target with BR if the need arise
5049 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5050                                       SelectionDAG &DAG) const {
5051   SDLoc DL(BRCOND);
5052 
5053   SDNode *Intr = BRCOND.getOperand(1).getNode();
5054   SDValue Target = BRCOND.getOperand(2);
5055   SDNode *BR = nullptr;
5056   SDNode *SetCC = nullptr;
5057 
5058   if (Intr->getOpcode() == ISD::SETCC) {
5059     // As long as we negate the condition everything is fine
5060     SetCC = Intr;
5061     Intr = SetCC->getOperand(0).getNode();
5062 
5063   } else {
5064     // Get the target from BR if we don't negate the condition
5065     BR = findUser(BRCOND, ISD::BR);
5066     assert(BR && "brcond missing unconditional branch user");
5067     Target = BR->getOperand(1);
5068   }
5069 
5070   unsigned CFNode = isCFIntrinsic(Intr);
5071   if (CFNode == 0) {
5072     // This is a uniform branch so we don't need to legalize.
5073     return BRCOND;
5074   }
5075 
5076   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5077                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5078 
5079   assert(!SetCC ||
5080         (SetCC->getConstantOperandVal(1) == 1 &&
5081          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5082                                                              ISD::SETNE));
5083 
5084   // operands of the new intrinsic call
5085   SmallVector<SDValue, 4> Ops;
5086   if (HaveChain)
5087     Ops.push_back(BRCOND.getOperand(0));
5088 
5089   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5090   Ops.push_back(Target);
5091 
5092   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5093 
5094   // build the new intrinsic call
5095   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5096 
5097   if (!HaveChain) {
5098     SDValue Ops[] =  {
5099       SDValue(Result, 0),
5100       BRCOND.getOperand(0)
5101     };
5102 
5103     Result = DAG.getMergeValues(Ops, DL).getNode();
5104   }
5105 
5106   if (BR) {
5107     // Give the branch instruction our target
5108     SDValue Ops[] = {
5109       BR->getOperand(0),
5110       BRCOND.getOperand(2)
5111     };
5112     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5113     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5114   }
5115 
5116   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5117 
5118   // Copy the intrinsic results to registers
5119   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5120     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5121     if (!CopyToReg)
5122       continue;
5123 
5124     Chain = DAG.getCopyToReg(
5125       Chain, DL,
5126       CopyToReg->getOperand(1),
5127       SDValue(Result, i - 1),
5128       SDValue());
5129 
5130     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5131   }
5132 
5133   // Remove the old intrinsic from the chain
5134   DAG.ReplaceAllUsesOfValueWith(
5135     SDValue(Intr, Intr->getNumValues() - 1),
5136     Intr->getOperand(0));
5137 
5138   return Chain;
5139 }
5140 
5141 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5142                                           SelectionDAG &DAG) const {
5143   MVT VT = Op.getSimpleValueType();
5144   SDLoc DL(Op);
5145   // Checking the depth
5146   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5147     return DAG.getConstant(0, DL, VT);
5148 
5149   MachineFunction &MF = DAG.getMachineFunction();
5150   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5151   // Check for kernel and shader functions
5152   if (Info->isEntryFunction())
5153     return DAG.getConstant(0, DL, VT);
5154 
5155   MachineFrameInfo &MFI = MF.getFrameInfo();
5156   // There is a call to @llvm.returnaddress in this function
5157   MFI.setReturnAddressIsTaken(true);
5158 
5159   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5160   // Get the return address reg and mark it as an implicit live-in
5161   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5162 
5163   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5164 }
5165 
5166 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5167                                             SDValue Op,
5168                                             const SDLoc &DL,
5169                                             EVT VT) const {
5170   return Op.getValueType().bitsLE(VT) ?
5171       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5172     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5173                 DAG.getTargetConstant(0, DL, MVT::i32));
5174 }
5175 
5176 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5177   assert(Op.getValueType() == MVT::f16 &&
5178          "Do not know how to custom lower FP_ROUND for non-f16 type");
5179 
5180   SDValue Src = Op.getOperand(0);
5181   EVT SrcVT = Src.getValueType();
5182   if (SrcVT != MVT::f64)
5183     return Op;
5184 
5185   SDLoc DL(Op);
5186 
5187   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5188   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5189   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5190 }
5191 
5192 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5193                                                SelectionDAG &DAG) const {
5194   EVT VT = Op.getValueType();
5195   const MachineFunction &MF = DAG.getMachineFunction();
5196   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5197   bool IsIEEEMode = Info->getMode().IEEE;
5198 
5199   // FIXME: Assert during selection that this is only selected for
5200   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5201   // mode functions, but this happens to be OK since it's only done in cases
5202   // where there is known no sNaN.
5203   if (IsIEEEMode)
5204     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5205 
5206   if (VT == MVT::v4f16)
5207     return splitBinaryVectorOp(Op, DAG);
5208   return Op;
5209 }
5210 
5211 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5212   EVT VT = Op.getValueType();
5213   SDLoc SL(Op);
5214   SDValue LHS = Op.getOperand(0);
5215   SDValue RHS = Op.getOperand(1);
5216   bool isSigned = Op.getOpcode() == ISD::SMULO;
5217 
5218   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5219     const APInt &C = RHSC->getAPIntValue();
5220     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5221     if (C.isPowerOf2()) {
5222       // smulo(x, signed_min) is same as umulo(x, signed_min).
5223       bool UseArithShift = isSigned && !C.isMinSignedValue();
5224       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5225       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5226       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5227           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5228                       SL, VT, Result, ShiftAmt),
5229           LHS, ISD::SETNE);
5230       return DAG.getMergeValues({ Result, Overflow }, SL);
5231     }
5232   }
5233 
5234   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5235   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5236                             SL, VT, LHS, RHS);
5237 
5238   SDValue Sign = isSigned
5239     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5240                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5241     : DAG.getConstant(0, SL, VT);
5242   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5243 
5244   return DAG.getMergeValues({ Result, Overflow }, SL);
5245 }
5246 
5247 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5248   if (!Subtarget->isTrapHandlerEnabled() ||
5249       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5250     return lowerTrapEndpgm(Op, DAG);
5251 
5252   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5253     switch (*HsaAbiVer) {
5254     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5255     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5256       return lowerTrapHsaQueuePtr(Op, DAG);
5257     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5258       return Subtarget->supportsGetDoorbellID() ?
5259           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5260     }
5261   }
5262 
5263   llvm_unreachable("Unknown trap handler");
5264 }
5265 
5266 SDValue SITargetLowering::lowerTrapEndpgm(
5267     SDValue Op, SelectionDAG &DAG) const {
5268   SDLoc SL(Op);
5269   SDValue Chain = Op.getOperand(0);
5270   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5271 }
5272 
5273 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5274     SDValue Op, SelectionDAG &DAG) const {
5275   SDLoc SL(Op);
5276   SDValue Chain = Op.getOperand(0);
5277 
5278   MachineFunction &MF = DAG.getMachineFunction();
5279   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5280   Register UserSGPR = Info->getQueuePtrUserSGPR();
5281   assert(UserSGPR != AMDGPU::NoRegister);
5282   SDValue QueuePtr = CreateLiveInRegister(
5283     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5284   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5285   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5286                                    QueuePtr, SDValue());
5287 
5288   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5289   SDValue Ops[] = {
5290     ToReg,
5291     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5292     SGPR01,
5293     ToReg.getValue(1)
5294   };
5295   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5296 }
5297 
5298 SDValue SITargetLowering::lowerTrapHsa(
5299     SDValue Op, SelectionDAG &DAG) const {
5300   SDLoc SL(Op);
5301   SDValue Chain = Op.getOperand(0);
5302 
5303   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5304   SDValue Ops[] = {
5305     Chain,
5306     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5307   };
5308   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5309 }
5310 
5311 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5312   SDLoc SL(Op);
5313   SDValue Chain = Op.getOperand(0);
5314   MachineFunction &MF = DAG.getMachineFunction();
5315 
5316   if (!Subtarget->isTrapHandlerEnabled() ||
5317       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5318     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5319                                      "debugtrap handler not supported",
5320                                      Op.getDebugLoc(),
5321                                      DS_Warning);
5322     LLVMContext &Ctx = MF.getFunction().getContext();
5323     Ctx.diagnose(NoTrap);
5324     return Chain;
5325   }
5326 
5327   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5328   SDValue Ops[] = {
5329     Chain,
5330     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5331   };
5332   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5333 }
5334 
5335 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5336                                              SelectionDAG &DAG) const {
5337   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5338   if (Subtarget->hasApertureRegs()) {
5339     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5340         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5341         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5342     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5343         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5344         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5345     unsigned Encoding =
5346         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5347         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5348         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5349 
5350     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5351     SDValue ApertureReg = SDValue(
5352         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5353     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5354     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5355   }
5356 
5357   MachineFunction &MF = DAG.getMachineFunction();
5358   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5359   Register UserSGPR = Info->getQueuePtrUserSGPR();
5360   assert(UserSGPR != AMDGPU::NoRegister);
5361 
5362   SDValue QueuePtr = CreateLiveInRegister(
5363     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5364 
5365   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5366   // private_segment_aperture_base_hi.
5367   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5368 
5369   SDValue Ptr =
5370       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5371 
5372   // TODO: Use custom target PseudoSourceValue.
5373   // TODO: We should use the value from the IR intrinsic call, but it might not
5374   // be available and how do we get it?
5375   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5376   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5377                      commonAlignment(Align(64), StructOffset),
5378                      MachineMemOperand::MODereferenceable |
5379                          MachineMemOperand::MOInvariant);
5380 }
5381 
5382 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5383                                              SelectionDAG &DAG) const {
5384   SDLoc SL(Op);
5385   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5386 
5387   SDValue Src = ASC->getOperand(0);
5388   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5389 
5390   const AMDGPUTargetMachine &TM =
5391     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5392 
5393   // flat -> local/private
5394   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5395     unsigned DestAS = ASC->getDestAddressSpace();
5396 
5397     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5398         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5399       unsigned NullVal = TM.getNullPointerValue(DestAS);
5400       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5401       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5402       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5403 
5404       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5405                          NonNull, Ptr, SegmentNullPtr);
5406     }
5407   }
5408 
5409   // local/private -> flat
5410   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5411     unsigned SrcAS = ASC->getSrcAddressSpace();
5412 
5413     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5414         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5415       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5416       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5417 
5418       SDValue NonNull
5419         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5420 
5421       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5422       SDValue CvtPtr
5423         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5424 
5425       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5426                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5427                          FlatNullPtr);
5428     }
5429   }
5430 
5431   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5432       Src.getValueType() == MVT::i64)
5433     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5434 
5435   // global <-> flat are no-ops and never emitted.
5436 
5437   const MachineFunction &MF = DAG.getMachineFunction();
5438   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5439     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5440   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5441 
5442   return DAG.getUNDEF(ASC->getValueType(0));
5443 }
5444 
5445 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5446 // the small vector and inserting them into the big vector. That is better than
5447 // the default expansion of doing it via a stack slot. Even though the use of
5448 // the stack slot would be optimized away afterwards, the stack slot itself
5449 // remains.
5450 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5451                                                 SelectionDAG &DAG) const {
5452   SDValue Vec = Op.getOperand(0);
5453   SDValue Ins = Op.getOperand(1);
5454   SDValue Idx = Op.getOperand(2);
5455   EVT VecVT = Vec.getValueType();
5456   EVT InsVT = Ins.getValueType();
5457   EVT EltVT = VecVT.getVectorElementType();
5458   unsigned InsNumElts = InsVT.getVectorNumElements();
5459   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5460   SDLoc SL(Op);
5461 
5462   for (unsigned I = 0; I != InsNumElts; ++I) {
5463     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5464                               DAG.getConstant(I, SL, MVT::i32));
5465     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5466                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5467   }
5468   return Vec;
5469 }
5470 
5471 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5472                                                  SelectionDAG &DAG) const {
5473   SDValue Vec = Op.getOperand(0);
5474   SDValue InsVal = Op.getOperand(1);
5475   SDValue Idx = Op.getOperand(2);
5476   EVT VecVT = Vec.getValueType();
5477   EVT EltVT = VecVT.getVectorElementType();
5478   unsigned VecSize = VecVT.getSizeInBits();
5479   unsigned EltSize = EltVT.getSizeInBits();
5480 
5481 
5482   assert(VecSize <= 64);
5483 
5484   unsigned NumElts = VecVT.getVectorNumElements();
5485   SDLoc SL(Op);
5486   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5487 
5488   if (NumElts == 4 && EltSize == 16 && KIdx) {
5489     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5490 
5491     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5492                                  DAG.getConstant(0, SL, MVT::i32));
5493     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5494                                  DAG.getConstant(1, SL, MVT::i32));
5495 
5496     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5497     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5498 
5499     unsigned Idx = KIdx->getZExtValue();
5500     bool InsertLo = Idx < 2;
5501     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5502       InsertLo ? LoVec : HiVec,
5503       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5504       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5505 
5506     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5507 
5508     SDValue Concat = InsertLo ?
5509       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5510       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5511 
5512     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5513   }
5514 
5515   if (isa<ConstantSDNode>(Idx))
5516     return SDValue();
5517 
5518   MVT IntVT = MVT::getIntegerVT(VecSize);
5519 
5520   // Avoid stack access for dynamic indexing.
5521   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5522 
5523   // Create a congruent vector with the target value in each element so that
5524   // the required element can be masked and ORed into the target vector.
5525   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5526                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5527 
5528   assert(isPowerOf2_32(EltSize));
5529   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5530 
5531   // Convert vector index to bit-index.
5532   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5533 
5534   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5535   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5536                             DAG.getConstant(0xffff, SL, IntVT),
5537                             ScaledIdx);
5538 
5539   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5540   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5541                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5542 
5543   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5544   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5545 }
5546 
5547 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5548                                                   SelectionDAG &DAG) const {
5549   SDLoc SL(Op);
5550 
5551   EVT ResultVT = Op.getValueType();
5552   SDValue Vec = Op.getOperand(0);
5553   SDValue Idx = Op.getOperand(1);
5554   EVT VecVT = Vec.getValueType();
5555   unsigned VecSize = VecVT.getSizeInBits();
5556   EVT EltVT = VecVT.getVectorElementType();
5557   assert(VecSize <= 64);
5558 
5559   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5560 
5561   // Make sure we do any optimizations that will make it easier to fold
5562   // source modifiers before obscuring it with bit operations.
5563 
5564   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5565   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5566     return Combined;
5567 
5568   unsigned EltSize = EltVT.getSizeInBits();
5569   assert(isPowerOf2_32(EltSize));
5570 
5571   MVT IntVT = MVT::getIntegerVT(VecSize);
5572   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5573 
5574   // Convert vector index to bit-index (* EltSize)
5575   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5576 
5577   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5578   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5579 
5580   if (ResultVT == MVT::f16) {
5581     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5582     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5583   }
5584 
5585   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5586 }
5587 
5588 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5589   assert(Elt % 2 == 0);
5590   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5591 }
5592 
5593 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5594                                               SelectionDAG &DAG) const {
5595   SDLoc SL(Op);
5596   EVT ResultVT = Op.getValueType();
5597   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5598 
5599   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5600   EVT EltVT = PackVT.getVectorElementType();
5601   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5602 
5603   // vector_shuffle <0,1,6,7> lhs, rhs
5604   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5605   //
5606   // vector_shuffle <6,7,2,3> lhs, rhs
5607   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5608   //
5609   // vector_shuffle <6,7,0,1> lhs, rhs
5610   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5611 
5612   // Avoid scalarizing when both halves are reading from consecutive elements.
5613   SmallVector<SDValue, 4> Pieces;
5614   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5615     if (elementPairIsContiguous(SVN->getMask(), I)) {
5616       const int Idx = SVN->getMaskElt(I);
5617       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5618       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5619       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5620                                     PackVT, SVN->getOperand(VecIdx),
5621                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5622       Pieces.push_back(SubVec);
5623     } else {
5624       const int Idx0 = SVN->getMaskElt(I);
5625       const int Idx1 = SVN->getMaskElt(I + 1);
5626       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5627       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5628       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5629       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5630 
5631       SDValue Vec0 = SVN->getOperand(VecIdx0);
5632       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5633                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5634 
5635       SDValue Vec1 = SVN->getOperand(VecIdx1);
5636       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5637                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5638       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5639     }
5640   }
5641 
5642   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5643 }
5644 
5645 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5646                                             SelectionDAG &DAG) const {
5647   SDLoc SL(Op);
5648   EVT VT = Op.getValueType();
5649 
5650   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5651     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5652 
5653     // Turn into pair of packed build_vectors.
5654     // TODO: Special case for constants that can be materialized with s_mov_b64.
5655     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5656                                     { Op.getOperand(0), Op.getOperand(1) });
5657     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5658                                     { Op.getOperand(2), Op.getOperand(3) });
5659 
5660     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5661     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5662 
5663     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5664     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5665   }
5666 
5667   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5668   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5669 
5670   SDValue Lo = Op.getOperand(0);
5671   SDValue Hi = Op.getOperand(1);
5672 
5673   // Avoid adding defined bits with the zero_extend.
5674   if (Hi.isUndef()) {
5675     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5676     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5677     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5678   }
5679 
5680   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5681   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5682 
5683   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5684                               DAG.getConstant(16, SL, MVT::i32));
5685   if (Lo.isUndef())
5686     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5687 
5688   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5689   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5690 
5691   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5692   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5693 }
5694 
5695 bool
5696 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5697   // We can fold offsets for anything that doesn't require a GOT relocation.
5698   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5699           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5700           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5701          !shouldEmitGOTReloc(GA->getGlobal());
5702 }
5703 
5704 static SDValue
5705 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5706                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5707                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5708   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5709   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5710   // lowered to the following code sequence:
5711   //
5712   // For constant address space:
5713   //   s_getpc_b64 s[0:1]
5714   //   s_add_u32 s0, s0, $symbol
5715   //   s_addc_u32 s1, s1, 0
5716   //
5717   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5718   //   a fixup or relocation is emitted to replace $symbol with a literal
5719   //   constant, which is a pc-relative offset from the encoding of the $symbol
5720   //   operand to the global variable.
5721   //
5722   // For global address space:
5723   //   s_getpc_b64 s[0:1]
5724   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5725   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5726   //
5727   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5728   //   fixups or relocations are emitted to replace $symbol@*@lo and
5729   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5730   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5731   //   operand to the global variable.
5732   //
5733   // What we want here is an offset from the value returned by s_getpc
5734   // (which is the address of the s_add_u32 instruction) to the global
5735   // variable, but since the encoding of $symbol starts 4 bytes after the start
5736   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5737   // small. This requires us to add 4 to the global variable offset in order to
5738   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5739   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5740   // instruction.
5741   SDValue PtrLo =
5742       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5743   SDValue PtrHi;
5744   if (GAFlags == SIInstrInfo::MO_NONE) {
5745     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5746   } else {
5747     PtrHi =
5748         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5749   }
5750   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5751 }
5752 
5753 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5754                                              SDValue Op,
5755                                              SelectionDAG &DAG) const {
5756   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5757   SDLoc DL(GSD);
5758   EVT PtrVT = Op.getValueType();
5759 
5760   const GlobalValue *GV = GSD->getGlobal();
5761   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5762        shouldUseLDSConstAddress(GV)) ||
5763       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5764       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5765     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5766         GV->hasExternalLinkage()) {
5767       Type *Ty = GV->getValueType();
5768       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5769       // zero-sized type in other languages to declare the dynamic shared
5770       // memory which size is not known at the compile time. They will be
5771       // allocated by the runtime and placed directly after the static
5772       // allocated ones. They all share the same offset.
5773       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5774         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5775         // Adjust alignment for that dynamic shared memory array.
5776         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5777         return SDValue(
5778             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5779       }
5780     }
5781     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5782   }
5783 
5784   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5785     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5786                                             SIInstrInfo::MO_ABS32_LO);
5787     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5788   }
5789 
5790   if (shouldEmitFixup(GV))
5791     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5792   else if (shouldEmitPCReloc(GV))
5793     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5794                                    SIInstrInfo::MO_REL32);
5795 
5796   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5797                                             SIInstrInfo::MO_GOTPCREL32);
5798 
5799   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5800   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5801   const DataLayout &DataLayout = DAG.getDataLayout();
5802   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5803   MachinePointerInfo PtrInfo
5804     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5805 
5806   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5807                      MachineMemOperand::MODereferenceable |
5808                          MachineMemOperand::MOInvariant);
5809 }
5810 
5811 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5812                                    const SDLoc &DL, SDValue V) const {
5813   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5814   // the destination register.
5815   //
5816   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5817   // so we will end up with redundant moves to m0.
5818   //
5819   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5820 
5821   // A Null SDValue creates a glue result.
5822   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5823                                   V, Chain);
5824   return SDValue(M0, 0);
5825 }
5826 
5827 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5828                                                  SDValue Op,
5829                                                  MVT VT,
5830                                                  unsigned Offset) const {
5831   SDLoc SL(Op);
5832   SDValue Param = lowerKernargMemParameter(
5833       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5834   // The local size values will have the hi 16-bits as zero.
5835   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5836                      DAG.getValueType(VT));
5837 }
5838 
5839 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5840                                         EVT VT) {
5841   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5842                                       "non-hsa intrinsic with hsa target",
5843                                       DL.getDebugLoc());
5844   DAG.getContext()->diagnose(BadIntrin);
5845   return DAG.getUNDEF(VT);
5846 }
5847 
5848 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5849                                          EVT VT) {
5850   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5851                                       "intrinsic not supported on subtarget",
5852                                       DL.getDebugLoc());
5853   DAG.getContext()->diagnose(BadIntrin);
5854   return DAG.getUNDEF(VT);
5855 }
5856 
5857 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5858                                     ArrayRef<SDValue> Elts) {
5859   assert(!Elts.empty());
5860   MVT Type;
5861   unsigned NumElts = Elts.size();
5862 
5863   if (NumElts <= 8) {
5864     Type = MVT::getVectorVT(MVT::f32, NumElts);
5865   } else {
5866     assert(Elts.size() <= 16);
5867     Type = MVT::v16f32;
5868     NumElts = 16;
5869   }
5870 
5871   SmallVector<SDValue, 16> VecElts(NumElts);
5872   for (unsigned i = 0; i < Elts.size(); ++i) {
5873     SDValue Elt = Elts[i];
5874     if (Elt.getValueType() != MVT::f32)
5875       Elt = DAG.getBitcast(MVT::f32, Elt);
5876     VecElts[i] = Elt;
5877   }
5878   for (unsigned i = Elts.size(); i < NumElts; ++i)
5879     VecElts[i] = DAG.getUNDEF(MVT::f32);
5880 
5881   if (NumElts == 1)
5882     return VecElts[0];
5883   return DAG.getBuildVector(Type, DL, VecElts);
5884 }
5885 
5886 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5887                               SDValue Src, int ExtraElts) {
5888   EVT SrcVT = Src.getValueType();
5889 
5890   SmallVector<SDValue, 8> Elts;
5891 
5892   if (SrcVT.isVector())
5893     DAG.ExtractVectorElements(Src, Elts);
5894   else
5895     Elts.push_back(Src);
5896 
5897   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5898   while (ExtraElts--)
5899     Elts.push_back(Undef);
5900 
5901   return DAG.getBuildVector(CastVT, DL, Elts);
5902 }
5903 
5904 // Re-construct the required return value for a image load intrinsic.
5905 // This is more complicated due to the optional use TexFailCtrl which means the required
5906 // return type is an aggregate
5907 static SDValue constructRetValue(SelectionDAG &DAG,
5908                                  MachineSDNode *Result,
5909                                  ArrayRef<EVT> ResultTypes,
5910                                  bool IsTexFail, bool Unpacked, bool IsD16,
5911                                  int DMaskPop, int NumVDataDwords,
5912                                  const SDLoc &DL) {
5913   // Determine the required return type. This is the same regardless of IsTexFail flag
5914   EVT ReqRetVT = ResultTypes[0];
5915   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5916   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5917     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5918 
5919   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5920     DMaskPop : (DMaskPop + 1) / 2;
5921 
5922   MVT DataDwordVT = NumDataDwords == 1 ?
5923     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5924 
5925   MVT MaskPopVT = MaskPopDwords == 1 ?
5926     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5927 
5928   SDValue Data(Result, 0);
5929   SDValue TexFail;
5930 
5931   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5932     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5933     if (MaskPopVT.isVector()) {
5934       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5935                          SDValue(Result, 0), ZeroIdx);
5936     } else {
5937       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5938                          SDValue(Result, 0), ZeroIdx);
5939     }
5940   }
5941 
5942   if (DataDwordVT.isVector())
5943     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5944                           NumDataDwords - MaskPopDwords);
5945 
5946   if (IsD16)
5947     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5948 
5949   EVT LegalReqRetVT = ReqRetVT;
5950   if (!ReqRetVT.isVector()) {
5951     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5952   } else {
5953     // We need to widen the return vector to a legal type
5954     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5955         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5956       LegalReqRetVT =
5957           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5958                            ReqRetVT.getVectorNumElements() + 1);
5959     }
5960   }
5961   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5962 
5963   if (IsTexFail) {
5964     TexFail =
5965         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5966                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5967 
5968     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5969   }
5970 
5971   if (Result->getNumValues() == 1)
5972     return Data;
5973 
5974   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5975 }
5976 
5977 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5978                          SDValue *LWE, bool &IsTexFail) {
5979   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5980 
5981   uint64_t Value = TexFailCtrlConst->getZExtValue();
5982   if (Value) {
5983     IsTexFail = true;
5984   }
5985 
5986   SDLoc DL(TexFailCtrlConst);
5987   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5988   Value &= ~(uint64_t)0x1;
5989   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5990   Value &= ~(uint64_t)0x2;
5991 
5992   return Value == 0;
5993 }
5994 
5995 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
5996                                       MVT PackVectorVT,
5997                                       SmallVectorImpl<SDValue> &PackedAddrs,
5998                                       unsigned DimIdx, unsigned EndIdx,
5999                                       unsigned NumGradients) {
6000   SDLoc DL(Op);
6001   for (unsigned I = DimIdx; I < EndIdx; I++) {
6002     SDValue Addr = Op.getOperand(I);
6003 
6004     // Gradients are packed with undef for each coordinate.
6005     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6006     // 1D: undef,dx/dh; undef,dx/dv
6007     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6008     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6009     if (((I + 1) >= EndIdx) ||
6010         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6011                                          I == DimIdx + NumGradients - 1))) {
6012       if (Addr.getValueType() != MVT::i16)
6013         Addr = DAG.getBitcast(MVT::i16, Addr);
6014       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6015     } else {
6016       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6017       I++;
6018     }
6019     Addr = DAG.getBitcast(MVT::f32, Addr);
6020     PackedAddrs.push_back(Addr);
6021   }
6022 }
6023 
6024 SDValue SITargetLowering::lowerImage(SDValue Op,
6025                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6026                                      SelectionDAG &DAG, bool WithChain) const {
6027   SDLoc DL(Op);
6028   MachineFunction &MF = DAG.getMachineFunction();
6029   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6030   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6031       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6032   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6033   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6034       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6035   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6036       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6037   unsigned IntrOpcode = Intr->BaseOpcode;
6038   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6039 
6040   SmallVector<EVT, 3> ResultTypes(Op->values());
6041   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6042   bool IsD16 = false;
6043   bool IsG16 = false;
6044   bool IsA16 = false;
6045   SDValue VData;
6046   int NumVDataDwords;
6047   bool AdjustRetType = false;
6048 
6049   // Offset of intrinsic arguments
6050   const unsigned ArgOffset = WithChain ? 2 : 1;
6051 
6052   unsigned DMask;
6053   unsigned DMaskLanes = 0;
6054 
6055   if (BaseOpcode->Atomic) {
6056     VData = Op.getOperand(2);
6057 
6058     bool Is64Bit = VData.getValueType() == MVT::i64;
6059     if (BaseOpcode->AtomicX2) {
6060       SDValue VData2 = Op.getOperand(3);
6061       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6062                                  {VData, VData2});
6063       if (Is64Bit)
6064         VData = DAG.getBitcast(MVT::v4i32, VData);
6065 
6066       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6067       DMask = Is64Bit ? 0xf : 0x3;
6068       NumVDataDwords = Is64Bit ? 4 : 2;
6069     } else {
6070       DMask = Is64Bit ? 0x3 : 0x1;
6071       NumVDataDwords = Is64Bit ? 2 : 1;
6072     }
6073   } else {
6074     auto *DMaskConst =
6075         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6076     DMask = DMaskConst->getZExtValue();
6077     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6078 
6079     if (BaseOpcode->Store) {
6080       VData = Op.getOperand(2);
6081 
6082       MVT StoreVT = VData.getSimpleValueType();
6083       if (StoreVT.getScalarType() == MVT::f16) {
6084         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6085           return Op; // D16 is unsupported for this instruction
6086 
6087         IsD16 = true;
6088         VData = handleD16VData(VData, DAG, true);
6089       }
6090 
6091       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6092     } else {
6093       // Work out the num dwords based on the dmask popcount and underlying type
6094       // and whether packing is supported.
6095       MVT LoadVT = ResultTypes[0].getSimpleVT();
6096       if (LoadVT.getScalarType() == MVT::f16) {
6097         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6098           return Op; // D16 is unsupported for this instruction
6099 
6100         IsD16 = true;
6101       }
6102 
6103       // Confirm that the return type is large enough for the dmask specified
6104       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6105           (!LoadVT.isVector() && DMaskLanes > 1))
6106           return Op;
6107 
6108       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6109       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6110       // instructions.
6111       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6112           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6113         NumVDataDwords = (DMaskLanes + 1) / 2;
6114       else
6115         NumVDataDwords = DMaskLanes;
6116 
6117       AdjustRetType = true;
6118     }
6119   }
6120 
6121   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6122   SmallVector<SDValue, 4> VAddrs;
6123 
6124   // Optimize _L to _LZ when _L is zero
6125   if (LZMappingInfo) {
6126     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6127             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6128       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6129         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6130         VAddrEnd--;                      // remove 'lod'
6131       }
6132     }
6133   }
6134 
6135   // Optimize _mip away, when 'lod' is zero
6136   if (MIPMappingInfo) {
6137     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6138             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6139       if (ConstantLod->isNullValue()) {
6140         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6141         VAddrEnd--;                           // remove 'mip'
6142       }
6143     }
6144   }
6145 
6146   // Push back extra arguments.
6147   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6148     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6149 
6150   // Check for 16 bit addresses or derivatives and pack if true.
6151   MVT VAddrVT =
6152       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6153   MVT VAddrScalarVT = VAddrVT.getScalarType();
6154   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6155   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6156 
6157   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6158   VAddrScalarVT = VAddrVT.getScalarType();
6159   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6160   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6161 
6162   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6163     // 16 bit gradients are supported, but are tied to the A16 control
6164     // so both gradients and addresses must be 16 bit
6165     LLVM_DEBUG(
6166         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6167                   "require 16 bit args for both gradients and addresses");
6168     return Op;
6169   }
6170 
6171   if (IsA16) {
6172     if (!ST->hasA16()) {
6173       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6174                            "support 16 bit addresses\n");
6175       return Op;
6176     }
6177   }
6178 
6179   // We've dealt with incorrect input so we know that if IsA16, IsG16
6180   // are set then we have to compress/pack operands (either address,
6181   // gradient or both)
6182   // In the case where a16 and gradients are tied (no G16 support) then we
6183   // have already verified that both IsA16 and IsG16 are true
6184   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6185     // Activate g16
6186     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6187         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6188     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6189   }
6190 
6191   // Add gradients (packed or unpacked)
6192   if (IsG16) {
6193     // Pack the gradients
6194     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6195     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6196                               ArgOffset + Intr->GradientStart,
6197                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6198   } else {
6199     for (unsigned I = ArgOffset + Intr->GradientStart;
6200          I < ArgOffset + Intr->CoordStart; I++)
6201       VAddrs.push_back(Op.getOperand(I));
6202   }
6203 
6204   // Add addresses (packed or unpacked)
6205   if (IsA16) {
6206     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6207                               ArgOffset + Intr->CoordStart, VAddrEnd,
6208                               0 /* No gradients */);
6209   } else {
6210     // Add uncompressed address
6211     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6212       VAddrs.push_back(Op.getOperand(I));
6213   }
6214 
6215   // If the register allocator cannot place the address registers contiguously
6216   // without introducing moves, then using the non-sequential address encoding
6217   // is always preferable, since it saves VALU instructions and is usually a
6218   // wash in terms of code size or even better.
6219   //
6220   // However, we currently have no way of hinting to the register allocator that
6221   // MIMG addresses should be placed contiguously when it is possible to do so,
6222   // so force non-NSA for the common 2-address case as a heuristic.
6223   //
6224   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6225   // allocation when possible.
6226   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6227                 VAddrs.size() >= 3 &&
6228                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6229   SDValue VAddr;
6230   if (!UseNSA)
6231     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6232 
6233   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6234   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6235   SDValue Unorm;
6236   if (!BaseOpcode->Sampler) {
6237     Unorm = True;
6238   } else {
6239     auto UnormConst =
6240         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6241 
6242     Unorm = UnormConst->getZExtValue() ? True : False;
6243   }
6244 
6245   SDValue TFE;
6246   SDValue LWE;
6247   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6248   bool IsTexFail = false;
6249   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6250     return Op;
6251 
6252   if (IsTexFail) {
6253     if (!DMaskLanes) {
6254       // Expecting to get an error flag since TFC is on - and dmask is 0
6255       // Force dmask to be at least 1 otherwise the instruction will fail
6256       DMask = 0x1;
6257       DMaskLanes = 1;
6258       NumVDataDwords = 1;
6259     }
6260     NumVDataDwords += 1;
6261     AdjustRetType = true;
6262   }
6263 
6264   // Has something earlier tagged that the return type needs adjusting
6265   // This happens if the instruction is a load or has set TexFailCtrl flags
6266   if (AdjustRetType) {
6267     // NumVDataDwords reflects the true number of dwords required in the return type
6268     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6269       // This is a no-op load. This can be eliminated
6270       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6271       if (isa<MemSDNode>(Op))
6272         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6273       return Undef;
6274     }
6275 
6276     EVT NewVT = NumVDataDwords > 1 ?
6277                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6278                 : MVT::i32;
6279 
6280     ResultTypes[0] = NewVT;
6281     if (ResultTypes.size() == 3) {
6282       // Original result was aggregate type used for TexFailCtrl results
6283       // The actual instruction returns as a vector type which has now been
6284       // created. Remove the aggregate result.
6285       ResultTypes.erase(&ResultTypes[1]);
6286     }
6287   }
6288 
6289   unsigned CPol = cast<ConstantSDNode>(
6290       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6291   if (BaseOpcode->Atomic)
6292     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6293   if (CPol & ~AMDGPU::CPol::ALL)
6294     return Op;
6295 
6296   SmallVector<SDValue, 26> Ops;
6297   if (BaseOpcode->Store || BaseOpcode->Atomic)
6298     Ops.push_back(VData); // vdata
6299   if (UseNSA)
6300     append_range(Ops, VAddrs);
6301   else
6302     Ops.push_back(VAddr);
6303   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6304   if (BaseOpcode->Sampler)
6305     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6306   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6307   if (IsGFX10Plus)
6308     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6309   Ops.push_back(Unorm);
6310   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6311   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6312                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6313   if (IsGFX10Plus)
6314     Ops.push_back(IsA16 ? True : False);
6315   if (!Subtarget->hasGFX90AInsts()) {
6316     Ops.push_back(TFE); //tfe
6317   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6318     report_fatal_error("TFE is not supported on this GPU");
6319   }
6320   Ops.push_back(LWE); // lwe
6321   if (!IsGFX10Plus)
6322     Ops.push_back(DimInfo->DA ? True : False);
6323   if (BaseOpcode->HasD16)
6324     Ops.push_back(IsD16 ? True : False);
6325   if (isa<MemSDNode>(Op))
6326     Ops.push_back(Op.getOperand(0)); // chain
6327 
6328   int NumVAddrDwords =
6329       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6330   int Opcode = -1;
6331 
6332   if (IsGFX10Plus) {
6333     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6334                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6335                                           : AMDGPU::MIMGEncGfx10Default,
6336                                    NumVDataDwords, NumVAddrDwords);
6337   } else {
6338     if (Subtarget->hasGFX90AInsts()) {
6339       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6340                                      NumVDataDwords, NumVAddrDwords);
6341       if (Opcode == -1)
6342         report_fatal_error(
6343             "requested image instruction is not supported on this GPU");
6344     }
6345     if (Opcode == -1 &&
6346         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6347       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6348                                      NumVDataDwords, NumVAddrDwords);
6349     if (Opcode == -1)
6350       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6351                                      NumVDataDwords, NumVAddrDwords);
6352   }
6353   assert(Opcode != -1);
6354 
6355   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6356   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6357     MachineMemOperand *MemRef = MemOp->getMemOperand();
6358     DAG.setNodeMemRefs(NewNode, {MemRef});
6359   }
6360 
6361   if (BaseOpcode->AtomicX2) {
6362     SmallVector<SDValue, 1> Elt;
6363     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6364     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6365   }
6366   if (BaseOpcode->Store)
6367     return SDValue(NewNode, 0);
6368   return constructRetValue(DAG, NewNode,
6369                            OrigResultTypes, IsTexFail,
6370                            Subtarget->hasUnpackedD16VMem(), IsD16,
6371                            DMaskLanes, NumVDataDwords, DL);
6372 }
6373 
6374 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6375                                        SDValue Offset, SDValue CachePolicy,
6376                                        SelectionDAG &DAG) const {
6377   MachineFunction &MF = DAG.getMachineFunction();
6378 
6379   const DataLayout &DataLayout = DAG.getDataLayout();
6380   Align Alignment =
6381       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6382 
6383   MachineMemOperand *MMO = MF.getMachineMemOperand(
6384       MachinePointerInfo(),
6385       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6386           MachineMemOperand::MOInvariant,
6387       VT.getStoreSize(), Alignment);
6388 
6389   if (!Offset->isDivergent()) {
6390     SDValue Ops[] = {
6391         Rsrc,
6392         Offset, // Offset
6393         CachePolicy
6394     };
6395 
6396     // Widen vec3 load to vec4.
6397     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6398       EVT WidenedVT =
6399           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6400       auto WidenedOp = DAG.getMemIntrinsicNode(
6401           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6402           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6403       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6404                                    DAG.getVectorIdxConstant(0, DL));
6405       return Subvector;
6406     }
6407 
6408     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6409                                    DAG.getVTList(VT), Ops, VT, MMO);
6410   }
6411 
6412   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6413   // assume that the buffer is unswizzled.
6414   SmallVector<SDValue, 4> Loads;
6415   unsigned NumLoads = 1;
6416   MVT LoadVT = VT.getSimpleVT();
6417   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6418   assert((LoadVT.getScalarType() == MVT::i32 ||
6419           LoadVT.getScalarType() == MVT::f32));
6420 
6421   if (NumElts == 8 || NumElts == 16) {
6422     NumLoads = NumElts / 4;
6423     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6424   }
6425 
6426   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6427   SDValue Ops[] = {
6428       DAG.getEntryNode(),                               // Chain
6429       Rsrc,                                             // rsrc
6430       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6431       {},                                               // voffset
6432       {},                                               // soffset
6433       {},                                               // offset
6434       CachePolicy,                                      // cachepolicy
6435       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6436   };
6437 
6438   // Use the alignment to ensure that the required offsets will fit into the
6439   // immediate offsets.
6440   setBufferOffsets(Offset, DAG, &Ops[3],
6441                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6442 
6443   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6444   for (unsigned i = 0; i < NumLoads; ++i) {
6445     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6446     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6447                                         LoadVT, MMO, DAG));
6448   }
6449 
6450   if (NumElts == 8 || NumElts == 16)
6451     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6452 
6453   return Loads[0];
6454 }
6455 
6456 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6457                                                   SelectionDAG &DAG) const {
6458   MachineFunction &MF = DAG.getMachineFunction();
6459   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6460 
6461   EVT VT = Op.getValueType();
6462   SDLoc DL(Op);
6463   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6464 
6465   // TODO: Should this propagate fast-math-flags?
6466 
6467   switch (IntrinsicID) {
6468   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6469     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6470       return emitNonHSAIntrinsicError(DAG, DL, VT);
6471     return getPreloadedValue(DAG, *MFI, VT,
6472                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6473   }
6474   case Intrinsic::amdgcn_dispatch_ptr:
6475   case Intrinsic::amdgcn_queue_ptr: {
6476     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6477       DiagnosticInfoUnsupported BadIntrin(
6478           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6479           DL.getDebugLoc());
6480       DAG.getContext()->diagnose(BadIntrin);
6481       return DAG.getUNDEF(VT);
6482     }
6483 
6484     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6485       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6486     return getPreloadedValue(DAG, *MFI, VT, RegID);
6487   }
6488   case Intrinsic::amdgcn_implicitarg_ptr: {
6489     if (MFI->isEntryFunction())
6490       return getImplicitArgPtr(DAG, DL);
6491     return getPreloadedValue(DAG, *MFI, VT,
6492                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6493   }
6494   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6495     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6496       // This only makes sense to call in a kernel, so just lower to null.
6497       return DAG.getConstant(0, DL, VT);
6498     }
6499 
6500     return getPreloadedValue(DAG, *MFI, VT,
6501                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6502   }
6503   case Intrinsic::amdgcn_dispatch_id: {
6504     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6505   }
6506   case Intrinsic::amdgcn_rcp:
6507     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6508   case Intrinsic::amdgcn_rsq:
6509     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6510   case Intrinsic::amdgcn_rsq_legacy:
6511     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6512       return emitRemovedIntrinsicError(DAG, DL, VT);
6513     return SDValue();
6514   case Intrinsic::amdgcn_rcp_legacy:
6515     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6516       return emitRemovedIntrinsicError(DAG, DL, VT);
6517     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6518   case Intrinsic::amdgcn_rsq_clamp: {
6519     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6520       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6521 
6522     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6523     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6524     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6525 
6526     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6527     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6528                               DAG.getConstantFP(Max, DL, VT));
6529     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6530                        DAG.getConstantFP(Min, DL, VT));
6531   }
6532   case Intrinsic::r600_read_ngroups_x:
6533     if (Subtarget->isAmdHsaOS())
6534       return emitNonHSAIntrinsicError(DAG, DL, VT);
6535 
6536     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6537                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6538                                     false);
6539   case Intrinsic::r600_read_ngroups_y:
6540     if (Subtarget->isAmdHsaOS())
6541       return emitNonHSAIntrinsicError(DAG, DL, VT);
6542 
6543     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6544                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6545                                     false);
6546   case Intrinsic::r600_read_ngroups_z:
6547     if (Subtarget->isAmdHsaOS())
6548       return emitNonHSAIntrinsicError(DAG, DL, VT);
6549 
6550     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6551                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6552                                     false);
6553   case Intrinsic::r600_read_global_size_x:
6554     if (Subtarget->isAmdHsaOS())
6555       return emitNonHSAIntrinsicError(DAG, DL, VT);
6556 
6557     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6558                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6559                                     Align(4), false);
6560   case Intrinsic::r600_read_global_size_y:
6561     if (Subtarget->isAmdHsaOS())
6562       return emitNonHSAIntrinsicError(DAG, DL, VT);
6563 
6564     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6565                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6566                                     Align(4), false);
6567   case Intrinsic::r600_read_global_size_z:
6568     if (Subtarget->isAmdHsaOS())
6569       return emitNonHSAIntrinsicError(DAG, DL, VT);
6570 
6571     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6572                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6573                                     Align(4), false);
6574   case Intrinsic::r600_read_local_size_x:
6575     if (Subtarget->isAmdHsaOS())
6576       return emitNonHSAIntrinsicError(DAG, DL, VT);
6577 
6578     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6579                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6580   case Intrinsic::r600_read_local_size_y:
6581     if (Subtarget->isAmdHsaOS())
6582       return emitNonHSAIntrinsicError(DAG, DL, VT);
6583 
6584     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6585                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6586   case Intrinsic::r600_read_local_size_z:
6587     if (Subtarget->isAmdHsaOS())
6588       return emitNonHSAIntrinsicError(DAG, DL, VT);
6589 
6590     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6591                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6592   case Intrinsic::amdgcn_workgroup_id_x:
6593     return getPreloadedValue(DAG, *MFI, VT,
6594                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6595   case Intrinsic::amdgcn_workgroup_id_y:
6596     return getPreloadedValue(DAG, *MFI, VT,
6597                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6598   case Intrinsic::amdgcn_workgroup_id_z:
6599     return getPreloadedValue(DAG, *MFI, VT,
6600                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6601   case Intrinsic::amdgcn_workitem_id_x:
6602     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6603                           SDLoc(DAG.getEntryNode()),
6604                           MFI->getArgInfo().WorkItemIDX);
6605   case Intrinsic::amdgcn_workitem_id_y:
6606     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6607                           SDLoc(DAG.getEntryNode()),
6608                           MFI->getArgInfo().WorkItemIDY);
6609   case Intrinsic::amdgcn_workitem_id_z:
6610     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6611                           SDLoc(DAG.getEntryNode()),
6612                           MFI->getArgInfo().WorkItemIDZ);
6613   case Intrinsic::amdgcn_wavefrontsize:
6614     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6615                            SDLoc(Op), MVT::i32);
6616   case Intrinsic::amdgcn_s_buffer_load: {
6617     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6618     if (CPol & ~AMDGPU::CPol::ALL)
6619       return Op;
6620     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6621                         DAG);
6622   }
6623   case Intrinsic::amdgcn_fdiv_fast:
6624     return lowerFDIV_FAST(Op, DAG);
6625   case Intrinsic::amdgcn_sin:
6626     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6627 
6628   case Intrinsic::amdgcn_cos:
6629     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6630 
6631   case Intrinsic::amdgcn_mul_u24:
6632     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6633   case Intrinsic::amdgcn_mul_i24:
6634     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6635 
6636   case Intrinsic::amdgcn_log_clamp: {
6637     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6638       return SDValue();
6639 
6640     return emitRemovedIntrinsicError(DAG, DL, VT);
6641   }
6642   case Intrinsic::amdgcn_ldexp:
6643     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6644                        Op.getOperand(1), Op.getOperand(2));
6645 
6646   case Intrinsic::amdgcn_fract:
6647     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6648 
6649   case Intrinsic::amdgcn_class:
6650     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6651                        Op.getOperand(1), Op.getOperand(2));
6652   case Intrinsic::amdgcn_div_fmas:
6653     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6654                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6655                        Op.getOperand(4));
6656 
6657   case Intrinsic::amdgcn_div_fixup:
6658     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6659                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6660 
6661   case Intrinsic::amdgcn_div_scale: {
6662     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6663 
6664     // Translate to the operands expected by the machine instruction. The
6665     // first parameter must be the same as the first instruction.
6666     SDValue Numerator = Op.getOperand(1);
6667     SDValue Denominator = Op.getOperand(2);
6668 
6669     // Note this order is opposite of the machine instruction's operations,
6670     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6671     // intrinsic has the numerator as the first operand to match a normal
6672     // division operation.
6673 
6674     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6675 
6676     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6677                        Denominator, Numerator);
6678   }
6679   case Intrinsic::amdgcn_icmp: {
6680     // There is a Pat that handles this variant, so return it as-is.
6681     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6682         Op.getConstantOperandVal(2) == 0 &&
6683         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6684       return Op;
6685     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6686   }
6687   case Intrinsic::amdgcn_fcmp: {
6688     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6689   }
6690   case Intrinsic::amdgcn_ballot:
6691     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6692   case Intrinsic::amdgcn_fmed3:
6693     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6694                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6695   case Intrinsic::amdgcn_fdot2:
6696     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6697                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6698                        Op.getOperand(4));
6699   case Intrinsic::amdgcn_fmul_legacy:
6700     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6701                        Op.getOperand(1), Op.getOperand(2));
6702   case Intrinsic::amdgcn_sffbh:
6703     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6704   case Intrinsic::amdgcn_sbfe:
6705     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6706                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6707   case Intrinsic::amdgcn_ubfe:
6708     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6709                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6710   case Intrinsic::amdgcn_cvt_pkrtz:
6711   case Intrinsic::amdgcn_cvt_pknorm_i16:
6712   case Intrinsic::amdgcn_cvt_pknorm_u16:
6713   case Intrinsic::amdgcn_cvt_pk_i16:
6714   case Intrinsic::amdgcn_cvt_pk_u16: {
6715     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6716     EVT VT = Op.getValueType();
6717     unsigned Opcode;
6718 
6719     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6720       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6721     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6722       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6723     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6724       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6725     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6726       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6727     else
6728       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6729 
6730     if (isTypeLegal(VT))
6731       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6732 
6733     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6734                                Op.getOperand(1), Op.getOperand(2));
6735     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6736   }
6737   case Intrinsic::amdgcn_fmad_ftz:
6738     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6739                        Op.getOperand(2), Op.getOperand(3));
6740 
6741   case Intrinsic::amdgcn_if_break:
6742     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6743                                       Op->getOperand(1), Op->getOperand(2)), 0);
6744 
6745   case Intrinsic::amdgcn_groupstaticsize: {
6746     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6747     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6748       return Op;
6749 
6750     const Module *M = MF.getFunction().getParent();
6751     const GlobalValue *GV =
6752         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6753     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6754                                             SIInstrInfo::MO_ABS32_LO);
6755     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6756   }
6757   case Intrinsic::amdgcn_is_shared:
6758   case Intrinsic::amdgcn_is_private: {
6759     SDLoc SL(Op);
6760     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6761       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6762     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6763     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6764                                  Op.getOperand(1));
6765 
6766     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6767                                 DAG.getConstant(1, SL, MVT::i32));
6768     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6769   }
6770   case Intrinsic::amdgcn_alignbit:
6771     return DAG.getNode(ISD::FSHR, DL, VT,
6772                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6773   case Intrinsic::amdgcn_perm:
6774     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6775                        Op.getOperand(2), Op.getOperand(3));
6776   case Intrinsic::amdgcn_reloc_constant: {
6777     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6778     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6779     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6780     auto RelocSymbol = cast<GlobalVariable>(
6781         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6782     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6783                                             SIInstrInfo::MO_ABS32_LO);
6784     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6785   }
6786   default:
6787     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6788             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6789       return lowerImage(Op, ImageDimIntr, DAG, false);
6790 
6791     return Op;
6792   }
6793 }
6794 
6795 /// Update \p MMO based on the offset inputs to an intrinsic.
6796 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6797                             SDValue SOffset, SDValue Offset,
6798                             SDValue VIndex = SDValue()) {
6799   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6800       !isa<ConstantSDNode>(Offset)) {
6801     // The combined offset is not known to be constant, so we cannot represent
6802     // it in the MMO. Give up.
6803     MMO->setValue((Value *)nullptr);
6804     return;
6805   }
6806 
6807   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6808                  !cast<ConstantSDNode>(VIndex)->isNullValue())) {
6809     // The strided index component of the address is not known to be zero, so we
6810     // cannot represent it in the MMO. Give up.
6811     MMO->setValue((Value *)nullptr);
6812     return;
6813   }
6814 
6815   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6816                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6817                  cast<ConstantSDNode>(Offset)->getSExtValue());
6818 }
6819 
6820 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6821                                                      SelectionDAG &DAG,
6822                                                      unsigned NewOpcode) const {
6823   SDLoc DL(Op);
6824 
6825   SDValue VData = Op.getOperand(2);
6826   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6827   SDValue Ops[] = {
6828     Op.getOperand(0), // Chain
6829     VData,            // vdata
6830     Op.getOperand(3), // rsrc
6831     DAG.getConstant(0, DL, MVT::i32), // vindex
6832     Offsets.first,    // voffset
6833     Op.getOperand(5), // soffset
6834     Offsets.second,   // offset
6835     Op.getOperand(6), // cachepolicy
6836     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6837   };
6838 
6839   auto *M = cast<MemSDNode>(Op);
6840   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6841 
6842   EVT MemVT = VData.getValueType();
6843   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6844                                  M->getMemOperand());
6845 }
6846 
6847 // Return a value to use for the idxen operand by examining the vindex operand.
6848 static unsigned getIdxEn(SDValue VIndex) {
6849   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6850     // No need to set idxen if vindex is known to be zero.
6851     return VIndexC->getZExtValue() != 0;
6852   return 1;
6853 }
6854 
6855 SDValue
6856 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6857                                                 unsigned NewOpcode) const {
6858   SDLoc DL(Op);
6859 
6860   SDValue VData = Op.getOperand(2);
6861   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6862   SDValue Ops[] = {
6863     Op.getOperand(0), // Chain
6864     VData,            // vdata
6865     Op.getOperand(3), // rsrc
6866     Op.getOperand(4), // vindex
6867     Offsets.first,    // voffset
6868     Op.getOperand(6), // soffset
6869     Offsets.second,   // offset
6870     Op.getOperand(7), // cachepolicy
6871     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6872   };
6873 
6874   auto *M = cast<MemSDNode>(Op);
6875   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
6876 
6877   EVT MemVT = VData.getValueType();
6878   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6879                                  M->getMemOperand());
6880 }
6881 
6882 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6883                                                  SelectionDAG &DAG) const {
6884   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6885   SDLoc DL(Op);
6886 
6887   switch (IntrID) {
6888   case Intrinsic::amdgcn_ds_ordered_add:
6889   case Intrinsic::amdgcn_ds_ordered_swap: {
6890     MemSDNode *M = cast<MemSDNode>(Op);
6891     SDValue Chain = M->getOperand(0);
6892     SDValue M0 = M->getOperand(2);
6893     SDValue Value = M->getOperand(3);
6894     unsigned IndexOperand = M->getConstantOperandVal(7);
6895     unsigned WaveRelease = M->getConstantOperandVal(8);
6896     unsigned WaveDone = M->getConstantOperandVal(9);
6897 
6898     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6899     IndexOperand &= ~0x3f;
6900     unsigned CountDw = 0;
6901 
6902     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6903       CountDw = (IndexOperand >> 24) & 0xf;
6904       IndexOperand &= ~(0xf << 24);
6905 
6906       if (CountDw < 1 || CountDw > 4) {
6907         report_fatal_error(
6908             "ds_ordered_count: dword count must be between 1 and 4");
6909       }
6910     }
6911 
6912     if (IndexOperand)
6913       report_fatal_error("ds_ordered_count: bad index operand");
6914 
6915     if (WaveDone && !WaveRelease)
6916       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6917 
6918     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6919     unsigned ShaderType =
6920         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6921     unsigned Offset0 = OrderedCountIndex << 2;
6922     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6923                        (Instruction << 4);
6924 
6925     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6926       Offset1 |= (CountDw - 1) << 6;
6927 
6928     unsigned Offset = Offset0 | (Offset1 << 8);
6929 
6930     SDValue Ops[] = {
6931       Chain,
6932       Value,
6933       DAG.getTargetConstant(Offset, DL, MVT::i16),
6934       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6935     };
6936     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6937                                    M->getVTList(), Ops, M->getMemoryVT(),
6938                                    M->getMemOperand());
6939   }
6940   case Intrinsic::amdgcn_ds_fadd: {
6941     MemSDNode *M = cast<MemSDNode>(Op);
6942     unsigned Opc;
6943     switch (IntrID) {
6944     case Intrinsic::amdgcn_ds_fadd:
6945       Opc = ISD::ATOMIC_LOAD_FADD;
6946       break;
6947     }
6948 
6949     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6950                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6951                          M->getMemOperand());
6952   }
6953   case Intrinsic::amdgcn_atomic_inc:
6954   case Intrinsic::amdgcn_atomic_dec:
6955   case Intrinsic::amdgcn_ds_fmin:
6956   case Intrinsic::amdgcn_ds_fmax: {
6957     MemSDNode *M = cast<MemSDNode>(Op);
6958     unsigned Opc;
6959     switch (IntrID) {
6960     case Intrinsic::amdgcn_atomic_inc:
6961       Opc = AMDGPUISD::ATOMIC_INC;
6962       break;
6963     case Intrinsic::amdgcn_atomic_dec:
6964       Opc = AMDGPUISD::ATOMIC_DEC;
6965       break;
6966     case Intrinsic::amdgcn_ds_fmin:
6967       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6968       break;
6969     case Intrinsic::amdgcn_ds_fmax:
6970       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6971       break;
6972     default:
6973       llvm_unreachable("Unknown intrinsic!");
6974     }
6975     SDValue Ops[] = {
6976       M->getOperand(0), // Chain
6977       M->getOperand(2), // Ptr
6978       M->getOperand(3)  // Value
6979     };
6980 
6981     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6982                                    M->getMemoryVT(), M->getMemOperand());
6983   }
6984   case Intrinsic::amdgcn_buffer_load:
6985   case Intrinsic::amdgcn_buffer_load_format: {
6986     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6987     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6988     unsigned IdxEn = getIdxEn(Op.getOperand(3));
6989     SDValue Ops[] = {
6990       Op.getOperand(0), // Chain
6991       Op.getOperand(2), // rsrc
6992       Op.getOperand(3), // vindex
6993       SDValue(),        // voffset -- will be set by setBufferOffsets
6994       SDValue(),        // soffset -- will be set by setBufferOffsets
6995       SDValue(),        // offset -- will be set by setBufferOffsets
6996       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6997       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6998     };
6999     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7000 
7001     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7002         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7003 
7004     EVT VT = Op.getValueType();
7005     EVT IntVT = VT.changeTypeToInteger();
7006     auto *M = cast<MemSDNode>(Op);
7007     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7008     EVT LoadVT = Op.getValueType();
7009 
7010     if (LoadVT.getScalarType() == MVT::f16)
7011       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7012                                  M, DAG, Ops);
7013 
7014     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7015     if (LoadVT.getScalarType() == MVT::i8 ||
7016         LoadVT.getScalarType() == MVT::i16)
7017       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7018 
7019     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7020                                M->getMemOperand(), DAG);
7021   }
7022   case Intrinsic::amdgcn_raw_buffer_load:
7023   case Intrinsic::amdgcn_raw_buffer_load_format: {
7024     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7025 
7026     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7027     SDValue Ops[] = {
7028       Op.getOperand(0), // Chain
7029       Op.getOperand(2), // rsrc
7030       DAG.getConstant(0, DL, MVT::i32), // vindex
7031       Offsets.first,    // voffset
7032       Op.getOperand(4), // soffset
7033       Offsets.second,   // offset
7034       Op.getOperand(5), // cachepolicy, swizzled buffer
7035       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7036     };
7037 
7038     auto *M = cast<MemSDNode>(Op);
7039     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7040     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7041   }
7042   case Intrinsic::amdgcn_struct_buffer_load:
7043   case Intrinsic::amdgcn_struct_buffer_load_format: {
7044     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7045 
7046     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7047     SDValue Ops[] = {
7048       Op.getOperand(0), // Chain
7049       Op.getOperand(2), // rsrc
7050       Op.getOperand(3), // vindex
7051       Offsets.first,    // voffset
7052       Op.getOperand(5), // soffset
7053       Offsets.second,   // offset
7054       Op.getOperand(6), // cachepolicy, swizzled buffer
7055       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7056     };
7057 
7058     auto *M = cast<MemSDNode>(Op);
7059     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7060     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7061   }
7062   case Intrinsic::amdgcn_tbuffer_load: {
7063     MemSDNode *M = cast<MemSDNode>(Op);
7064     EVT LoadVT = Op.getValueType();
7065 
7066     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7067     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7068     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7069     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7070     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7071     SDValue Ops[] = {
7072       Op.getOperand(0),  // Chain
7073       Op.getOperand(2),  // rsrc
7074       Op.getOperand(3),  // vindex
7075       Op.getOperand(4),  // voffset
7076       Op.getOperand(5),  // soffset
7077       Op.getOperand(6),  // offset
7078       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7079       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7080       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7081     };
7082 
7083     if (LoadVT.getScalarType() == MVT::f16)
7084       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7085                                  M, DAG, Ops);
7086     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7087                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7088                                DAG);
7089   }
7090   case Intrinsic::amdgcn_raw_tbuffer_load: {
7091     MemSDNode *M = cast<MemSDNode>(Op);
7092     EVT LoadVT = Op.getValueType();
7093     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7094 
7095     SDValue Ops[] = {
7096       Op.getOperand(0),  // Chain
7097       Op.getOperand(2),  // rsrc
7098       DAG.getConstant(0, DL, MVT::i32), // vindex
7099       Offsets.first,     // voffset
7100       Op.getOperand(4),  // soffset
7101       Offsets.second,    // offset
7102       Op.getOperand(5),  // format
7103       Op.getOperand(6),  // cachepolicy, swizzled buffer
7104       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7105     };
7106 
7107     if (LoadVT.getScalarType() == MVT::f16)
7108       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7109                                  M, DAG, Ops);
7110     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7111                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7112                                DAG);
7113   }
7114   case Intrinsic::amdgcn_struct_tbuffer_load: {
7115     MemSDNode *M = cast<MemSDNode>(Op);
7116     EVT LoadVT = Op.getValueType();
7117     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7118 
7119     SDValue Ops[] = {
7120       Op.getOperand(0),  // Chain
7121       Op.getOperand(2),  // rsrc
7122       Op.getOperand(3),  // vindex
7123       Offsets.first,     // voffset
7124       Op.getOperand(5),  // soffset
7125       Offsets.second,    // offset
7126       Op.getOperand(6),  // format
7127       Op.getOperand(7),  // cachepolicy, swizzled buffer
7128       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7129     };
7130 
7131     if (LoadVT.getScalarType() == MVT::f16)
7132       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7133                                  M, DAG, Ops);
7134     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7135                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7136                                DAG);
7137   }
7138   case Intrinsic::amdgcn_buffer_atomic_swap:
7139   case Intrinsic::amdgcn_buffer_atomic_add:
7140   case Intrinsic::amdgcn_buffer_atomic_sub:
7141   case Intrinsic::amdgcn_buffer_atomic_csub:
7142   case Intrinsic::amdgcn_buffer_atomic_smin:
7143   case Intrinsic::amdgcn_buffer_atomic_umin:
7144   case Intrinsic::amdgcn_buffer_atomic_smax:
7145   case Intrinsic::amdgcn_buffer_atomic_umax:
7146   case Intrinsic::amdgcn_buffer_atomic_and:
7147   case Intrinsic::amdgcn_buffer_atomic_or:
7148   case Intrinsic::amdgcn_buffer_atomic_xor:
7149   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7150     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7151     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7152     SDValue Ops[] = {
7153       Op.getOperand(0), // Chain
7154       Op.getOperand(2), // vdata
7155       Op.getOperand(3), // rsrc
7156       Op.getOperand(4), // vindex
7157       SDValue(),        // voffset -- will be set by setBufferOffsets
7158       SDValue(),        // soffset -- will be set by setBufferOffsets
7159       SDValue(),        // offset -- will be set by setBufferOffsets
7160       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7161       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7162     };
7163     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7164 
7165     EVT VT = Op.getValueType();
7166 
7167     auto *M = cast<MemSDNode>(Op);
7168     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7169     unsigned Opcode = 0;
7170 
7171     switch (IntrID) {
7172     case Intrinsic::amdgcn_buffer_atomic_swap:
7173       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7174       break;
7175     case Intrinsic::amdgcn_buffer_atomic_add:
7176       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7177       break;
7178     case Intrinsic::amdgcn_buffer_atomic_sub:
7179       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7180       break;
7181     case Intrinsic::amdgcn_buffer_atomic_csub:
7182       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7183       break;
7184     case Intrinsic::amdgcn_buffer_atomic_smin:
7185       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7186       break;
7187     case Intrinsic::amdgcn_buffer_atomic_umin:
7188       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7189       break;
7190     case Intrinsic::amdgcn_buffer_atomic_smax:
7191       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7192       break;
7193     case Intrinsic::amdgcn_buffer_atomic_umax:
7194       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7195       break;
7196     case Intrinsic::amdgcn_buffer_atomic_and:
7197       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7198       break;
7199     case Intrinsic::amdgcn_buffer_atomic_or:
7200       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7201       break;
7202     case Intrinsic::amdgcn_buffer_atomic_xor:
7203       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7204       break;
7205     case Intrinsic::amdgcn_buffer_atomic_fadd:
7206       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7207         DiagnosticInfoUnsupported
7208           NoFpRet(DAG.getMachineFunction().getFunction(),
7209                   "return versions of fp atomics not supported",
7210                   DL.getDebugLoc(), DS_Error);
7211         DAG.getContext()->diagnose(NoFpRet);
7212         return SDValue();
7213       }
7214       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7215       break;
7216     default:
7217       llvm_unreachable("unhandled atomic opcode");
7218     }
7219 
7220     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7221                                    M->getMemOperand());
7222   }
7223   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7224     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7225   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7226     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7227   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7228     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7229   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7230     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7231   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7232     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7233   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7234     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7235   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7236     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7237   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7238     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7239   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7240     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7241   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7242     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7243   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7244     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7245   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7246     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7247   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7248     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7249   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7250     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7251   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7252     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7253   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7254     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7255   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7256     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7257   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7258     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7259   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7260     return lowerStructBufferAtomicIntrin(Op, DAG,
7261                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7262   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7263     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7264   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7265     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7266   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7267     return lowerStructBufferAtomicIntrin(Op, DAG,
7268                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7269   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7270     return lowerStructBufferAtomicIntrin(Op, DAG,
7271                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7272   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7273     return lowerStructBufferAtomicIntrin(Op, DAG,
7274                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7275   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7276     return lowerStructBufferAtomicIntrin(Op, DAG,
7277                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7278   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7279     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7280   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7281     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7282   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7283     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7284   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7285     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7286   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7287     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7288 
7289   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7290     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7291     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7292     SDValue Ops[] = {
7293       Op.getOperand(0), // Chain
7294       Op.getOperand(2), // src
7295       Op.getOperand(3), // cmp
7296       Op.getOperand(4), // rsrc
7297       Op.getOperand(5), // vindex
7298       SDValue(),        // voffset -- will be set by setBufferOffsets
7299       SDValue(),        // soffset -- will be set by setBufferOffsets
7300       SDValue(),        // offset -- will be set by setBufferOffsets
7301       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7302       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7303     };
7304     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7305 
7306     EVT VT = Op.getValueType();
7307     auto *M = cast<MemSDNode>(Op);
7308     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7309 
7310     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7311                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7312   }
7313   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7314     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7315     SDValue Ops[] = {
7316       Op.getOperand(0), // Chain
7317       Op.getOperand(2), // src
7318       Op.getOperand(3), // cmp
7319       Op.getOperand(4), // rsrc
7320       DAG.getConstant(0, DL, MVT::i32), // vindex
7321       Offsets.first,    // voffset
7322       Op.getOperand(6), // soffset
7323       Offsets.second,   // offset
7324       Op.getOperand(7), // cachepolicy
7325       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7326     };
7327     EVT VT = Op.getValueType();
7328     auto *M = cast<MemSDNode>(Op);
7329     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7330 
7331     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7332                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7333   }
7334   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7335     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7336     SDValue Ops[] = {
7337       Op.getOperand(0), // Chain
7338       Op.getOperand(2), // src
7339       Op.getOperand(3), // cmp
7340       Op.getOperand(4), // rsrc
7341       Op.getOperand(5), // vindex
7342       Offsets.first,    // voffset
7343       Op.getOperand(7), // soffset
7344       Offsets.second,   // offset
7345       Op.getOperand(8), // cachepolicy
7346       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7347     };
7348     EVT VT = Op.getValueType();
7349     auto *M = cast<MemSDNode>(Op);
7350     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7351 
7352     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7353                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7354   }
7355   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7356     MemSDNode *M = cast<MemSDNode>(Op);
7357     SDValue NodePtr = M->getOperand(2);
7358     SDValue RayExtent = M->getOperand(3);
7359     SDValue RayOrigin = M->getOperand(4);
7360     SDValue RayDir = M->getOperand(5);
7361     SDValue RayInvDir = M->getOperand(6);
7362     SDValue TDescr = M->getOperand(7);
7363 
7364     assert(NodePtr.getValueType() == MVT::i32 ||
7365            NodePtr.getValueType() == MVT::i64);
7366     assert(RayDir.getValueType() == MVT::v4f16 ||
7367            RayDir.getValueType() == MVT::v4f32);
7368 
7369     if (!Subtarget->hasGFX10_AEncoding()) {
7370       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7371       return SDValue();
7372     }
7373 
7374     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7375     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7376     const unsigned NumVAddrs = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7377     const bool UseNSA =
7378         Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize();
7379     const unsigned Opcodes[2][2][2] = {
7380         {{AMDGPU::IMAGE_BVH_INTERSECT_RAY_sa,
7381           AMDGPU::IMAGE_BVH64_INTERSECT_RAY_sa},
7382          {AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_sa,
7383           AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_sa}},
7384         {{AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa,
7385           AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa},
7386          {AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa,
7387           AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa}}};
7388     const unsigned Opcode = Opcodes[UseNSA][IsA16][Is64];
7389 
7390     SmallVector<SDValue, 16> Ops;
7391 
7392     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7393       SmallVector<SDValue, 3> Lanes;
7394       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7395       if (Lanes[0].getValueSizeInBits() == 32) {
7396         for (unsigned I = 0; I < 3; ++I)
7397           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7398       } else {
7399         if (IsAligned) {
7400           Ops.push_back(
7401             DAG.getBitcast(MVT::i32,
7402                            DAG.getBuildVector(MVT::v2f16, DL,
7403                                               { Lanes[0], Lanes[1] })));
7404           Ops.push_back(Lanes[2]);
7405         } else {
7406           SDValue Elt0 = Ops.pop_back_val();
7407           Ops.push_back(
7408             DAG.getBitcast(MVT::i32,
7409                            DAG.getBuildVector(MVT::v2f16, DL,
7410                                               { Elt0, Lanes[0] })));
7411           Ops.push_back(
7412             DAG.getBitcast(MVT::i32,
7413                            DAG.getBuildVector(MVT::v2f16, DL,
7414                                               { Lanes[1], Lanes[2] })));
7415         }
7416       }
7417     };
7418 
7419     if (Is64)
7420       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7421     else
7422       Ops.push_back(NodePtr);
7423 
7424     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7425     packLanes(RayOrigin, true);
7426     packLanes(RayDir, true);
7427     packLanes(RayInvDir, false);
7428 
7429     if (!UseNSA) {
7430       // Build a single vector containing all the operands so far prepared.
7431       if (NumVAddrs > 8) {
7432         SDValue Undef = DAG.getUNDEF(MVT::i32);
7433         Ops.append(16 - Ops.size(), Undef);
7434       }
7435       assert(Ops.size() == 8 || Ops.size() == 16);
7436       SDValue MergedOps = DAG.getBuildVector(
7437           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7438       Ops.clear();
7439       Ops.push_back(MergedOps);
7440     }
7441 
7442     Ops.push_back(TDescr);
7443     if (IsA16)
7444       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7445     Ops.push_back(M->getChain());
7446 
7447     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7448     MachineMemOperand *MemRef = M->getMemOperand();
7449     DAG.setNodeMemRefs(NewNode, {MemRef});
7450     return SDValue(NewNode, 0);
7451   }
7452   case Intrinsic::amdgcn_global_atomic_fadd:
7453     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7454       DiagnosticInfoUnsupported
7455         NoFpRet(DAG.getMachineFunction().getFunction(),
7456                 "return versions of fp atomics not supported",
7457                 DL.getDebugLoc(), DS_Error);
7458       DAG.getContext()->diagnose(NoFpRet);
7459       return SDValue();
7460     }
7461     LLVM_FALLTHROUGH;
7462   case Intrinsic::amdgcn_global_atomic_fmin:
7463   case Intrinsic::amdgcn_global_atomic_fmax:
7464   case Intrinsic::amdgcn_flat_atomic_fadd:
7465   case Intrinsic::amdgcn_flat_atomic_fmin:
7466   case Intrinsic::amdgcn_flat_atomic_fmax: {
7467     MemSDNode *M = cast<MemSDNode>(Op);
7468     SDValue Ops[] = {
7469       M->getOperand(0), // Chain
7470       M->getOperand(2), // Ptr
7471       M->getOperand(3)  // Value
7472     };
7473     unsigned Opcode = 0;
7474     switch (IntrID) {
7475     case Intrinsic::amdgcn_global_atomic_fadd:
7476     case Intrinsic::amdgcn_flat_atomic_fadd: {
7477       EVT VT = Op.getOperand(3).getValueType();
7478       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7479                            DAG.getVTList(VT, MVT::Other), Ops,
7480                            M->getMemOperand());
7481     }
7482     case Intrinsic::amdgcn_global_atomic_fmin:
7483     case Intrinsic::amdgcn_flat_atomic_fmin: {
7484       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7485       break;
7486     }
7487     case Intrinsic::amdgcn_global_atomic_fmax:
7488     case Intrinsic::amdgcn_flat_atomic_fmax: {
7489       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7490       break;
7491     }
7492     default:
7493       llvm_unreachable("unhandled atomic opcode");
7494     }
7495     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7496                                    M->getVTList(), Ops, M->getMemoryVT(),
7497                                    M->getMemOperand());
7498   }
7499   default:
7500 
7501     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7502             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7503       return lowerImage(Op, ImageDimIntr, DAG, true);
7504 
7505     return SDValue();
7506   }
7507 }
7508 
7509 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7510 // dwordx4 if on SI.
7511 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7512                                               SDVTList VTList,
7513                                               ArrayRef<SDValue> Ops, EVT MemVT,
7514                                               MachineMemOperand *MMO,
7515                                               SelectionDAG &DAG) const {
7516   EVT VT = VTList.VTs[0];
7517   EVT WidenedVT = VT;
7518   EVT WidenedMemVT = MemVT;
7519   if (!Subtarget->hasDwordx3LoadStores() &&
7520       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7521     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7522                                  WidenedVT.getVectorElementType(), 4);
7523     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7524                                     WidenedMemVT.getVectorElementType(), 4);
7525     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7526   }
7527 
7528   assert(VTList.NumVTs == 2);
7529   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7530 
7531   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7532                                        WidenedMemVT, MMO);
7533   if (WidenedVT != VT) {
7534     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7535                                DAG.getVectorIdxConstant(0, DL));
7536     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7537   }
7538   return NewOp;
7539 }
7540 
7541 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7542                                          bool ImageStore) const {
7543   EVT StoreVT = VData.getValueType();
7544 
7545   // No change for f16 and legal vector D16 types.
7546   if (!StoreVT.isVector())
7547     return VData;
7548 
7549   SDLoc DL(VData);
7550   unsigned NumElements = StoreVT.getVectorNumElements();
7551 
7552   if (Subtarget->hasUnpackedD16VMem()) {
7553     // We need to unpack the packed data to store.
7554     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7555     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7556 
7557     EVT EquivStoreVT =
7558         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7559     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7560     return DAG.UnrollVectorOp(ZExt.getNode());
7561   }
7562 
7563   // The sq block of gfx8.1 does not estimate register use correctly for d16
7564   // image store instructions. The data operand is computed as if it were not a
7565   // d16 image instruction.
7566   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7567     // Bitcast to i16
7568     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7569     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7570 
7571     // Decompose into scalars
7572     SmallVector<SDValue, 4> Elts;
7573     DAG.ExtractVectorElements(IntVData, Elts);
7574 
7575     // Group pairs of i16 into v2i16 and bitcast to i32
7576     SmallVector<SDValue, 4> PackedElts;
7577     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7578       SDValue Pair =
7579           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7580       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7581       PackedElts.push_back(IntPair);
7582     }
7583     if ((NumElements % 2) == 1) {
7584       // Handle v3i16
7585       unsigned I = Elts.size() / 2;
7586       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7587                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7588       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7589       PackedElts.push_back(IntPair);
7590     }
7591 
7592     // Pad using UNDEF
7593     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7594 
7595     // Build final vector
7596     EVT VecVT =
7597         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7598     return DAG.getBuildVector(VecVT, DL, PackedElts);
7599   }
7600 
7601   if (NumElements == 3) {
7602     EVT IntStoreVT =
7603         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7604     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7605 
7606     EVT WidenedStoreVT = EVT::getVectorVT(
7607         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7608     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7609                                          WidenedStoreVT.getStoreSizeInBits());
7610     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7611     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7612   }
7613 
7614   assert(isTypeLegal(StoreVT));
7615   return VData;
7616 }
7617 
7618 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7619                                               SelectionDAG &DAG) const {
7620   SDLoc DL(Op);
7621   SDValue Chain = Op.getOperand(0);
7622   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7623   MachineFunction &MF = DAG.getMachineFunction();
7624 
7625   switch (IntrinsicID) {
7626   case Intrinsic::amdgcn_exp_compr: {
7627     SDValue Src0 = Op.getOperand(4);
7628     SDValue Src1 = Op.getOperand(5);
7629     // Hack around illegal type on SI by directly selecting it.
7630     if (isTypeLegal(Src0.getValueType()))
7631       return SDValue();
7632 
7633     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7634     SDValue Undef = DAG.getUNDEF(MVT::f32);
7635     const SDValue Ops[] = {
7636       Op.getOperand(2), // tgt
7637       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7638       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7639       Undef, // src2
7640       Undef, // src3
7641       Op.getOperand(7), // vm
7642       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7643       Op.getOperand(3), // en
7644       Op.getOperand(0) // Chain
7645     };
7646 
7647     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7648     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7649   }
7650   case Intrinsic::amdgcn_s_barrier: {
7651     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7652       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7653       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7654       if (WGSize <= ST.getWavefrontSize())
7655         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7656                                           Op.getOperand(0)), 0);
7657     }
7658     return SDValue();
7659   };
7660   case Intrinsic::amdgcn_tbuffer_store: {
7661     SDValue VData = Op.getOperand(2);
7662     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7663     if (IsD16)
7664       VData = handleD16VData(VData, DAG);
7665     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7666     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7667     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7668     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7669     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7670     SDValue Ops[] = {
7671       Chain,
7672       VData,             // vdata
7673       Op.getOperand(3),  // rsrc
7674       Op.getOperand(4),  // vindex
7675       Op.getOperand(5),  // voffset
7676       Op.getOperand(6),  // soffset
7677       Op.getOperand(7),  // offset
7678       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7679       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7680       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7681     };
7682     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7683                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7684     MemSDNode *M = cast<MemSDNode>(Op);
7685     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7686                                    M->getMemoryVT(), M->getMemOperand());
7687   }
7688 
7689   case Intrinsic::amdgcn_struct_tbuffer_store: {
7690     SDValue VData = Op.getOperand(2);
7691     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7692     if (IsD16)
7693       VData = handleD16VData(VData, DAG);
7694     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7695     SDValue Ops[] = {
7696       Chain,
7697       VData,             // vdata
7698       Op.getOperand(3),  // rsrc
7699       Op.getOperand(4),  // vindex
7700       Offsets.first,     // voffset
7701       Op.getOperand(6),  // soffset
7702       Offsets.second,    // offset
7703       Op.getOperand(7),  // format
7704       Op.getOperand(8),  // cachepolicy, swizzled buffer
7705       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7706     };
7707     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7708                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7709     MemSDNode *M = cast<MemSDNode>(Op);
7710     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7711                                    M->getMemoryVT(), M->getMemOperand());
7712   }
7713 
7714   case Intrinsic::amdgcn_raw_tbuffer_store: {
7715     SDValue VData = Op.getOperand(2);
7716     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7717     if (IsD16)
7718       VData = handleD16VData(VData, DAG);
7719     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7720     SDValue Ops[] = {
7721       Chain,
7722       VData,             // vdata
7723       Op.getOperand(3),  // rsrc
7724       DAG.getConstant(0, DL, MVT::i32), // vindex
7725       Offsets.first,     // voffset
7726       Op.getOperand(5),  // soffset
7727       Offsets.second,    // offset
7728       Op.getOperand(6),  // format
7729       Op.getOperand(7),  // cachepolicy, swizzled buffer
7730       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7731     };
7732     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7733                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7734     MemSDNode *M = cast<MemSDNode>(Op);
7735     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7736                                    M->getMemoryVT(), M->getMemOperand());
7737   }
7738 
7739   case Intrinsic::amdgcn_buffer_store:
7740   case Intrinsic::amdgcn_buffer_store_format: {
7741     SDValue VData = Op.getOperand(2);
7742     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7743     if (IsD16)
7744       VData = handleD16VData(VData, DAG);
7745     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7746     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7747     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7748     SDValue Ops[] = {
7749       Chain,
7750       VData,
7751       Op.getOperand(3), // rsrc
7752       Op.getOperand(4), // vindex
7753       SDValue(), // voffset -- will be set by setBufferOffsets
7754       SDValue(), // soffset -- will be set by setBufferOffsets
7755       SDValue(), // offset -- will be set by setBufferOffsets
7756       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7757       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7758     };
7759     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7760 
7761     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7762                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7763     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7764     MemSDNode *M = cast<MemSDNode>(Op);
7765     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7766 
7767     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7768     EVT VDataType = VData.getValueType().getScalarType();
7769     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7770       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7771 
7772     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7773                                    M->getMemoryVT(), M->getMemOperand());
7774   }
7775 
7776   case Intrinsic::amdgcn_raw_buffer_store:
7777   case Intrinsic::amdgcn_raw_buffer_store_format: {
7778     const bool IsFormat =
7779         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7780 
7781     SDValue VData = Op.getOperand(2);
7782     EVT VDataVT = VData.getValueType();
7783     EVT EltType = VDataVT.getScalarType();
7784     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7785     if (IsD16) {
7786       VData = handleD16VData(VData, DAG);
7787       VDataVT = VData.getValueType();
7788     }
7789 
7790     if (!isTypeLegal(VDataVT)) {
7791       VData =
7792           DAG.getNode(ISD::BITCAST, DL,
7793                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7794     }
7795 
7796     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7797     SDValue Ops[] = {
7798       Chain,
7799       VData,
7800       Op.getOperand(3), // rsrc
7801       DAG.getConstant(0, DL, MVT::i32), // vindex
7802       Offsets.first,    // voffset
7803       Op.getOperand(5), // soffset
7804       Offsets.second,   // offset
7805       Op.getOperand(6), // cachepolicy, swizzled buffer
7806       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7807     };
7808     unsigned Opc =
7809         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7810     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7811     MemSDNode *M = cast<MemSDNode>(Op);
7812     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7813 
7814     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7815     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7816       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7817 
7818     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7819                                    M->getMemoryVT(), M->getMemOperand());
7820   }
7821 
7822   case Intrinsic::amdgcn_struct_buffer_store:
7823   case Intrinsic::amdgcn_struct_buffer_store_format: {
7824     const bool IsFormat =
7825         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7826 
7827     SDValue VData = Op.getOperand(2);
7828     EVT VDataVT = VData.getValueType();
7829     EVT EltType = VDataVT.getScalarType();
7830     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7831 
7832     if (IsD16) {
7833       VData = handleD16VData(VData, DAG);
7834       VDataVT = VData.getValueType();
7835     }
7836 
7837     if (!isTypeLegal(VDataVT)) {
7838       VData =
7839           DAG.getNode(ISD::BITCAST, DL,
7840                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7841     }
7842 
7843     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7844     SDValue Ops[] = {
7845       Chain,
7846       VData,
7847       Op.getOperand(3), // rsrc
7848       Op.getOperand(4), // vindex
7849       Offsets.first,    // voffset
7850       Op.getOperand(6), // soffset
7851       Offsets.second,   // offset
7852       Op.getOperand(7), // cachepolicy, swizzled buffer
7853       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7854     };
7855     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7856                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7857     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7858     MemSDNode *M = cast<MemSDNode>(Op);
7859     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7860 
7861     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7862     EVT VDataType = VData.getValueType().getScalarType();
7863     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7864       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7865 
7866     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7867                                    M->getMemoryVT(), M->getMemOperand());
7868   }
7869   case Intrinsic::amdgcn_end_cf:
7870     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7871                                       Op->getOperand(2), Chain), 0);
7872 
7873   default: {
7874     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7875             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7876       return lowerImage(Op, ImageDimIntr, DAG, true);
7877 
7878     return Op;
7879   }
7880   }
7881 }
7882 
7883 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7884 // offset (the offset that is included in bounds checking and swizzling, to be
7885 // split between the instruction's voffset and immoffset fields) and soffset
7886 // (the offset that is excluded from bounds checking and swizzling, to go in
7887 // the instruction's soffset field).  This function takes the first kind of
7888 // offset and figures out how to split it between voffset and immoffset.
7889 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7890     SDValue Offset, SelectionDAG &DAG) const {
7891   SDLoc DL(Offset);
7892   const unsigned MaxImm = 4095;
7893   SDValue N0 = Offset;
7894   ConstantSDNode *C1 = nullptr;
7895 
7896   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7897     N0 = SDValue();
7898   else if (DAG.isBaseWithConstantOffset(N0)) {
7899     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7900     N0 = N0.getOperand(0);
7901   }
7902 
7903   if (C1) {
7904     unsigned ImmOffset = C1->getZExtValue();
7905     // If the immediate value is too big for the immoffset field, put the value
7906     // and -4096 into the immoffset field so that the value that is copied/added
7907     // for the voffset field is a multiple of 4096, and it stands more chance
7908     // of being CSEd with the copy/add for another similar load/store.
7909     // However, do not do that rounding down to a multiple of 4096 if that is a
7910     // negative number, as it appears to be illegal to have a negative offset
7911     // in the vgpr, even if adding the immediate offset makes it positive.
7912     unsigned Overflow = ImmOffset & ~MaxImm;
7913     ImmOffset -= Overflow;
7914     if ((int32_t)Overflow < 0) {
7915       Overflow += ImmOffset;
7916       ImmOffset = 0;
7917     }
7918     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7919     if (Overflow) {
7920       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7921       if (!N0)
7922         N0 = OverflowVal;
7923       else {
7924         SDValue Ops[] = { N0, OverflowVal };
7925         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7926       }
7927     }
7928   }
7929   if (!N0)
7930     N0 = DAG.getConstant(0, DL, MVT::i32);
7931   if (!C1)
7932     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7933   return {N0, SDValue(C1, 0)};
7934 }
7935 
7936 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7937 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7938 // pointed to by Offsets.
7939 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7940                                         SelectionDAG &DAG, SDValue *Offsets,
7941                                         Align Alignment) const {
7942   SDLoc DL(CombinedOffset);
7943   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7944     uint32_t Imm = C->getZExtValue();
7945     uint32_t SOffset, ImmOffset;
7946     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7947                                  Alignment)) {
7948       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7949       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7950       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7951       return;
7952     }
7953   }
7954   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7955     SDValue N0 = CombinedOffset.getOperand(0);
7956     SDValue N1 = CombinedOffset.getOperand(1);
7957     uint32_t SOffset, ImmOffset;
7958     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7959     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7960                                                 Subtarget, Alignment)) {
7961       Offsets[0] = N0;
7962       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7963       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7964       return;
7965     }
7966   }
7967   Offsets[0] = CombinedOffset;
7968   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7969   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7970 }
7971 
7972 // Handle 8 bit and 16 bit buffer loads
7973 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7974                                                      EVT LoadVT, SDLoc DL,
7975                                                      ArrayRef<SDValue> Ops,
7976                                                      MemSDNode *M) const {
7977   EVT IntVT = LoadVT.changeTypeToInteger();
7978   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7979          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7980 
7981   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7982   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7983                                                Ops, IntVT,
7984                                                M->getMemOperand());
7985   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7986   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7987 
7988   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7989 }
7990 
7991 // Handle 8 bit and 16 bit buffer stores
7992 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7993                                                       EVT VDataType, SDLoc DL,
7994                                                       SDValue Ops[],
7995                                                       MemSDNode *M) const {
7996   if (VDataType == MVT::f16)
7997     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7998 
7999   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8000   Ops[1] = BufferStoreExt;
8001   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8002                                  AMDGPUISD::BUFFER_STORE_SHORT;
8003   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8004   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8005                                      M->getMemOperand());
8006 }
8007 
8008 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8009                                  ISD::LoadExtType ExtType, SDValue Op,
8010                                  const SDLoc &SL, EVT VT) {
8011   if (VT.bitsLT(Op.getValueType()))
8012     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8013 
8014   switch (ExtType) {
8015   case ISD::SEXTLOAD:
8016     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8017   case ISD::ZEXTLOAD:
8018     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8019   case ISD::EXTLOAD:
8020     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8021   case ISD::NON_EXTLOAD:
8022     return Op;
8023   }
8024 
8025   llvm_unreachable("invalid ext type");
8026 }
8027 
8028 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8029   SelectionDAG &DAG = DCI.DAG;
8030   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8031     return SDValue();
8032 
8033   // FIXME: Constant loads should all be marked invariant.
8034   unsigned AS = Ld->getAddressSpace();
8035   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8036       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8037       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8038     return SDValue();
8039 
8040   // Don't do this early, since it may interfere with adjacent load merging for
8041   // illegal types. We can avoid losing alignment information for exotic types
8042   // pre-legalize.
8043   EVT MemVT = Ld->getMemoryVT();
8044   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8045       MemVT.getSizeInBits() >= 32)
8046     return SDValue();
8047 
8048   SDLoc SL(Ld);
8049 
8050   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8051          "unexpected vector extload");
8052 
8053   // TODO: Drop only high part of range.
8054   SDValue Ptr = Ld->getBasePtr();
8055   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8056                                 MVT::i32, SL, Ld->getChain(), Ptr,
8057                                 Ld->getOffset(),
8058                                 Ld->getPointerInfo(), MVT::i32,
8059                                 Ld->getAlignment(),
8060                                 Ld->getMemOperand()->getFlags(),
8061                                 Ld->getAAInfo(),
8062                                 nullptr); // Drop ranges
8063 
8064   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8065   if (MemVT.isFloatingPoint()) {
8066     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8067            "unexpected fp extload");
8068     TruncVT = MemVT.changeTypeToInteger();
8069   }
8070 
8071   SDValue Cvt = NewLoad;
8072   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8073     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8074                       DAG.getValueType(TruncVT));
8075   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8076              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8077     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8078   } else {
8079     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8080   }
8081 
8082   EVT VT = Ld->getValueType(0);
8083   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8084 
8085   DCI.AddToWorklist(Cvt.getNode());
8086 
8087   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8088   // the appropriate extension from the 32-bit load.
8089   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8090   DCI.AddToWorklist(Cvt.getNode());
8091 
8092   // Handle conversion back to floating point if necessary.
8093   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8094 
8095   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8096 }
8097 
8098 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8099   SDLoc DL(Op);
8100   LoadSDNode *Load = cast<LoadSDNode>(Op);
8101   ISD::LoadExtType ExtType = Load->getExtensionType();
8102   EVT MemVT = Load->getMemoryVT();
8103 
8104   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8105     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8106       return SDValue();
8107 
8108     // FIXME: Copied from PPC
8109     // First, load into 32 bits, then truncate to 1 bit.
8110 
8111     SDValue Chain = Load->getChain();
8112     SDValue BasePtr = Load->getBasePtr();
8113     MachineMemOperand *MMO = Load->getMemOperand();
8114 
8115     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8116 
8117     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8118                                    BasePtr, RealMemVT, MMO);
8119 
8120     if (!MemVT.isVector()) {
8121       SDValue Ops[] = {
8122         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8123         NewLD.getValue(1)
8124       };
8125 
8126       return DAG.getMergeValues(Ops, DL);
8127     }
8128 
8129     SmallVector<SDValue, 3> Elts;
8130     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8131       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8132                                 DAG.getConstant(I, DL, MVT::i32));
8133 
8134       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8135     }
8136 
8137     SDValue Ops[] = {
8138       DAG.getBuildVector(MemVT, DL, Elts),
8139       NewLD.getValue(1)
8140     };
8141 
8142     return DAG.getMergeValues(Ops, DL);
8143   }
8144 
8145   if (!MemVT.isVector())
8146     return SDValue();
8147 
8148   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8149          "Custom lowering for non-i32 vectors hasn't been implemented.");
8150 
8151   unsigned Alignment = Load->getAlignment();
8152   unsigned AS = Load->getAddressSpace();
8153   if (Subtarget->hasLDSMisalignedBug() &&
8154       AS == AMDGPUAS::FLAT_ADDRESS &&
8155       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8156     return SplitVectorLoad(Op, DAG);
8157   }
8158 
8159   MachineFunction &MF = DAG.getMachineFunction();
8160   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8161   // If there is a possibilty that flat instruction access scratch memory
8162   // then we need to use the same legalization rules we use for private.
8163   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8164       !Subtarget->hasMultiDwordFlatScratchAddressing())
8165     AS = MFI->hasFlatScratchInit() ?
8166          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8167 
8168   unsigned NumElements = MemVT.getVectorNumElements();
8169 
8170   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8171       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8172     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8173       if (MemVT.isPow2VectorType())
8174         return SDValue();
8175       return WidenOrSplitVectorLoad(Op, DAG);
8176     }
8177     // Non-uniform loads will be selected to MUBUF instructions, so they
8178     // have the same legalization requirements as global and private
8179     // loads.
8180     //
8181   }
8182 
8183   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8184       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8185       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8186     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8187         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8188         Alignment >= 4 && NumElements < 32) {
8189       if (MemVT.isPow2VectorType())
8190         return SDValue();
8191       return WidenOrSplitVectorLoad(Op, DAG);
8192     }
8193     // Non-uniform loads will be selected to MUBUF instructions, so they
8194     // have the same legalization requirements as global and private
8195     // loads.
8196     //
8197   }
8198   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8199       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8200       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8201       AS == AMDGPUAS::FLAT_ADDRESS) {
8202     if (NumElements > 4)
8203       return SplitVectorLoad(Op, DAG);
8204     // v3 loads not supported on SI.
8205     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8206       return WidenOrSplitVectorLoad(Op, DAG);
8207 
8208     // v3 and v4 loads are supported for private and global memory.
8209     return SDValue();
8210   }
8211   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8212     // Depending on the setting of the private_element_size field in the
8213     // resource descriptor, we can only make private accesses up to a certain
8214     // size.
8215     switch (Subtarget->getMaxPrivateElementSize()) {
8216     case 4: {
8217       SDValue Ops[2];
8218       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8219       return DAG.getMergeValues(Ops, DL);
8220     }
8221     case 8:
8222       if (NumElements > 2)
8223         return SplitVectorLoad(Op, DAG);
8224       return SDValue();
8225     case 16:
8226       // Same as global/flat
8227       if (NumElements > 4)
8228         return SplitVectorLoad(Op, DAG);
8229       // v3 loads not supported on SI.
8230       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8231         return WidenOrSplitVectorLoad(Op, DAG);
8232 
8233       return SDValue();
8234     default:
8235       llvm_unreachable("unsupported private_element_size");
8236     }
8237   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8238     // Use ds_read_b128 or ds_read_b96 when possible.
8239     if (Subtarget->hasDS96AndDS128() &&
8240         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8241          MemVT.getStoreSize() == 12) &&
8242         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8243                                            Load->getAlign()))
8244       return SDValue();
8245 
8246     if (NumElements > 2)
8247       return SplitVectorLoad(Op, DAG);
8248 
8249     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8250     // address is negative, then the instruction is incorrectly treated as
8251     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8252     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8253     // load later in the SILoadStoreOptimizer.
8254     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8255         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8256         Load->getAlignment() < 8) {
8257       return SplitVectorLoad(Op, DAG);
8258     }
8259   }
8260 
8261   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8262                                       MemVT, *Load->getMemOperand())) {
8263     SDValue Ops[2];
8264     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8265     return DAG.getMergeValues(Ops, DL);
8266   }
8267 
8268   return SDValue();
8269 }
8270 
8271 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8272   EVT VT = Op.getValueType();
8273   assert(VT.getSizeInBits() == 64);
8274 
8275   SDLoc DL(Op);
8276   SDValue Cond = Op.getOperand(0);
8277 
8278   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8279   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8280 
8281   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8282   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8283 
8284   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8285   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8286 
8287   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8288 
8289   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8290   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8291 
8292   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8293 
8294   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8295   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8296 }
8297 
8298 // Catch division cases where we can use shortcuts with rcp and rsq
8299 // instructions.
8300 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8301                                               SelectionDAG &DAG) const {
8302   SDLoc SL(Op);
8303   SDValue LHS = Op.getOperand(0);
8304   SDValue RHS = Op.getOperand(1);
8305   EVT VT = Op.getValueType();
8306   const SDNodeFlags Flags = Op->getFlags();
8307 
8308   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8309 
8310   // Without !fpmath accuracy information, we can't do more because we don't
8311   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8312   if (!AllowInaccurateRcp)
8313     return SDValue();
8314 
8315   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8316     if (CLHS->isExactlyValue(1.0)) {
8317       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8318       // the CI documentation has a worst case error of 1 ulp.
8319       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8320       // use it as long as we aren't trying to use denormals.
8321       //
8322       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8323 
8324       // 1.0 / sqrt(x) -> rsq(x)
8325 
8326       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8327       // error seems really high at 2^29 ULP.
8328       if (RHS.getOpcode() == ISD::FSQRT)
8329         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8330 
8331       // 1.0 / x -> rcp(x)
8332       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8333     }
8334 
8335     // Same as for 1.0, but expand the sign out of the constant.
8336     if (CLHS->isExactlyValue(-1.0)) {
8337       // -1.0 / x -> rcp (fneg x)
8338       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8339       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8340     }
8341   }
8342 
8343   // Turn into multiply by the reciprocal.
8344   // x / y -> x * (1.0 / y)
8345   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8346   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8347 }
8348 
8349 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8350                                                 SelectionDAG &DAG) const {
8351   SDLoc SL(Op);
8352   SDValue X = Op.getOperand(0);
8353   SDValue Y = Op.getOperand(1);
8354   EVT VT = Op.getValueType();
8355   const SDNodeFlags Flags = Op->getFlags();
8356 
8357   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8358                             DAG.getTarget().Options.UnsafeFPMath;
8359   if (!AllowInaccurateDiv)
8360     return SDValue();
8361 
8362   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8363   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8364 
8365   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8366   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8367 
8368   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8369   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8370   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8371   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8372   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8373   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8374 }
8375 
8376 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8377                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8378                           SDNodeFlags Flags) {
8379   if (GlueChain->getNumValues() <= 1) {
8380     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8381   }
8382 
8383   assert(GlueChain->getNumValues() == 3);
8384 
8385   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8386   switch (Opcode) {
8387   default: llvm_unreachable("no chain equivalent for opcode");
8388   case ISD::FMUL:
8389     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8390     break;
8391   }
8392 
8393   return DAG.getNode(Opcode, SL, VTList,
8394                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8395                      Flags);
8396 }
8397 
8398 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8399                            EVT VT, SDValue A, SDValue B, SDValue C,
8400                            SDValue GlueChain, SDNodeFlags Flags) {
8401   if (GlueChain->getNumValues() <= 1) {
8402     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8403   }
8404 
8405   assert(GlueChain->getNumValues() == 3);
8406 
8407   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8408   switch (Opcode) {
8409   default: llvm_unreachable("no chain equivalent for opcode");
8410   case ISD::FMA:
8411     Opcode = AMDGPUISD::FMA_W_CHAIN;
8412     break;
8413   }
8414 
8415   return DAG.getNode(Opcode, SL, VTList,
8416                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8417                      Flags);
8418 }
8419 
8420 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8421   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8422     return FastLowered;
8423 
8424   SDLoc SL(Op);
8425   SDValue Src0 = Op.getOperand(0);
8426   SDValue Src1 = Op.getOperand(1);
8427 
8428   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8429   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8430 
8431   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8432   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8433 
8434   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8435   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8436 
8437   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8438 }
8439 
8440 // Faster 2.5 ULP division that does not support denormals.
8441 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8442   SDLoc SL(Op);
8443   SDValue LHS = Op.getOperand(1);
8444   SDValue RHS = Op.getOperand(2);
8445 
8446   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8447 
8448   const APFloat K0Val(BitsToFloat(0x6f800000));
8449   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8450 
8451   const APFloat K1Val(BitsToFloat(0x2f800000));
8452   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8453 
8454   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8455 
8456   EVT SetCCVT =
8457     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8458 
8459   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8460 
8461   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8462 
8463   // TODO: Should this propagate fast-math-flags?
8464   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8465 
8466   // rcp does not support denormals.
8467   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8468 
8469   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8470 
8471   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8472 }
8473 
8474 // Returns immediate value for setting the F32 denorm mode when using the
8475 // S_DENORM_MODE instruction.
8476 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8477                                     const SDLoc &SL, const GCNSubtarget *ST) {
8478   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8479   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8480                                 ? FP_DENORM_FLUSH_NONE
8481                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8482 
8483   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8484   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8485 }
8486 
8487 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8488   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8489     return FastLowered;
8490 
8491   // The selection matcher assumes anything with a chain selecting to a
8492   // mayRaiseFPException machine instruction. Since we're introducing a chain
8493   // here, we need to explicitly report nofpexcept for the regular fdiv
8494   // lowering.
8495   SDNodeFlags Flags = Op->getFlags();
8496   Flags.setNoFPExcept(true);
8497 
8498   SDLoc SL(Op);
8499   SDValue LHS = Op.getOperand(0);
8500   SDValue RHS = Op.getOperand(1);
8501 
8502   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8503 
8504   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8505 
8506   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8507                                           {RHS, RHS, LHS}, Flags);
8508   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8509                                         {LHS, RHS, LHS}, Flags);
8510 
8511   // Denominator is scaled to not be denormal, so using rcp is ok.
8512   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8513                                   DenominatorScaled, Flags);
8514   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8515                                      DenominatorScaled, Flags);
8516 
8517   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8518                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8519                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8520   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8521 
8522   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8523 
8524   if (!HasFP32Denormals) {
8525     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8526     // lowering. The chain dependence is insufficient, and we need glue. We do
8527     // not need the glue variants in a strictfp function.
8528 
8529     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8530 
8531     SDNode *EnableDenorm;
8532     if (Subtarget->hasDenormModeInst()) {
8533       const SDValue EnableDenormValue =
8534           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8535 
8536       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8537                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8538     } else {
8539       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8540                                                         SL, MVT::i32);
8541       EnableDenorm =
8542           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8543                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8544     }
8545 
8546     SDValue Ops[3] = {
8547       NegDivScale0,
8548       SDValue(EnableDenorm, 0),
8549       SDValue(EnableDenorm, 1)
8550     };
8551 
8552     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8553   }
8554 
8555   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8556                              ApproxRcp, One, NegDivScale0, Flags);
8557 
8558   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8559                              ApproxRcp, Fma0, Flags);
8560 
8561   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8562                            Fma1, Fma1, Flags);
8563 
8564   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8565                              NumeratorScaled, Mul, Flags);
8566 
8567   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8568                              Fma2, Fma1, Mul, Fma2, Flags);
8569 
8570   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8571                              NumeratorScaled, Fma3, Flags);
8572 
8573   if (!HasFP32Denormals) {
8574     SDNode *DisableDenorm;
8575     if (Subtarget->hasDenormModeInst()) {
8576       const SDValue DisableDenormValue =
8577           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8578 
8579       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8580                                   Fma4.getValue(1), DisableDenormValue,
8581                                   Fma4.getValue(2)).getNode();
8582     } else {
8583       const SDValue DisableDenormValue =
8584           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8585 
8586       DisableDenorm = DAG.getMachineNode(
8587           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8588           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8589     }
8590 
8591     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8592                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8593     DAG.setRoot(OutputChain);
8594   }
8595 
8596   SDValue Scale = NumeratorScaled.getValue(1);
8597   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8598                              {Fma4, Fma1, Fma3, Scale}, Flags);
8599 
8600   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8601 }
8602 
8603 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8604   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8605     return FastLowered;
8606 
8607   SDLoc SL(Op);
8608   SDValue X = Op.getOperand(0);
8609   SDValue Y = Op.getOperand(1);
8610 
8611   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8612 
8613   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8614 
8615   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8616 
8617   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8618 
8619   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8620 
8621   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8622 
8623   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8624 
8625   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8626 
8627   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8628 
8629   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8630   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8631 
8632   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8633                              NegDivScale0, Mul, DivScale1);
8634 
8635   SDValue Scale;
8636 
8637   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8638     // Workaround a hardware bug on SI where the condition output from div_scale
8639     // is not usable.
8640 
8641     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8642 
8643     // Figure out if the scale to use for div_fmas.
8644     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8645     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8646     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8647     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8648 
8649     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8650     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8651 
8652     SDValue Scale0Hi
8653       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8654     SDValue Scale1Hi
8655       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8656 
8657     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8658     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8659     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8660   } else {
8661     Scale = DivScale1.getValue(1);
8662   }
8663 
8664   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8665                              Fma4, Fma3, Mul, Scale);
8666 
8667   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8668 }
8669 
8670 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8671   EVT VT = Op.getValueType();
8672 
8673   if (VT == MVT::f32)
8674     return LowerFDIV32(Op, DAG);
8675 
8676   if (VT == MVT::f64)
8677     return LowerFDIV64(Op, DAG);
8678 
8679   if (VT == MVT::f16)
8680     return LowerFDIV16(Op, DAG);
8681 
8682   llvm_unreachable("Unexpected type for fdiv");
8683 }
8684 
8685 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8686   SDLoc DL(Op);
8687   StoreSDNode *Store = cast<StoreSDNode>(Op);
8688   EVT VT = Store->getMemoryVT();
8689 
8690   if (VT == MVT::i1) {
8691     return DAG.getTruncStore(Store->getChain(), DL,
8692        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8693        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8694   }
8695 
8696   assert(VT.isVector() &&
8697          Store->getValue().getValueType().getScalarType() == MVT::i32);
8698 
8699   unsigned AS = Store->getAddressSpace();
8700   if (Subtarget->hasLDSMisalignedBug() &&
8701       AS == AMDGPUAS::FLAT_ADDRESS &&
8702       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8703     return SplitVectorStore(Op, DAG);
8704   }
8705 
8706   MachineFunction &MF = DAG.getMachineFunction();
8707   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8708   // If there is a possibilty that flat instruction access scratch memory
8709   // then we need to use the same legalization rules we use for private.
8710   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8711       !Subtarget->hasMultiDwordFlatScratchAddressing())
8712     AS = MFI->hasFlatScratchInit() ?
8713          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8714 
8715   unsigned NumElements = VT.getVectorNumElements();
8716   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8717       AS == AMDGPUAS::FLAT_ADDRESS) {
8718     if (NumElements > 4)
8719       return SplitVectorStore(Op, DAG);
8720     // v3 stores not supported on SI.
8721     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8722       return SplitVectorStore(Op, DAG);
8723 
8724     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8725                                         VT, *Store->getMemOperand()))
8726       return expandUnalignedStore(Store, DAG);
8727 
8728     return SDValue();
8729   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8730     switch (Subtarget->getMaxPrivateElementSize()) {
8731     case 4:
8732       return scalarizeVectorStore(Store, DAG);
8733     case 8:
8734       if (NumElements > 2)
8735         return SplitVectorStore(Op, DAG);
8736       return SDValue();
8737     case 16:
8738       if (NumElements > 4 ||
8739           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8740         return SplitVectorStore(Op, DAG);
8741       return SDValue();
8742     default:
8743       llvm_unreachable("unsupported private_element_size");
8744     }
8745   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8746     // Use ds_write_b128 or ds_write_b96 when possible.
8747     if (Subtarget->hasDS96AndDS128() &&
8748         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8749          (VT.getStoreSize() == 12)) &&
8750         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8751                                            Store->getAlign()))
8752       return SDValue();
8753 
8754     if (NumElements > 2)
8755       return SplitVectorStore(Op, DAG);
8756 
8757     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8758     // address is negative, then the instruction is incorrectly treated as
8759     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8760     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8761     // store later in the SILoadStoreOptimizer.
8762     if (!Subtarget->hasUsableDSOffset() &&
8763         NumElements == 2 && VT.getStoreSize() == 8 &&
8764         Store->getAlignment() < 8) {
8765       return SplitVectorStore(Op, DAG);
8766     }
8767 
8768     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8769                                         VT, *Store->getMemOperand())) {
8770       if (VT.isVector())
8771         return SplitVectorStore(Op, DAG);
8772       return expandUnalignedStore(Store, DAG);
8773     }
8774 
8775     return SDValue();
8776   } else {
8777     llvm_unreachable("unhandled address space");
8778   }
8779 }
8780 
8781 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8782   SDLoc DL(Op);
8783   EVT VT = Op.getValueType();
8784   SDValue Arg = Op.getOperand(0);
8785   SDValue TrigVal;
8786 
8787   // Propagate fast-math flags so that the multiply we introduce can be folded
8788   // if Arg is already the result of a multiply by constant.
8789   auto Flags = Op->getFlags();
8790 
8791   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8792 
8793   if (Subtarget->hasTrigReducedRange()) {
8794     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8795     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8796   } else {
8797     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8798   }
8799 
8800   switch (Op.getOpcode()) {
8801   case ISD::FCOS:
8802     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8803   case ISD::FSIN:
8804     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8805   default:
8806     llvm_unreachable("Wrong trig opcode");
8807   }
8808 }
8809 
8810 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8811   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8812   assert(AtomicNode->isCompareAndSwap());
8813   unsigned AS = AtomicNode->getAddressSpace();
8814 
8815   // No custom lowering required for local address space
8816   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8817     return Op;
8818 
8819   // Non-local address space requires custom lowering for atomic compare
8820   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8821   SDLoc DL(Op);
8822   SDValue ChainIn = Op.getOperand(0);
8823   SDValue Addr = Op.getOperand(1);
8824   SDValue Old = Op.getOperand(2);
8825   SDValue New = Op.getOperand(3);
8826   EVT VT = Op.getValueType();
8827   MVT SimpleVT = VT.getSimpleVT();
8828   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8829 
8830   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8831   SDValue Ops[] = { ChainIn, Addr, NewOld };
8832 
8833   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8834                                  Ops, VT, AtomicNode->getMemOperand());
8835 }
8836 
8837 //===----------------------------------------------------------------------===//
8838 // Custom DAG optimizations
8839 //===----------------------------------------------------------------------===//
8840 
8841 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8842                                                      DAGCombinerInfo &DCI) const {
8843   EVT VT = N->getValueType(0);
8844   EVT ScalarVT = VT.getScalarType();
8845   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8846     return SDValue();
8847 
8848   SelectionDAG &DAG = DCI.DAG;
8849   SDLoc DL(N);
8850 
8851   SDValue Src = N->getOperand(0);
8852   EVT SrcVT = Src.getValueType();
8853 
8854   // TODO: We could try to match extracting the higher bytes, which would be
8855   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8856   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8857   // about in practice.
8858   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8859     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8860       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8861       DCI.AddToWorklist(Cvt.getNode());
8862 
8863       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8864       if (ScalarVT != MVT::f32) {
8865         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8866                           DAG.getTargetConstant(0, DL, MVT::i32));
8867       }
8868       return Cvt;
8869     }
8870   }
8871 
8872   return SDValue();
8873 }
8874 
8875 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8876 
8877 // This is a variant of
8878 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8879 //
8880 // The normal DAG combiner will do this, but only if the add has one use since
8881 // that would increase the number of instructions.
8882 //
8883 // This prevents us from seeing a constant offset that can be folded into a
8884 // memory instruction's addressing mode. If we know the resulting add offset of
8885 // a pointer can be folded into an addressing offset, we can replace the pointer
8886 // operand with the add of new constant offset. This eliminates one of the uses,
8887 // and may allow the remaining use to also be simplified.
8888 //
8889 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8890                                                unsigned AddrSpace,
8891                                                EVT MemVT,
8892                                                DAGCombinerInfo &DCI) const {
8893   SDValue N0 = N->getOperand(0);
8894   SDValue N1 = N->getOperand(1);
8895 
8896   // We only do this to handle cases where it's profitable when there are
8897   // multiple uses of the add, so defer to the standard combine.
8898   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8899       N0->hasOneUse())
8900     return SDValue();
8901 
8902   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8903   if (!CN1)
8904     return SDValue();
8905 
8906   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8907   if (!CAdd)
8908     return SDValue();
8909 
8910   // If the resulting offset is too large, we can't fold it into the addressing
8911   // mode offset.
8912   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8913   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8914 
8915   AddrMode AM;
8916   AM.HasBaseReg = true;
8917   AM.BaseOffs = Offset.getSExtValue();
8918   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8919     return SDValue();
8920 
8921   SelectionDAG &DAG = DCI.DAG;
8922   SDLoc SL(N);
8923   EVT VT = N->getValueType(0);
8924 
8925   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8926   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8927 
8928   SDNodeFlags Flags;
8929   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8930                           (N0.getOpcode() == ISD::OR ||
8931                            N0->getFlags().hasNoUnsignedWrap()));
8932 
8933   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8934 }
8935 
8936 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8937 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8938 /// specific intrinsic, but they all place the pointer operand first.
8939 static unsigned getBasePtrIndex(const MemSDNode *N) {
8940   switch (N->getOpcode()) {
8941   case ISD::STORE:
8942   case ISD::INTRINSIC_W_CHAIN:
8943   case ISD::INTRINSIC_VOID:
8944     return 2;
8945   default:
8946     return 1;
8947   }
8948 }
8949 
8950 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8951                                                   DAGCombinerInfo &DCI) const {
8952   SelectionDAG &DAG = DCI.DAG;
8953   SDLoc SL(N);
8954 
8955   unsigned PtrIdx = getBasePtrIndex(N);
8956   SDValue Ptr = N->getOperand(PtrIdx);
8957 
8958   // TODO: We could also do this for multiplies.
8959   if (Ptr.getOpcode() == ISD::SHL) {
8960     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8961                                           N->getMemoryVT(), DCI);
8962     if (NewPtr) {
8963       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8964 
8965       NewOps[PtrIdx] = NewPtr;
8966       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8967     }
8968   }
8969 
8970   return SDValue();
8971 }
8972 
8973 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8974   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8975          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8976          (Opc == ISD::XOR && Val == 0);
8977 }
8978 
8979 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8980 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8981 // integer combine opportunities since most 64-bit operations are decomposed
8982 // this way.  TODO: We won't want this for SALU especially if it is an inline
8983 // immediate.
8984 SDValue SITargetLowering::splitBinaryBitConstantOp(
8985   DAGCombinerInfo &DCI,
8986   const SDLoc &SL,
8987   unsigned Opc, SDValue LHS,
8988   const ConstantSDNode *CRHS) const {
8989   uint64_t Val = CRHS->getZExtValue();
8990   uint32_t ValLo = Lo_32(Val);
8991   uint32_t ValHi = Hi_32(Val);
8992   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8993 
8994     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8995          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8996         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8997     // If we need to materialize a 64-bit immediate, it will be split up later
8998     // anyway. Avoid creating the harder to understand 64-bit immediate
8999     // materialization.
9000     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9001   }
9002 
9003   return SDValue();
9004 }
9005 
9006 // Returns true if argument is a boolean value which is not serialized into
9007 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9008 static bool isBoolSGPR(SDValue V) {
9009   if (V.getValueType() != MVT::i1)
9010     return false;
9011   switch (V.getOpcode()) {
9012   default:
9013     break;
9014   case ISD::SETCC:
9015   case AMDGPUISD::FP_CLASS:
9016     return true;
9017   case ISD::AND:
9018   case ISD::OR:
9019   case ISD::XOR:
9020     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9021   }
9022   return false;
9023 }
9024 
9025 // If a constant has all zeroes or all ones within each byte return it.
9026 // Otherwise return 0.
9027 static uint32_t getConstantPermuteMask(uint32_t C) {
9028   // 0xff for any zero byte in the mask
9029   uint32_t ZeroByteMask = 0;
9030   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9031   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9032   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9033   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9034   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9035   if ((NonZeroByteMask & C) != NonZeroByteMask)
9036     return 0; // Partial bytes selected.
9037   return C;
9038 }
9039 
9040 // Check if a node selects whole bytes from its operand 0 starting at a byte
9041 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9042 // or -1 if not succeeded.
9043 // Note byte select encoding:
9044 // value 0-3 selects corresponding source byte;
9045 // value 0xc selects zero;
9046 // value 0xff selects 0xff.
9047 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9048   assert(V.getValueSizeInBits() == 32);
9049 
9050   if (V.getNumOperands() != 2)
9051     return ~0;
9052 
9053   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9054   if (!N1)
9055     return ~0;
9056 
9057   uint32_t C = N1->getZExtValue();
9058 
9059   switch (V.getOpcode()) {
9060   default:
9061     break;
9062   case ISD::AND:
9063     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9064       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9065     }
9066     break;
9067 
9068   case ISD::OR:
9069     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9070       return (0x03020100 & ~ConstMask) | ConstMask;
9071     }
9072     break;
9073 
9074   case ISD::SHL:
9075     if (C % 8)
9076       return ~0;
9077 
9078     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9079 
9080   case ISD::SRL:
9081     if (C % 8)
9082       return ~0;
9083 
9084     return uint32_t(0x0c0c0c0c03020100ull >> C);
9085   }
9086 
9087   return ~0;
9088 }
9089 
9090 SDValue SITargetLowering::performAndCombine(SDNode *N,
9091                                             DAGCombinerInfo &DCI) const {
9092   if (DCI.isBeforeLegalize())
9093     return SDValue();
9094 
9095   SelectionDAG &DAG = DCI.DAG;
9096   EVT VT = N->getValueType(0);
9097   SDValue LHS = N->getOperand(0);
9098   SDValue RHS = N->getOperand(1);
9099 
9100 
9101   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9102   if (VT == MVT::i64 && CRHS) {
9103     if (SDValue Split
9104         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9105       return Split;
9106   }
9107 
9108   if (CRHS && VT == MVT::i32) {
9109     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9110     // nb = number of trailing zeroes in mask
9111     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9112     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9113     uint64_t Mask = CRHS->getZExtValue();
9114     unsigned Bits = countPopulation(Mask);
9115     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9116         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9117       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9118         unsigned Shift = CShift->getZExtValue();
9119         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9120         unsigned Offset = NB + Shift;
9121         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9122           SDLoc SL(N);
9123           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9124                                     LHS->getOperand(0),
9125                                     DAG.getConstant(Offset, SL, MVT::i32),
9126                                     DAG.getConstant(Bits, SL, MVT::i32));
9127           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9128           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9129                                     DAG.getValueType(NarrowVT));
9130           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9131                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9132           return Shl;
9133         }
9134       }
9135     }
9136 
9137     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9138     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9139         isa<ConstantSDNode>(LHS.getOperand(2))) {
9140       uint32_t Sel = getConstantPermuteMask(Mask);
9141       if (!Sel)
9142         return SDValue();
9143 
9144       // Select 0xc for all zero bytes
9145       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9146       SDLoc DL(N);
9147       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9148                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9149     }
9150   }
9151 
9152   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9153   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9154   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9155     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9156     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9157 
9158     SDValue X = LHS.getOperand(0);
9159     SDValue Y = RHS.getOperand(0);
9160     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9161       return SDValue();
9162 
9163     if (LCC == ISD::SETO) {
9164       if (X != LHS.getOperand(1))
9165         return SDValue();
9166 
9167       if (RCC == ISD::SETUNE) {
9168         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9169         if (!C1 || !C1->isInfinity() || C1->isNegative())
9170           return SDValue();
9171 
9172         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9173                               SIInstrFlags::N_SUBNORMAL |
9174                               SIInstrFlags::N_ZERO |
9175                               SIInstrFlags::P_ZERO |
9176                               SIInstrFlags::P_SUBNORMAL |
9177                               SIInstrFlags::P_NORMAL;
9178 
9179         static_assert(((~(SIInstrFlags::S_NAN |
9180                           SIInstrFlags::Q_NAN |
9181                           SIInstrFlags::N_INFINITY |
9182                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9183                       "mask not equal");
9184 
9185         SDLoc DL(N);
9186         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9187                            X, DAG.getConstant(Mask, DL, MVT::i32));
9188       }
9189     }
9190   }
9191 
9192   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9193     std::swap(LHS, RHS);
9194 
9195   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9196       RHS.hasOneUse()) {
9197     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9198     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9199     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9200     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9201     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9202         (RHS.getOperand(0) == LHS.getOperand(0) &&
9203          LHS.getOperand(0) == LHS.getOperand(1))) {
9204       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9205       unsigned NewMask = LCC == ISD::SETO ?
9206         Mask->getZExtValue() & ~OrdMask :
9207         Mask->getZExtValue() & OrdMask;
9208 
9209       SDLoc DL(N);
9210       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9211                          DAG.getConstant(NewMask, DL, MVT::i32));
9212     }
9213   }
9214 
9215   if (VT == MVT::i32 &&
9216       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9217     // and x, (sext cc from i1) => select cc, x, 0
9218     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9219       std::swap(LHS, RHS);
9220     if (isBoolSGPR(RHS.getOperand(0)))
9221       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9222                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9223   }
9224 
9225   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9226   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9227   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9228       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9229     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9230     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9231     if (LHSMask != ~0u && RHSMask != ~0u) {
9232       // Canonicalize the expression in an attempt to have fewer unique masks
9233       // and therefore fewer registers used to hold the masks.
9234       if (LHSMask > RHSMask) {
9235         std::swap(LHSMask, RHSMask);
9236         std::swap(LHS, RHS);
9237       }
9238 
9239       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9240       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9241       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9242       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9243 
9244       // Check of we need to combine values from two sources within a byte.
9245       if (!(LHSUsedLanes & RHSUsedLanes) &&
9246           // If we select high and lower word keep it for SDWA.
9247           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9248           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9249         // Each byte in each mask is either selector mask 0-3, or has higher
9250         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9251         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9252         // mask which is not 0xff wins. By anding both masks we have a correct
9253         // result except that 0x0c shall be corrected to give 0x0c only.
9254         uint32_t Mask = LHSMask & RHSMask;
9255         for (unsigned I = 0; I < 32; I += 8) {
9256           uint32_t ByteSel = 0xff << I;
9257           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9258             Mask &= (0x0c << I) & 0xffffffff;
9259         }
9260 
9261         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9262         // or 0x0c.
9263         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9264         SDLoc DL(N);
9265 
9266         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9267                            LHS.getOperand(0), RHS.getOperand(0),
9268                            DAG.getConstant(Sel, DL, MVT::i32));
9269       }
9270     }
9271   }
9272 
9273   return SDValue();
9274 }
9275 
9276 SDValue SITargetLowering::performOrCombine(SDNode *N,
9277                                            DAGCombinerInfo &DCI) const {
9278   SelectionDAG &DAG = DCI.DAG;
9279   SDValue LHS = N->getOperand(0);
9280   SDValue RHS = N->getOperand(1);
9281 
9282   EVT VT = N->getValueType(0);
9283   if (VT == MVT::i1) {
9284     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9285     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9286         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9287       SDValue Src = LHS.getOperand(0);
9288       if (Src != RHS.getOperand(0))
9289         return SDValue();
9290 
9291       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9292       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9293       if (!CLHS || !CRHS)
9294         return SDValue();
9295 
9296       // Only 10 bits are used.
9297       static const uint32_t MaxMask = 0x3ff;
9298 
9299       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9300       SDLoc DL(N);
9301       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9302                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9303     }
9304 
9305     return SDValue();
9306   }
9307 
9308   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9309   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9310       LHS.getOpcode() == AMDGPUISD::PERM &&
9311       isa<ConstantSDNode>(LHS.getOperand(2))) {
9312     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9313     if (!Sel)
9314       return SDValue();
9315 
9316     Sel |= LHS.getConstantOperandVal(2);
9317     SDLoc DL(N);
9318     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9319                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9320   }
9321 
9322   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9323   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9324   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9325       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9326     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9327     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9328     if (LHSMask != ~0u && RHSMask != ~0u) {
9329       // Canonicalize the expression in an attempt to have fewer unique masks
9330       // and therefore fewer registers used to hold the masks.
9331       if (LHSMask > RHSMask) {
9332         std::swap(LHSMask, RHSMask);
9333         std::swap(LHS, RHS);
9334       }
9335 
9336       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9337       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9338       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9339       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9340 
9341       // Check of we need to combine values from two sources within a byte.
9342       if (!(LHSUsedLanes & RHSUsedLanes) &&
9343           // If we select high and lower word keep it for SDWA.
9344           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9345           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9346         // Kill zero bytes selected by other mask. Zero value is 0xc.
9347         LHSMask &= ~RHSUsedLanes;
9348         RHSMask &= ~LHSUsedLanes;
9349         // Add 4 to each active LHS lane
9350         LHSMask |= LHSUsedLanes & 0x04040404;
9351         // Combine masks
9352         uint32_t Sel = LHSMask | RHSMask;
9353         SDLoc DL(N);
9354 
9355         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9356                            LHS.getOperand(0), RHS.getOperand(0),
9357                            DAG.getConstant(Sel, DL, MVT::i32));
9358       }
9359     }
9360   }
9361 
9362   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9363     return SDValue();
9364 
9365   // TODO: This could be a generic combine with a predicate for extracting the
9366   // high half of an integer being free.
9367 
9368   // (or i64:x, (zero_extend i32:y)) ->
9369   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9370   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9371       RHS.getOpcode() != ISD::ZERO_EXTEND)
9372     std::swap(LHS, RHS);
9373 
9374   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9375     SDValue ExtSrc = RHS.getOperand(0);
9376     EVT SrcVT = ExtSrc.getValueType();
9377     if (SrcVT == MVT::i32) {
9378       SDLoc SL(N);
9379       SDValue LowLHS, HiBits;
9380       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9381       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9382 
9383       DCI.AddToWorklist(LowOr.getNode());
9384       DCI.AddToWorklist(HiBits.getNode());
9385 
9386       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9387                                 LowOr, HiBits);
9388       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9389     }
9390   }
9391 
9392   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9393   if (CRHS) {
9394     if (SDValue Split
9395           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9396       return Split;
9397   }
9398 
9399   return SDValue();
9400 }
9401 
9402 SDValue SITargetLowering::performXorCombine(SDNode *N,
9403                                             DAGCombinerInfo &DCI) const {
9404   EVT VT = N->getValueType(0);
9405   if (VT != MVT::i64)
9406     return SDValue();
9407 
9408   SDValue LHS = N->getOperand(0);
9409   SDValue RHS = N->getOperand(1);
9410 
9411   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9412   if (CRHS) {
9413     if (SDValue Split
9414           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9415       return Split;
9416   }
9417 
9418   return SDValue();
9419 }
9420 
9421 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9422                                                    DAGCombinerInfo &DCI) const {
9423   if (!Subtarget->has16BitInsts() ||
9424       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9425     return SDValue();
9426 
9427   EVT VT = N->getValueType(0);
9428   if (VT != MVT::i32)
9429     return SDValue();
9430 
9431   SDValue Src = N->getOperand(0);
9432   if (Src.getValueType() != MVT::i16)
9433     return SDValue();
9434 
9435   return SDValue();
9436 }
9437 
9438 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9439                                                         DAGCombinerInfo &DCI)
9440                                                         const {
9441   SDValue Src = N->getOperand(0);
9442   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9443 
9444   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9445       VTSign->getVT() == MVT::i8) ||
9446       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9447       VTSign->getVT() == MVT::i16)) &&
9448       Src.hasOneUse()) {
9449     auto *M = cast<MemSDNode>(Src);
9450     SDValue Ops[] = {
9451       Src.getOperand(0), // Chain
9452       Src.getOperand(1), // rsrc
9453       Src.getOperand(2), // vindex
9454       Src.getOperand(3), // voffset
9455       Src.getOperand(4), // soffset
9456       Src.getOperand(5), // offset
9457       Src.getOperand(6),
9458       Src.getOperand(7)
9459     };
9460     // replace with BUFFER_LOAD_BYTE/SHORT
9461     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9462                                          Src.getOperand(0).getValueType());
9463     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9464                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9465     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9466                                                           ResList,
9467                                                           Ops, M->getMemoryVT(),
9468                                                           M->getMemOperand());
9469     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9470                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9471   }
9472   return SDValue();
9473 }
9474 
9475 SDValue SITargetLowering::performClassCombine(SDNode *N,
9476                                               DAGCombinerInfo &DCI) const {
9477   SelectionDAG &DAG = DCI.DAG;
9478   SDValue Mask = N->getOperand(1);
9479 
9480   // fp_class x, 0 -> false
9481   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9482     if (CMask->isNullValue())
9483       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9484   }
9485 
9486   if (N->getOperand(0).isUndef())
9487     return DAG.getUNDEF(MVT::i1);
9488 
9489   return SDValue();
9490 }
9491 
9492 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9493                                             DAGCombinerInfo &DCI) const {
9494   EVT VT = N->getValueType(0);
9495   SDValue N0 = N->getOperand(0);
9496 
9497   if (N0.isUndef())
9498     return N0;
9499 
9500   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9501                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9502     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9503                            N->getFlags());
9504   }
9505 
9506   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9507     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9508                            N0.getOperand(0), N->getFlags());
9509   }
9510 
9511   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9512 }
9513 
9514 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9515                                        unsigned MaxDepth) const {
9516   unsigned Opcode = Op.getOpcode();
9517   if (Opcode == ISD::FCANONICALIZE)
9518     return true;
9519 
9520   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9521     auto F = CFP->getValueAPF();
9522     if (F.isNaN() && F.isSignaling())
9523       return false;
9524     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9525   }
9526 
9527   // If source is a result of another standard FP operation it is already in
9528   // canonical form.
9529   if (MaxDepth == 0)
9530     return false;
9531 
9532   switch (Opcode) {
9533   // These will flush denorms if required.
9534   case ISD::FADD:
9535   case ISD::FSUB:
9536   case ISD::FMUL:
9537   case ISD::FCEIL:
9538   case ISD::FFLOOR:
9539   case ISD::FMA:
9540   case ISD::FMAD:
9541   case ISD::FSQRT:
9542   case ISD::FDIV:
9543   case ISD::FREM:
9544   case ISD::FP_ROUND:
9545   case ISD::FP_EXTEND:
9546   case AMDGPUISD::FMUL_LEGACY:
9547   case AMDGPUISD::FMAD_FTZ:
9548   case AMDGPUISD::RCP:
9549   case AMDGPUISD::RSQ:
9550   case AMDGPUISD::RSQ_CLAMP:
9551   case AMDGPUISD::RCP_LEGACY:
9552   case AMDGPUISD::RCP_IFLAG:
9553   case AMDGPUISD::DIV_SCALE:
9554   case AMDGPUISD::DIV_FMAS:
9555   case AMDGPUISD::DIV_FIXUP:
9556   case AMDGPUISD::FRACT:
9557   case AMDGPUISD::LDEXP:
9558   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9559   case AMDGPUISD::CVT_F32_UBYTE0:
9560   case AMDGPUISD::CVT_F32_UBYTE1:
9561   case AMDGPUISD::CVT_F32_UBYTE2:
9562   case AMDGPUISD::CVT_F32_UBYTE3:
9563     return true;
9564 
9565   // It can/will be lowered or combined as a bit operation.
9566   // Need to check their input recursively to handle.
9567   case ISD::FNEG:
9568   case ISD::FABS:
9569   case ISD::FCOPYSIGN:
9570     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9571 
9572   case ISD::FSIN:
9573   case ISD::FCOS:
9574   case ISD::FSINCOS:
9575     return Op.getValueType().getScalarType() != MVT::f16;
9576 
9577   case ISD::FMINNUM:
9578   case ISD::FMAXNUM:
9579   case ISD::FMINNUM_IEEE:
9580   case ISD::FMAXNUM_IEEE:
9581   case AMDGPUISD::CLAMP:
9582   case AMDGPUISD::FMED3:
9583   case AMDGPUISD::FMAX3:
9584   case AMDGPUISD::FMIN3: {
9585     // FIXME: Shouldn't treat the generic operations different based these.
9586     // However, we aren't really required to flush the result from
9587     // minnum/maxnum..
9588 
9589     // snans will be quieted, so we only need to worry about denormals.
9590     if (Subtarget->supportsMinMaxDenormModes() ||
9591         denormalsEnabledForType(DAG, Op.getValueType()))
9592       return true;
9593 
9594     // Flushing may be required.
9595     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9596     // targets need to check their input recursively.
9597 
9598     // FIXME: Does this apply with clamp? It's implemented with max.
9599     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9600       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9601         return false;
9602     }
9603 
9604     return true;
9605   }
9606   case ISD::SELECT: {
9607     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9608            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9609   }
9610   case ISD::BUILD_VECTOR: {
9611     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9612       SDValue SrcOp = Op.getOperand(i);
9613       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9614         return false;
9615     }
9616 
9617     return true;
9618   }
9619   case ISD::EXTRACT_VECTOR_ELT:
9620   case ISD::EXTRACT_SUBVECTOR: {
9621     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9622   }
9623   case ISD::INSERT_VECTOR_ELT: {
9624     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9625            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9626   }
9627   case ISD::UNDEF:
9628     // Could be anything.
9629     return false;
9630 
9631   case ISD::BITCAST:
9632     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9633   case ISD::TRUNCATE: {
9634     // Hack round the mess we make when legalizing extract_vector_elt
9635     if (Op.getValueType() == MVT::i16) {
9636       SDValue TruncSrc = Op.getOperand(0);
9637       if (TruncSrc.getValueType() == MVT::i32 &&
9638           TruncSrc.getOpcode() == ISD::BITCAST &&
9639           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9640         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9641       }
9642     }
9643     return false;
9644   }
9645   case ISD::INTRINSIC_WO_CHAIN: {
9646     unsigned IntrinsicID
9647       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9648     // TODO: Handle more intrinsics
9649     switch (IntrinsicID) {
9650     case Intrinsic::amdgcn_cvt_pkrtz:
9651     case Intrinsic::amdgcn_cubeid:
9652     case Intrinsic::amdgcn_frexp_mant:
9653     case Intrinsic::amdgcn_fdot2:
9654     case Intrinsic::amdgcn_rcp:
9655     case Intrinsic::amdgcn_rsq:
9656     case Intrinsic::amdgcn_rsq_clamp:
9657     case Intrinsic::amdgcn_rcp_legacy:
9658     case Intrinsic::amdgcn_rsq_legacy:
9659     case Intrinsic::amdgcn_trig_preop:
9660       return true;
9661     default:
9662       break;
9663     }
9664 
9665     LLVM_FALLTHROUGH;
9666   }
9667   default:
9668     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9669            DAG.isKnownNeverSNaN(Op);
9670   }
9671 
9672   llvm_unreachable("invalid operation");
9673 }
9674 
9675 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9676                                        unsigned MaxDepth) const {
9677   MachineRegisterInfo &MRI = MF.getRegInfo();
9678   MachineInstr *MI = MRI.getVRegDef(Reg);
9679   unsigned Opcode = MI->getOpcode();
9680 
9681   if (Opcode == AMDGPU::G_FCANONICALIZE)
9682     return true;
9683 
9684   if (Opcode == AMDGPU::G_FCONSTANT) {
9685     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9686     if (F.isNaN() && F.isSignaling())
9687       return false;
9688     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9689   }
9690 
9691   if (MaxDepth == 0)
9692     return false;
9693 
9694   switch (Opcode) {
9695   case AMDGPU::G_FMINNUM_IEEE:
9696   case AMDGPU::G_FMAXNUM_IEEE: {
9697     if (Subtarget->supportsMinMaxDenormModes() ||
9698         denormalsEnabledForType(MRI.getType(Reg), MF))
9699       return true;
9700     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9701       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9702         return false;
9703     }
9704     return true;
9705   }
9706   default:
9707     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9708            isKnownNeverSNaN(Reg, MRI);
9709   }
9710 
9711   llvm_unreachable("invalid operation");
9712 }
9713 
9714 // Constant fold canonicalize.
9715 SDValue SITargetLowering::getCanonicalConstantFP(
9716   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9717   // Flush denormals to 0 if not enabled.
9718   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9719     return DAG.getConstantFP(0.0, SL, VT);
9720 
9721   if (C.isNaN()) {
9722     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9723     if (C.isSignaling()) {
9724       // Quiet a signaling NaN.
9725       // FIXME: Is this supposed to preserve payload bits?
9726       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9727     }
9728 
9729     // Make sure it is the canonical NaN bitpattern.
9730     //
9731     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9732     // immediate?
9733     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9734       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9735   }
9736 
9737   // Already canonical.
9738   return DAG.getConstantFP(C, SL, VT);
9739 }
9740 
9741 static bool vectorEltWillFoldAway(SDValue Op) {
9742   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9743 }
9744 
9745 SDValue SITargetLowering::performFCanonicalizeCombine(
9746   SDNode *N,
9747   DAGCombinerInfo &DCI) const {
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDValue N0 = N->getOperand(0);
9750   EVT VT = N->getValueType(0);
9751 
9752   // fcanonicalize undef -> qnan
9753   if (N0.isUndef()) {
9754     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9755     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9756   }
9757 
9758   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9759     EVT VT = N->getValueType(0);
9760     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9761   }
9762 
9763   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9764   //                                                   (fcanonicalize k)
9765   //
9766   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9767 
9768   // TODO: This could be better with wider vectors that will be split to v2f16,
9769   // and to consider uses since there aren't that many packed operations.
9770   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9771       isTypeLegal(MVT::v2f16)) {
9772     SDLoc SL(N);
9773     SDValue NewElts[2];
9774     SDValue Lo = N0.getOperand(0);
9775     SDValue Hi = N0.getOperand(1);
9776     EVT EltVT = Lo.getValueType();
9777 
9778     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9779       for (unsigned I = 0; I != 2; ++I) {
9780         SDValue Op = N0.getOperand(I);
9781         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9782           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9783                                               CFP->getValueAPF());
9784         } else if (Op.isUndef()) {
9785           // Handled below based on what the other operand is.
9786           NewElts[I] = Op;
9787         } else {
9788           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9789         }
9790       }
9791 
9792       // If one half is undef, and one is constant, perfer a splat vector rather
9793       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9794       // cheaper to use and may be free with a packed operation.
9795       if (NewElts[0].isUndef()) {
9796         if (isa<ConstantFPSDNode>(NewElts[1]))
9797           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9798             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9799       }
9800 
9801       if (NewElts[1].isUndef()) {
9802         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9803           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9804       }
9805 
9806       return DAG.getBuildVector(VT, SL, NewElts);
9807     }
9808   }
9809 
9810   unsigned SrcOpc = N0.getOpcode();
9811 
9812   // If it's free to do so, push canonicalizes further up the source, which may
9813   // find a canonical source.
9814   //
9815   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9816   // sNaNs.
9817   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9818     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9819     if (CRHS && N0.hasOneUse()) {
9820       SDLoc SL(N);
9821       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9822                                    N0.getOperand(0));
9823       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9824       DCI.AddToWorklist(Canon0.getNode());
9825 
9826       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9827     }
9828   }
9829 
9830   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9831 }
9832 
9833 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9834   switch (Opc) {
9835   case ISD::FMAXNUM:
9836   case ISD::FMAXNUM_IEEE:
9837     return AMDGPUISD::FMAX3;
9838   case ISD::SMAX:
9839     return AMDGPUISD::SMAX3;
9840   case ISD::UMAX:
9841     return AMDGPUISD::UMAX3;
9842   case ISD::FMINNUM:
9843   case ISD::FMINNUM_IEEE:
9844     return AMDGPUISD::FMIN3;
9845   case ISD::SMIN:
9846     return AMDGPUISD::SMIN3;
9847   case ISD::UMIN:
9848     return AMDGPUISD::UMIN3;
9849   default:
9850     llvm_unreachable("Not a min/max opcode");
9851   }
9852 }
9853 
9854 SDValue SITargetLowering::performIntMed3ImmCombine(
9855   SelectionDAG &DAG, const SDLoc &SL,
9856   SDValue Op0, SDValue Op1, bool Signed) const {
9857   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9858   if (!K1)
9859     return SDValue();
9860 
9861   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9862   if (!K0)
9863     return SDValue();
9864 
9865   if (Signed) {
9866     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9867       return SDValue();
9868   } else {
9869     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9870       return SDValue();
9871   }
9872 
9873   EVT VT = K0->getValueType(0);
9874   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9875   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9876     return DAG.getNode(Med3Opc, SL, VT,
9877                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9878   }
9879 
9880   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9881   if (VT == MVT::i16) {
9882     MVT NVT = MVT::i32;
9883     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9884 
9885     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9886     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9887     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9888 
9889     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9890     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9891   }
9892 
9893   return SDValue();
9894 }
9895 
9896 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9897   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9898     return C;
9899 
9900   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9901     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9902       return C;
9903   }
9904 
9905   return nullptr;
9906 }
9907 
9908 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9909                                                   const SDLoc &SL,
9910                                                   SDValue Op0,
9911                                                   SDValue Op1) const {
9912   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9913   if (!K1)
9914     return SDValue();
9915 
9916   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9917   if (!K0)
9918     return SDValue();
9919 
9920   // Ordered >= (although NaN inputs should have folded away by now).
9921   if (K0->getValueAPF() > K1->getValueAPF())
9922     return SDValue();
9923 
9924   const MachineFunction &MF = DAG.getMachineFunction();
9925   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9926 
9927   // TODO: Check IEEE bit enabled?
9928   EVT VT = Op0.getValueType();
9929   if (Info->getMode().DX10Clamp) {
9930     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9931     // hardware fmed3 behavior converting to a min.
9932     // FIXME: Should this be allowing -0.0?
9933     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9934       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9935   }
9936 
9937   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9938   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9939     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9940     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9941     // then give the other result, which is different from med3 with a NaN
9942     // input.
9943     SDValue Var = Op0.getOperand(0);
9944     if (!DAG.isKnownNeverSNaN(Var))
9945       return SDValue();
9946 
9947     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9948 
9949     if ((!K0->hasOneUse() ||
9950          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9951         (!K1->hasOneUse() ||
9952          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9953       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9954                          Var, SDValue(K0, 0), SDValue(K1, 0));
9955     }
9956   }
9957 
9958   return SDValue();
9959 }
9960 
9961 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9962                                                DAGCombinerInfo &DCI) const {
9963   SelectionDAG &DAG = DCI.DAG;
9964 
9965   EVT VT = N->getValueType(0);
9966   unsigned Opc = N->getOpcode();
9967   SDValue Op0 = N->getOperand(0);
9968   SDValue Op1 = N->getOperand(1);
9969 
9970   // Only do this if the inner op has one use since this will just increases
9971   // register pressure for no benefit.
9972 
9973   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9974       !VT.isVector() &&
9975       (VT == MVT::i32 || VT == MVT::f32 ||
9976        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9977     // max(max(a, b), c) -> max3(a, b, c)
9978     // min(min(a, b), c) -> min3(a, b, c)
9979     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9980       SDLoc DL(N);
9981       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9982                          DL,
9983                          N->getValueType(0),
9984                          Op0.getOperand(0),
9985                          Op0.getOperand(1),
9986                          Op1);
9987     }
9988 
9989     // Try commuted.
9990     // max(a, max(b, c)) -> max3(a, b, c)
9991     // min(a, min(b, c)) -> min3(a, b, c)
9992     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9993       SDLoc DL(N);
9994       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9995                          DL,
9996                          N->getValueType(0),
9997                          Op0,
9998                          Op1.getOperand(0),
9999                          Op1.getOperand(1));
10000     }
10001   }
10002 
10003   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10004   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10005     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10006       return Med3;
10007   }
10008 
10009   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10010     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10011       return Med3;
10012   }
10013 
10014   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10015   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10016        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10017        (Opc == AMDGPUISD::FMIN_LEGACY &&
10018         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10019       (VT == MVT::f32 || VT == MVT::f64 ||
10020        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10021        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10022       Op0.hasOneUse()) {
10023     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10024       return Res;
10025   }
10026 
10027   return SDValue();
10028 }
10029 
10030 static bool isClampZeroToOne(SDValue A, SDValue B) {
10031   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10032     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10033       // FIXME: Should this be allowing -0.0?
10034       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10035              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10036     }
10037   }
10038 
10039   return false;
10040 }
10041 
10042 // FIXME: Should only worry about snans for version with chain.
10043 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10044                                               DAGCombinerInfo &DCI) const {
10045   EVT VT = N->getValueType(0);
10046   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10047   // NaNs. With a NaN input, the order of the operands may change the result.
10048 
10049   SelectionDAG &DAG = DCI.DAG;
10050   SDLoc SL(N);
10051 
10052   SDValue Src0 = N->getOperand(0);
10053   SDValue Src1 = N->getOperand(1);
10054   SDValue Src2 = N->getOperand(2);
10055 
10056   if (isClampZeroToOne(Src0, Src1)) {
10057     // const_a, const_b, x -> clamp is safe in all cases including signaling
10058     // nans.
10059     // FIXME: Should this be allowing -0.0?
10060     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10061   }
10062 
10063   const MachineFunction &MF = DAG.getMachineFunction();
10064   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10065 
10066   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10067   // handling no dx10-clamp?
10068   if (Info->getMode().DX10Clamp) {
10069     // If NaNs is clamped to 0, we are free to reorder the inputs.
10070 
10071     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10072       std::swap(Src0, Src1);
10073 
10074     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10075       std::swap(Src1, Src2);
10076 
10077     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10078       std::swap(Src0, Src1);
10079 
10080     if (isClampZeroToOne(Src1, Src2))
10081       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10082   }
10083 
10084   return SDValue();
10085 }
10086 
10087 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10088                                                  DAGCombinerInfo &DCI) const {
10089   SDValue Src0 = N->getOperand(0);
10090   SDValue Src1 = N->getOperand(1);
10091   if (Src0.isUndef() && Src1.isUndef())
10092     return DCI.DAG.getUNDEF(N->getValueType(0));
10093   return SDValue();
10094 }
10095 
10096 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10097 // expanded into a set of cmp/select instructions.
10098 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10099                                                 unsigned NumElem,
10100                                                 bool IsDivergentIdx) {
10101   if (UseDivergentRegisterIndexing)
10102     return false;
10103 
10104   unsigned VecSize = EltSize * NumElem;
10105 
10106   // Sub-dword vectors of size 2 dword or less have better implementation.
10107   if (VecSize <= 64 && EltSize < 32)
10108     return false;
10109 
10110   // Always expand the rest of sub-dword instructions, otherwise it will be
10111   // lowered via memory.
10112   if (EltSize < 32)
10113     return true;
10114 
10115   // Always do this if var-idx is divergent, otherwise it will become a loop.
10116   if (IsDivergentIdx)
10117     return true;
10118 
10119   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10120   unsigned NumInsts = NumElem /* Number of compares */ +
10121                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10122   return NumInsts <= 16;
10123 }
10124 
10125 static bool shouldExpandVectorDynExt(SDNode *N) {
10126   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10127   if (isa<ConstantSDNode>(Idx))
10128     return false;
10129 
10130   SDValue Vec = N->getOperand(0);
10131   EVT VecVT = Vec.getValueType();
10132   EVT EltVT = VecVT.getVectorElementType();
10133   unsigned EltSize = EltVT.getSizeInBits();
10134   unsigned NumElem = VecVT.getVectorNumElements();
10135 
10136   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10137                                                     Idx->isDivergent());
10138 }
10139 
10140 SDValue SITargetLowering::performExtractVectorEltCombine(
10141   SDNode *N, DAGCombinerInfo &DCI) const {
10142   SDValue Vec = N->getOperand(0);
10143   SelectionDAG &DAG = DCI.DAG;
10144 
10145   EVT VecVT = Vec.getValueType();
10146   EVT EltVT = VecVT.getVectorElementType();
10147 
10148   if ((Vec.getOpcode() == ISD::FNEG ||
10149        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10150     SDLoc SL(N);
10151     EVT EltVT = N->getValueType(0);
10152     SDValue Idx = N->getOperand(1);
10153     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10154                               Vec.getOperand(0), Idx);
10155     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10156   }
10157 
10158   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10159   //    =>
10160   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10161   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10162   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10163   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10164     SDLoc SL(N);
10165     EVT EltVT = N->getValueType(0);
10166     SDValue Idx = N->getOperand(1);
10167     unsigned Opc = Vec.getOpcode();
10168 
10169     switch(Opc) {
10170     default:
10171       break;
10172       // TODO: Support other binary operations.
10173     case ISD::FADD:
10174     case ISD::FSUB:
10175     case ISD::FMUL:
10176     case ISD::ADD:
10177     case ISD::UMIN:
10178     case ISD::UMAX:
10179     case ISD::SMIN:
10180     case ISD::SMAX:
10181     case ISD::FMAXNUM:
10182     case ISD::FMINNUM:
10183     case ISD::FMAXNUM_IEEE:
10184     case ISD::FMINNUM_IEEE: {
10185       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10186                                  Vec.getOperand(0), Idx);
10187       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10188                                  Vec.getOperand(1), Idx);
10189 
10190       DCI.AddToWorklist(Elt0.getNode());
10191       DCI.AddToWorklist(Elt1.getNode());
10192       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10193     }
10194     }
10195   }
10196 
10197   unsigned VecSize = VecVT.getSizeInBits();
10198   unsigned EltSize = EltVT.getSizeInBits();
10199 
10200   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10201   if (::shouldExpandVectorDynExt(N)) {
10202     SDLoc SL(N);
10203     SDValue Idx = N->getOperand(1);
10204     SDValue V;
10205     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10206       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10207       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10208       if (I == 0)
10209         V = Elt;
10210       else
10211         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10212     }
10213     return V;
10214   }
10215 
10216   if (!DCI.isBeforeLegalize())
10217     return SDValue();
10218 
10219   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10220   // elements. This exposes more load reduction opportunities by replacing
10221   // multiple small extract_vector_elements with a single 32-bit extract.
10222   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10223   if (isa<MemSDNode>(Vec) &&
10224       EltSize <= 16 &&
10225       EltVT.isByteSized() &&
10226       VecSize > 32 &&
10227       VecSize % 32 == 0 &&
10228       Idx) {
10229     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10230 
10231     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10232     unsigned EltIdx = BitIndex / 32;
10233     unsigned LeftoverBitIdx = BitIndex % 32;
10234     SDLoc SL(N);
10235 
10236     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10237     DCI.AddToWorklist(Cast.getNode());
10238 
10239     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10240                               DAG.getConstant(EltIdx, SL, MVT::i32));
10241     DCI.AddToWorklist(Elt.getNode());
10242     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10243                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10244     DCI.AddToWorklist(Srl.getNode());
10245 
10246     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10247     DCI.AddToWorklist(Trunc.getNode());
10248     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10249   }
10250 
10251   return SDValue();
10252 }
10253 
10254 SDValue
10255 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10256                                                 DAGCombinerInfo &DCI) const {
10257   SDValue Vec = N->getOperand(0);
10258   SDValue Idx = N->getOperand(2);
10259   EVT VecVT = Vec.getValueType();
10260   EVT EltVT = VecVT.getVectorElementType();
10261 
10262   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10263   // => BUILD_VECTOR n x select (e, const-idx)
10264   if (!::shouldExpandVectorDynExt(N))
10265     return SDValue();
10266 
10267   SelectionDAG &DAG = DCI.DAG;
10268   SDLoc SL(N);
10269   SDValue Ins = N->getOperand(1);
10270   EVT IdxVT = Idx.getValueType();
10271 
10272   SmallVector<SDValue, 16> Ops;
10273   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10274     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10275     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10276     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10277     Ops.push_back(V);
10278   }
10279 
10280   return DAG.getBuildVector(VecVT, SL, Ops);
10281 }
10282 
10283 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10284                                           const SDNode *N0,
10285                                           const SDNode *N1) const {
10286   EVT VT = N0->getValueType(0);
10287 
10288   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10289   // support denormals ever.
10290   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10291        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10292         getSubtarget()->hasMadF16())) &&
10293        isOperationLegal(ISD::FMAD, VT))
10294     return ISD::FMAD;
10295 
10296   const TargetOptions &Options = DAG.getTarget().Options;
10297   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10298        (N0->getFlags().hasAllowContract() &&
10299         N1->getFlags().hasAllowContract())) &&
10300       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10301     return ISD::FMA;
10302   }
10303 
10304   return 0;
10305 }
10306 
10307 // For a reassociatable opcode perform:
10308 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10309 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10310                                                SelectionDAG &DAG) const {
10311   EVT VT = N->getValueType(0);
10312   if (VT != MVT::i32 && VT != MVT::i64)
10313     return SDValue();
10314 
10315   unsigned Opc = N->getOpcode();
10316   SDValue Op0 = N->getOperand(0);
10317   SDValue Op1 = N->getOperand(1);
10318 
10319   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10320     return SDValue();
10321 
10322   if (Op0->isDivergent())
10323     std::swap(Op0, Op1);
10324 
10325   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10326     return SDValue();
10327 
10328   SDValue Op2 = Op1.getOperand(1);
10329   Op1 = Op1.getOperand(0);
10330   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10331     return SDValue();
10332 
10333   if (Op1->isDivergent())
10334     std::swap(Op1, Op2);
10335 
10336   // If either operand is constant this will conflict with
10337   // DAGCombiner::ReassociateOps().
10338   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10339       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10340     return SDValue();
10341 
10342   SDLoc SL(N);
10343   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10344   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10345 }
10346 
10347 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10348                            EVT VT,
10349                            SDValue N0, SDValue N1, SDValue N2,
10350                            bool Signed) {
10351   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10352   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10353   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10354   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10355 }
10356 
10357 SDValue SITargetLowering::performAddCombine(SDNode *N,
10358                                             DAGCombinerInfo &DCI) const {
10359   SelectionDAG &DAG = DCI.DAG;
10360   EVT VT = N->getValueType(0);
10361   SDLoc SL(N);
10362   SDValue LHS = N->getOperand(0);
10363   SDValue RHS = N->getOperand(1);
10364 
10365   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10366       && Subtarget->hasMad64_32() &&
10367       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10368       VT.getScalarSizeInBits() <= 64) {
10369     if (LHS.getOpcode() != ISD::MUL)
10370       std::swap(LHS, RHS);
10371 
10372     SDValue MulLHS = LHS.getOperand(0);
10373     SDValue MulRHS = LHS.getOperand(1);
10374     SDValue AddRHS = RHS;
10375 
10376     // TODO: Maybe restrict if SGPR inputs.
10377     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10378         numBitsUnsigned(MulRHS, DAG) <= 32) {
10379       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10380       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10381       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10382       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10383     }
10384 
10385     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10386       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10387       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10388       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10389       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10390     }
10391 
10392     return SDValue();
10393   }
10394 
10395   if (SDValue V = reassociateScalarOps(N, DAG)) {
10396     return V;
10397   }
10398 
10399   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10400     return SDValue();
10401 
10402   // add x, zext (setcc) => addcarry x, 0, setcc
10403   // add x, sext (setcc) => subcarry x, 0, setcc
10404   unsigned Opc = LHS.getOpcode();
10405   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10406       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10407     std::swap(RHS, LHS);
10408 
10409   Opc = RHS.getOpcode();
10410   switch (Opc) {
10411   default: break;
10412   case ISD::ZERO_EXTEND:
10413   case ISD::SIGN_EXTEND:
10414   case ISD::ANY_EXTEND: {
10415     auto Cond = RHS.getOperand(0);
10416     // If this won't be a real VOPC output, we would still need to insert an
10417     // extra instruction anyway.
10418     if (!isBoolSGPR(Cond))
10419       break;
10420     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10421     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10422     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10423     return DAG.getNode(Opc, SL, VTList, Args);
10424   }
10425   case ISD::ADDCARRY: {
10426     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10427     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10428     if (!C || C->getZExtValue() != 0) break;
10429     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10430     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10431   }
10432   }
10433   return SDValue();
10434 }
10435 
10436 SDValue SITargetLowering::performSubCombine(SDNode *N,
10437                                             DAGCombinerInfo &DCI) const {
10438   SelectionDAG &DAG = DCI.DAG;
10439   EVT VT = N->getValueType(0);
10440 
10441   if (VT != MVT::i32)
10442     return SDValue();
10443 
10444   SDLoc SL(N);
10445   SDValue LHS = N->getOperand(0);
10446   SDValue RHS = N->getOperand(1);
10447 
10448   // sub x, zext (setcc) => subcarry x, 0, setcc
10449   // sub x, sext (setcc) => addcarry x, 0, setcc
10450   unsigned Opc = RHS.getOpcode();
10451   switch (Opc) {
10452   default: break;
10453   case ISD::ZERO_EXTEND:
10454   case ISD::SIGN_EXTEND:
10455   case ISD::ANY_EXTEND: {
10456     auto Cond = RHS.getOperand(0);
10457     // If this won't be a real VOPC output, we would still need to insert an
10458     // extra instruction anyway.
10459     if (!isBoolSGPR(Cond))
10460       break;
10461     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10462     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10463     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10464     return DAG.getNode(Opc, SL, VTList, Args);
10465   }
10466   }
10467 
10468   if (LHS.getOpcode() == ISD::SUBCARRY) {
10469     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10470     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10471     if (!C || !C->isNullValue())
10472       return SDValue();
10473     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10474     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10475   }
10476   return SDValue();
10477 }
10478 
10479 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10480   DAGCombinerInfo &DCI) const {
10481 
10482   if (N->getValueType(0) != MVT::i32)
10483     return SDValue();
10484 
10485   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10486   if (!C || C->getZExtValue() != 0)
10487     return SDValue();
10488 
10489   SelectionDAG &DAG = DCI.DAG;
10490   SDValue LHS = N->getOperand(0);
10491 
10492   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10493   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10494   unsigned LHSOpc = LHS.getOpcode();
10495   unsigned Opc = N->getOpcode();
10496   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10497       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10498     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10499     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10500   }
10501   return SDValue();
10502 }
10503 
10504 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10505                                              DAGCombinerInfo &DCI) const {
10506   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10507     return SDValue();
10508 
10509   SelectionDAG &DAG = DCI.DAG;
10510   EVT VT = N->getValueType(0);
10511 
10512   SDLoc SL(N);
10513   SDValue LHS = N->getOperand(0);
10514   SDValue RHS = N->getOperand(1);
10515 
10516   // These should really be instruction patterns, but writing patterns with
10517   // source modiifiers is a pain.
10518 
10519   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10520   if (LHS.getOpcode() == ISD::FADD) {
10521     SDValue A = LHS.getOperand(0);
10522     if (A == LHS.getOperand(1)) {
10523       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10524       if (FusedOp != 0) {
10525         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10526         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10527       }
10528     }
10529   }
10530 
10531   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10532   if (RHS.getOpcode() == ISD::FADD) {
10533     SDValue A = RHS.getOperand(0);
10534     if (A == RHS.getOperand(1)) {
10535       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10536       if (FusedOp != 0) {
10537         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10538         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10539       }
10540     }
10541   }
10542 
10543   return SDValue();
10544 }
10545 
10546 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10547                                              DAGCombinerInfo &DCI) const {
10548   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10549     return SDValue();
10550 
10551   SelectionDAG &DAG = DCI.DAG;
10552   SDLoc SL(N);
10553   EVT VT = N->getValueType(0);
10554   assert(!VT.isVector());
10555 
10556   // Try to get the fneg to fold into the source modifier. This undoes generic
10557   // DAG combines and folds them into the mad.
10558   //
10559   // Only do this if we are not trying to support denormals. v_mad_f32 does
10560   // not support denormals ever.
10561   SDValue LHS = N->getOperand(0);
10562   SDValue RHS = N->getOperand(1);
10563   if (LHS.getOpcode() == ISD::FADD) {
10564     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10565     SDValue A = LHS.getOperand(0);
10566     if (A == LHS.getOperand(1)) {
10567       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10568       if (FusedOp != 0){
10569         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10570         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10571 
10572         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10573       }
10574     }
10575   }
10576 
10577   if (RHS.getOpcode() == ISD::FADD) {
10578     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10579 
10580     SDValue A = RHS.getOperand(0);
10581     if (A == RHS.getOperand(1)) {
10582       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10583       if (FusedOp != 0){
10584         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10585         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10586       }
10587     }
10588   }
10589 
10590   return SDValue();
10591 }
10592 
10593 SDValue SITargetLowering::performFMACombine(SDNode *N,
10594                                             DAGCombinerInfo &DCI) const {
10595   SelectionDAG &DAG = DCI.DAG;
10596   EVT VT = N->getValueType(0);
10597   SDLoc SL(N);
10598 
10599   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10600     return SDValue();
10601 
10602   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10603   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10604   SDValue Op1 = N->getOperand(0);
10605   SDValue Op2 = N->getOperand(1);
10606   SDValue FMA = N->getOperand(2);
10607 
10608   if (FMA.getOpcode() != ISD::FMA ||
10609       Op1.getOpcode() != ISD::FP_EXTEND ||
10610       Op2.getOpcode() != ISD::FP_EXTEND)
10611     return SDValue();
10612 
10613   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10614   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10615   // is sufficient to allow generaing fdot2.
10616   const TargetOptions &Options = DAG.getTarget().Options;
10617   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10618       (N->getFlags().hasAllowContract() &&
10619        FMA->getFlags().hasAllowContract())) {
10620     Op1 = Op1.getOperand(0);
10621     Op2 = Op2.getOperand(0);
10622     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10623         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10624       return SDValue();
10625 
10626     SDValue Vec1 = Op1.getOperand(0);
10627     SDValue Idx1 = Op1.getOperand(1);
10628     SDValue Vec2 = Op2.getOperand(0);
10629 
10630     SDValue FMAOp1 = FMA.getOperand(0);
10631     SDValue FMAOp2 = FMA.getOperand(1);
10632     SDValue FMAAcc = FMA.getOperand(2);
10633 
10634     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10635         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10636       return SDValue();
10637 
10638     FMAOp1 = FMAOp1.getOperand(0);
10639     FMAOp2 = FMAOp2.getOperand(0);
10640     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10641         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10642       return SDValue();
10643 
10644     SDValue Vec3 = FMAOp1.getOperand(0);
10645     SDValue Vec4 = FMAOp2.getOperand(0);
10646     SDValue Idx2 = FMAOp1.getOperand(1);
10647 
10648     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10649         // Idx1 and Idx2 cannot be the same.
10650         Idx1 == Idx2)
10651       return SDValue();
10652 
10653     if (Vec1 == Vec2 || Vec3 == Vec4)
10654       return SDValue();
10655 
10656     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10657       return SDValue();
10658 
10659     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10660         (Vec1 == Vec4 && Vec2 == Vec3)) {
10661       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10662                          DAG.getTargetConstant(0, SL, MVT::i1));
10663     }
10664   }
10665   return SDValue();
10666 }
10667 
10668 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10669                                               DAGCombinerInfo &DCI) const {
10670   SelectionDAG &DAG = DCI.DAG;
10671   SDLoc SL(N);
10672 
10673   SDValue LHS = N->getOperand(0);
10674   SDValue RHS = N->getOperand(1);
10675   EVT VT = LHS.getValueType();
10676   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10677 
10678   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10679   if (!CRHS) {
10680     CRHS = dyn_cast<ConstantSDNode>(LHS);
10681     if (CRHS) {
10682       std::swap(LHS, RHS);
10683       CC = getSetCCSwappedOperands(CC);
10684     }
10685   }
10686 
10687   if (CRHS) {
10688     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10689         isBoolSGPR(LHS.getOperand(0))) {
10690       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10691       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10692       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10693       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10694       if ((CRHS->isAllOnesValue() &&
10695            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10696           (CRHS->isNullValue() &&
10697            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10698         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10699                            DAG.getConstant(-1, SL, MVT::i1));
10700       if ((CRHS->isAllOnesValue() &&
10701            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10702           (CRHS->isNullValue() &&
10703            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10704         return LHS.getOperand(0);
10705     }
10706 
10707     uint64_t CRHSVal = CRHS->getZExtValue();
10708     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10709         LHS.getOpcode() == ISD::SELECT &&
10710         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10711         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10712         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10713         isBoolSGPR(LHS.getOperand(0))) {
10714       // Given CT != FT:
10715       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10716       // setcc (select cc, CT, CF), CF, ne => cc
10717       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10718       // setcc (select cc, CT, CF), CT, eq => cc
10719       uint64_t CT = LHS.getConstantOperandVal(1);
10720       uint64_t CF = LHS.getConstantOperandVal(2);
10721 
10722       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10723           (CT == CRHSVal && CC == ISD::SETNE))
10724         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10725                            DAG.getConstant(-1, SL, MVT::i1));
10726       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10727           (CT == CRHSVal && CC == ISD::SETEQ))
10728         return LHS.getOperand(0);
10729     }
10730   }
10731 
10732   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10733                                            VT != MVT::f16))
10734     return SDValue();
10735 
10736   // Match isinf/isfinite pattern
10737   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10738   // (fcmp one (fabs x), inf) -> (fp_class x,
10739   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10740   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10741     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10742     if (!CRHS)
10743       return SDValue();
10744 
10745     const APFloat &APF = CRHS->getValueAPF();
10746     if (APF.isInfinity() && !APF.isNegative()) {
10747       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10748                                  SIInstrFlags::N_INFINITY;
10749       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10750                                     SIInstrFlags::P_ZERO |
10751                                     SIInstrFlags::N_NORMAL |
10752                                     SIInstrFlags::P_NORMAL |
10753                                     SIInstrFlags::N_SUBNORMAL |
10754                                     SIInstrFlags::P_SUBNORMAL;
10755       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10756       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10757                          DAG.getConstant(Mask, SL, MVT::i32));
10758     }
10759   }
10760 
10761   return SDValue();
10762 }
10763 
10764 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10765                                                      DAGCombinerInfo &DCI) const {
10766   SelectionDAG &DAG = DCI.DAG;
10767   SDLoc SL(N);
10768   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10769 
10770   SDValue Src = N->getOperand(0);
10771   SDValue Shift = N->getOperand(0);
10772 
10773   // TODO: Extend type shouldn't matter (assuming legal types).
10774   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10775     Shift = Shift.getOperand(0);
10776 
10777   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10778     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10779     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10780     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10781     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10782     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10783     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10784       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10785                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10786 
10787       unsigned ShiftOffset = 8 * Offset;
10788       if (Shift.getOpcode() == ISD::SHL)
10789         ShiftOffset -= C->getZExtValue();
10790       else
10791         ShiftOffset += C->getZExtValue();
10792 
10793       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10794         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10795                            MVT::f32, Shift);
10796       }
10797     }
10798   }
10799 
10800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10801   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10802   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10803     // We simplified Src. If this node is not dead, visit it again so it is
10804     // folded properly.
10805     if (N->getOpcode() != ISD::DELETED_NODE)
10806       DCI.AddToWorklist(N);
10807     return SDValue(N, 0);
10808   }
10809 
10810   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10811   if (SDValue DemandedSrc =
10812           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10813     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10814 
10815   return SDValue();
10816 }
10817 
10818 SDValue SITargetLowering::performClampCombine(SDNode *N,
10819                                               DAGCombinerInfo &DCI) const {
10820   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10821   if (!CSrc)
10822     return SDValue();
10823 
10824   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10825   const APFloat &F = CSrc->getValueAPF();
10826   APFloat Zero = APFloat::getZero(F.getSemantics());
10827   if (F < Zero ||
10828       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10829     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10830   }
10831 
10832   APFloat One(F.getSemantics(), "1.0");
10833   if (F > One)
10834     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10835 
10836   return SDValue(CSrc, 0);
10837 }
10838 
10839 
10840 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10841                                             DAGCombinerInfo &DCI) const {
10842   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10843     return SDValue();
10844   switch (N->getOpcode()) {
10845   case ISD::ADD:
10846     return performAddCombine(N, DCI);
10847   case ISD::SUB:
10848     return performSubCombine(N, DCI);
10849   case ISD::ADDCARRY:
10850   case ISD::SUBCARRY:
10851     return performAddCarrySubCarryCombine(N, DCI);
10852   case ISD::FADD:
10853     return performFAddCombine(N, DCI);
10854   case ISD::FSUB:
10855     return performFSubCombine(N, DCI);
10856   case ISD::SETCC:
10857     return performSetCCCombine(N, DCI);
10858   case ISD::FMAXNUM:
10859   case ISD::FMINNUM:
10860   case ISD::FMAXNUM_IEEE:
10861   case ISD::FMINNUM_IEEE:
10862   case ISD::SMAX:
10863   case ISD::SMIN:
10864   case ISD::UMAX:
10865   case ISD::UMIN:
10866   case AMDGPUISD::FMIN_LEGACY:
10867   case AMDGPUISD::FMAX_LEGACY:
10868     return performMinMaxCombine(N, DCI);
10869   case ISD::FMA:
10870     return performFMACombine(N, DCI);
10871   case ISD::AND:
10872     return performAndCombine(N, DCI);
10873   case ISD::OR:
10874     return performOrCombine(N, DCI);
10875   case ISD::XOR:
10876     return performXorCombine(N, DCI);
10877   case ISD::ZERO_EXTEND:
10878     return performZeroExtendCombine(N, DCI);
10879   case ISD::SIGN_EXTEND_INREG:
10880     return performSignExtendInRegCombine(N , DCI);
10881   case AMDGPUISD::FP_CLASS:
10882     return performClassCombine(N, DCI);
10883   case ISD::FCANONICALIZE:
10884     return performFCanonicalizeCombine(N, DCI);
10885   case AMDGPUISD::RCP:
10886     return performRcpCombine(N, DCI);
10887   case AMDGPUISD::FRACT:
10888   case AMDGPUISD::RSQ:
10889   case AMDGPUISD::RCP_LEGACY:
10890   case AMDGPUISD::RCP_IFLAG:
10891   case AMDGPUISD::RSQ_CLAMP:
10892   case AMDGPUISD::LDEXP: {
10893     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10894     SDValue Src = N->getOperand(0);
10895     if (Src.isUndef())
10896       return Src;
10897     break;
10898   }
10899   case ISD::SINT_TO_FP:
10900   case ISD::UINT_TO_FP:
10901     return performUCharToFloatCombine(N, DCI);
10902   case AMDGPUISD::CVT_F32_UBYTE0:
10903   case AMDGPUISD::CVT_F32_UBYTE1:
10904   case AMDGPUISD::CVT_F32_UBYTE2:
10905   case AMDGPUISD::CVT_F32_UBYTE3:
10906     return performCvtF32UByteNCombine(N, DCI);
10907   case AMDGPUISD::FMED3:
10908     return performFMed3Combine(N, DCI);
10909   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10910     return performCvtPkRTZCombine(N, DCI);
10911   case AMDGPUISD::CLAMP:
10912     return performClampCombine(N, DCI);
10913   case ISD::SCALAR_TO_VECTOR: {
10914     SelectionDAG &DAG = DCI.DAG;
10915     EVT VT = N->getValueType(0);
10916 
10917     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10918     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10919       SDLoc SL(N);
10920       SDValue Src = N->getOperand(0);
10921       EVT EltVT = Src.getValueType();
10922       if (EltVT == MVT::f16)
10923         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10924 
10925       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10926       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10927     }
10928 
10929     break;
10930   }
10931   case ISD::EXTRACT_VECTOR_ELT:
10932     return performExtractVectorEltCombine(N, DCI);
10933   case ISD::INSERT_VECTOR_ELT:
10934     return performInsertVectorEltCombine(N, DCI);
10935   case ISD::LOAD: {
10936     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10937       return Widended;
10938     LLVM_FALLTHROUGH;
10939   }
10940   default: {
10941     if (!DCI.isBeforeLegalize()) {
10942       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10943         return performMemSDNodeCombine(MemNode, DCI);
10944     }
10945 
10946     break;
10947   }
10948   }
10949 
10950   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10951 }
10952 
10953 /// Helper function for adjustWritemask
10954 static unsigned SubIdx2Lane(unsigned Idx) {
10955   switch (Idx) {
10956   default: return ~0u;
10957   case AMDGPU::sub0: return 0;
10958   case AMDGPU::sub1: return 1;
10959   case AMDGPU::sub2: return 2;
10960   case AMDGPU::sub3: return 3;
10961   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10962   }
10963 }
10964 
10965 /// Adjust the writemask of MIMG instructions
10966 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10967                                           SelectionDAG &DAG) const {
10968   unsigned Opcode = Node->getMachineOpcode();
10969 
10970   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10971   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10972   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10973     return Node; // not implemented for D16
10974 
10975   SDNode *Users[5] = { nullptr };
10976   unsigned Lane = 0;
10977   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10978   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10979   unsigned NewDmask = 0;
10980   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10981   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10982   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
10983                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10984   unsigned TFCLane = 0;
10985   bool HasChain = Node->getNumValues() > 1;
10986 
10987   if (OldDmask == 0) {
10988     // These are folded out, but on the chance it happens don't assert.
10989     return Node;
10990   }
10991 
10992   unsigned OldBitsSet = countPopulation(OldDmask);
10993   // Work out which is the TFE/LWE lane if that is enabled.
10994   if (UsesTFC) {
10995     TFCLane = OldBitsSet;
10996   }
10997 
10998   // Try to figure out the used register components
10999   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11000        I != E; ++I) {
11001 
11002     // Don't look at users of the chain.
11003     if (I.getUse().getResNo() != 0)
11004       continue;
11005 
11006     // Abort if we can't understand the usage
11007     if (!I->isMachineOpcode() ||
11008         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11009       return Node;
11010 
11011     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11012     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11013     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11014     // set, etc.
11015     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11016     if (Lane == ~0u)
11017       return Node;
11018 
11019     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11020     if (UsesTFC && Lane == TFCLane) {
11021       Users[Lane] = *I;
11022     } else {
11023       // Set which texture component corresponds to the lane.
11024       unsigned Comp;
11025       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11026         Comp = countTrailingZeros(Dmask);
11027         Dmask &= ~(1 << Comp);
11028       }
11029 
11030       // Abort if we have more than one user per component.
11031       if (Users[Lane])
11032         return Node;
11033 
11034       Users[Lane] = *I;
11035       NewDmask |= 1 << Comp;
11036     }
11037   }
11038 
11039   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11040   bool NoChannels = !NewDmask;
11041   if (NoChannels) {
11042     if (!UsesTFC) {
11043       // No uses of the result and not using TFC. Then do nothing.
11044       return Node;
11045     }
11046     // If the original dmask has one channel - then nothing to do
11047     if (OldBitsSet == 1)
11048       return Node;
11049     // Use an arbitrary dmask - required for the instruction to work
11050     NewDmask = 1;
11051   }
11052   // Abort if there's no change
11053   if (NewDmask == OldDmask)
11054     return Node;
11055 
11056   unsigned BitsSet = countPopulation(NewDmask);
11057 
11058   // Check for TFE or LWE - increase the number of channels by one to account
11059   // for the extra return value
11060   // This will need adjustment for D16 if this is also included in
11061   // adjustWriteMask (this function) but at present D16 are excluded.
11062   unsigned NewChannels = BitsSet + UsesTFC;
11063 
11064   int NewOpcode =
11065       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11066   assert(NewOpcode != -1 &&
11067          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11068          "failed to find equivalent MIMG op");
11069 
11070   // Adjust the writemask in the node
11071   SmallVector<SDValue, 12> Ops;
11072   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11073   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11074   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11075 
11076   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11077 
11078   MVT ResultVT = NewChannels == 1 ?
11079     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11080                            NewChannels == 5 ? 8 : NewChannels);
11081   SDVTList NewVTList = HasChain ?
11082     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11083 
11084 
11085   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11086                                               NewVTList, Ops);
11087 
11088   if (HasChain) {
11089     // Update chain.
11090     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11091     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11092   }
11093 
11094   if (NewChannels == 1) {
11095     assert(Node->hasNUsesOfValue(1, 0));
11096     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11097                                       SDLoc(Node), Users[Lane]->getValueType(0),
11098                                       SDValue(NewNode, 0));
11099     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11100     return nullptr;
11101   }
11102 
11103   // Update the users of the node with the new indices
11104   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11105     SDNode *User = Users[i];
11106     if (!User) {
11107       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11108       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11109       if (i || !NoChannels)
11110         continue;
11111     } else {
11112       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11113       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11114     }
11115 
11116     switch (Idx) {
11117     default: break;
11118     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11119     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11120     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11121     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11122     }
11123   }
11124 
11125   DAG.RemoveDeadNode(Node);
11126   return nullptr;
11127 }
11128 
11129 static bool isFrameIndexOp(SDValue Op) {
11130   if (Op.getOpcode() == ISD::AssertZext)
11131     Op = Op.getOperand(0);
11132 
11133   return isa<FrameIndexSDNode>(Op);
11134 }
11135 
11136 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11137 /// with frame index operands.
11138 /// LLVM assumes that inputs are to these instructions are registers.
11139 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11140                                                         SelectionDAG &DAG) const {
11141   if (Node->getOpcode() == ISD::CopyToReg) {
11142     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11143     SDValue SrcVal = Node->getOperand(2);
11144 
11145     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11146     // to try understanding copies to physical registers.
11147     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11148       SDLoc SL(Node);
11149       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11150       SDValue VReg = DAG.getRegister(
11151         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11152 
11153       SDNode *Glued = Node->getGluedNode();
11154       SDValue ToVReg
11155         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11156                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11157       SDValue ToResultReg
11158         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11159                            VReg, ToVReg.getValue(1));
11160       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11161       DAG.RemoveDeadNode(Node);
11162       return ToResultReg.getNode();
11163     }
11164   }
11165 
11166   SmallVector<SDValue, 8> Ops;
11167   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11168     if (!isFrameIndexOp(Node->getOperand(i))) {
11169       Ops.push_back(Node->getOperand(i));
11170       continue;
11171     }
11172 
11173     SDLoc DL(Node);
11174     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11175                                      Node->getOperand(i).getValueType(),
11176                                      Node->getOperand(i)), 0));
11177   }
11178 
11179   return DAG.UpdateNodeOperands(Node, Ops);
11180 }
11181 
11182 /// Fold the instructions after selecting them.
11183 /// Returns null if users were already updated.
11184 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11185                                           SelectionDAG &DAG) const {
11186   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11187   unsigned Opcode = Node->getMachineOpcode();
11188 
11189   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11190       !TII->isGather4(Opcode) &&
11191       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11192     return adjustWritemask(Node, DAG);
11193   }
11194 
11195   if (Opcode == AMDGPU::INSERT_SUBREG ||
11196       Opcode == AMDGPU::REG_SEQUENCE) {
11197     legalizeTargetIndependentNode(Node, DAG);
11198     return Node;
11199   }
11200 
11201   switch (Opcode) {
11202   case AMDGPU::V_DIV_SCALE_F32_e64:
11203   case AMDGPU::V_DIV_SCALE_F64_e64: {
11204     // Satisfy the operand register constraint when one of the inputs is
11205     // undefined. Ordinarily each undef value will have its own implicit_def of
11206     // a vreg, so force these to use a single register.
11207     SDValue Src0 = Node->getOperand(1);
11208     SDValue Src1 = Node->getOperand(3);
11209     SDValue Src2 = Node->getOperand(5);
11210 
11211     if ((Src0.isMachineOpcode() &&
11212          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11213         (Src0 == Src1 || Src0 == Src2))
11214       break;
11215 
11216     MVT VT = Src0.getValueType().getSimpleVT();
11217     const TargetRegisterClass *RC =
11218         getRegClassFor(VT, Src0.getNode()->isDivergent());
11219 
11220     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11221     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11222 
11223     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11224                                       UndefReg, Src0, SDValue());
11225 
11226     // src0 must be the same register as src1 or src2, even if the value is
11227     // undefined, so make sure we don't violate this constraint.
11228     if (Src0.isMachineOpcode() &&
11229         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11230       if (Src1.isMachineOpcode() &&
11231           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11232         Src0 = Src1;
11233       else if (Src2.isMachineOpcode() &&
11234                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11235         Src0 = Src2;
11236       else {
11237         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11238         Src0 = UndefReg;
11239         Src1 = UndefReg;
11240       }
11241     } else
11242       break;
11243 
11244     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11245     Ops[1] = Src0;
11246     Ops[3] = Src1;
11247     Ops[5] = Src2;
11248     Ops.push_back(ImpDef.getValue(1));
11249     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11250   }
11251   default:
11252     break;
11253   }
11254 
11255   return Node;
11256 }
11257 
11258 // Any MIMG instructions that use tfe or lwe require an initialization of the
11259 // result register that will be written in the case of a memory access failure.
11260 // The required code is also added to tie this init code to the result of the
11261 // img instruction.
11262 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11263   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11264   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11265   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11266   MachineBasicBlock &MBB = *MI.getParent();
11267 
11268   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11269   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11270   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11271 
11272   if (!TFE && !LWE) // intersect_ray
11273     return;
11274 
11275   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11276   unsigned LWEVal = LWE->getImm();
11277   unsigned D16Val = D16 ? D16->getImm() : 0;
11278 
11279   if (!TFEVal && !LWEVal)
11280     return;
11281 
11282   // At least one of TFE or LWE are non-zero
11283   // We have to insert a suitable initialization of the result value and
11284   // tie this to the dest of the image instruction.
11285 
11286   const DebugLoc &DL = MI.getDebugLoc();
11287 
11288   int DstIdx =
11289       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11290 
11291   // Calculate which dword we have to initialize to 0.
11292   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11293 
11294   // check that dmask operand is found.
11295   assert(MO_Dmask && "Expected dmask operand in instruction");
11296 
11297   unsigned dmask = MO_Dmask->getImm();
11298   // Determine the number of active lanes taking into account the
11299   // Gather4 special case
11300   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11301 
11302   bool Packed = !Subtarget->hasUnpackedD16VMem();
11303 
11304   unsigned InitIdx =
11305       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11306 
11307   // Abandon attempt if the dst size isn't large enough
11308   // - this is in fact an error but this is picked up elsewhere and
11309   // reported correctly.
11310   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11311   if (DstSize < InitIdx)
11312     return;
11313 
11314   // Create a register for the intialization value.
11315   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11316   unsigned NewDst = 0; // Final initialized value will be in here
11317 
11318   // If PRTStrictNull feature is enabled (the default) then initialize
11319   // all the result registers to 0, otherwise just the error indication
11320   // register (VGPRn+1)
11321   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11322   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11323 
11324   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11325   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11326     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11327     // Initialize dword
11328     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11329     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11330       .addImm(0);
11331     // Insert into the super-reg
11332     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11333       .addReg(PrevDst)
11334       .addReg(SubReg)
11335       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11336 
11337     PrevDst = NewDst;
11338   }
11339 
11340   // Add as an implicit operand
11341   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11342 
11343   // Tie the just added implicit operand to the dst
11344   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11345 }
11346 
11347 /// Assign the register class depending on the number of
11348 /// bits set in the writemask
11349 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11350                                                      SDNode *Node) const {
11351   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11352 
11353   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11354 
11355   if (TII->isVOP3(MI.getOpcode())) {
11356     // Make sure constant bus requirements are respected.
11357     TII->legalizeOperandsVOP3(MRI, MI);
11358 
11359     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11360     // This saves a chain-copy of registers and better ballance register
11361     // use between vgpr and agpr as agpr tuples tend to be big.
11362     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11363       unsigned Opc = MI.getOpcode();
11364       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11365       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11366                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11367         if (I == -1)
11368           break;
11369         MachineOperand &Op = MI.getOperand(I);
11370         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11371              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11372             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11373           continue;
11374         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11375         if (!Src || !Src->isCopy() ||
11376             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11377           continue;
11378         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11379         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11380         // All uses of agpr64 and agpr32 can also accept vgpr except for
11381         // v_accvgpr_read, but we do not produce agpr reads during selection,
11382         // so no use checks are needed.
11383         MRI.setRegClass(Op.getReg(), NewRC);
11384       }
11385     }
11386 
11387     return;
11388   }
11389 
11390   // Replace unused atomics with the no return version.
11391   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11392   if (NoRetAtomicOp != -1) {
11393     if (!Node->hasAnyUseOfValue(0)) {
11394       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11395                                                AMDGPU::OpName::cpol);
11396       if (CPolIdx != -1) {
11397         MachineOperand &CPol = MI.getOperand(CPolIdx);
11398         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11399       }
11400       MI.RemoveOperand(0);
11401       MI.setDesc(TII->get(NoRetAtomicOp));
11402       return;
11403     }
11404 
11405     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11406     // instruction, because the return type of these instructions is a vec2 of
11407     // the memory type, so it can be tied to the input operand.
11408     // This means these instructions always have a use, so we need to add a
11409     // special case to check if the atomic has only one extract_subreg use,
11410     // which itself has no uses.
11411     if ((Node->hasNUsesOfValue(1, 0) &&
11412          Node->use_begin()->isMachineOpcode() &&
11413          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11414          !Node->use_begin()->hasAnyUseOfValue(0))) {
11415       Register Def = MI.getOperand(0).getReg();
11416 
11417       // Change this into a noret atomic.
11418       MI.setDesc(TII->get(NoRetAtomicOp));
11419       MI.RemoveOperand(0);
11420 
11421       // If we only remove the def operand from the atomic instruction, the
11422       // extract_subreg will be left with a use of a vreg without a def.
11423       // So we need to insert an implicit_def to avoid machine verifier
11424       // errors.
11425       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11426               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11427     }
11428     return;
11429   }
11430 
11431   if (TII->isMIMG(MI) && !MI.mayStore())
11432     AddIMGInit(MI);
11433 }
11434 
11435 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11436                               uint64_t Val) {
11437   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11438   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11439 }
11440 
11441 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11442                                                 const SDLoc &DL,
11443                                                 SDValue Ptr) const {
11444   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11445 
11446   // Build the half of the subregister with the constants before building the
11447   // full 128-bit register. If we are building multiple resource descriptors,
11448   // this will allow CSEing of the 2-component register.
11449   const SDValue Ops0[] = {
11450     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11451     buildSMovImm32(DAG, DL, 0),
11452     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11453     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11454     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11455   };
11456 
11457   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11458                                                 MVT::v2i32, Ops0), 0);
11459 
11460   // Combine the constants and the pointer.
11461   const SDValue Ops1[] = {
11462     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11463     Ptr,
11464     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11465     SubRegHi,
11466     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11467   };
11468 
11469   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11470 }
11471 
11472 /// Return a resource descriptor with the 'Add TID' bit enabled
11473 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11474 ///        of the resource descriptor) to create an offset, which is added to
11475 ///        the resource pointer.
11476 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11477                                            SDValue Ptr, uint32_t RsrcDword1,
11478                                            uint64_t RsrcDword2And3) const {
11479   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11480   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11481   if (RsrcDword1) {
11482     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11483                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11484                     0);
11485   }
11486 
11487   SDValue DataLo = buildSMovImm32(DAG, DL,
11488                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11489   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11490 
11491   const SDValue Ops[] = {
11492     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11493     PtrLo,
11494     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11495     PtrHi,
11496     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11497     DataLo,
11498     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11499     DataHi,
11500     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11501   };
11502 
11503   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11504 }
11505 
11506 //===----------------------------------------------------------------------===//
11507 //                         SI Inline Assembly Support
11508 //===----------------------------------------------------------------------===//
11509 
11510 std::pair<unsigned, const TargetRegisterClass *>
11511 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11512                                                StringRef Constraint,
11513                                                MVT VT) const {
11514   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11515 
11516   const TargetRegisterClass *RC = nullptr;
11517   if (Constraint.size() == 1) {
11518     const unsigned BitWidth = VT.getSizeInBits();
11519     switch (Constraint[0]) {
11520     default:
11521       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11522     case 's':
11523     case 'r':
11524       switch (BitWidth) {
11525       case 16:
11526         RC = &AMDGPU::SReg_32RegClass;
11527         break;
11528       case 64:
11529         RC = &AMDGPU::SGPR_64RegClass;
11530         break;
11531       default:
11532         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11533         if (!RC)
11534           return std::make_pair(0U, nullptr);
11535         break;
11536       }
11537       break;
11538     case 'v':
11539       switch (BitWidth) {
11540       case 16:
11541         RC = &AMDGPU::VGPR_32RegClass;
11542         break;
11543       default:
11544         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11545         if (!RC)
11546           return std::make_pair(0U, nullptr);
11547         break;
11548       }
11549       break;
11550     case 'a':
11551       if (!Subtarget->hasMAIInsts())
11552         break;
11553       switch (BitWidth) {
11554       case 16:
11555         RC = &AMDGPU::AGPR_32RegClass;
11556         break;
11557       default:
11558         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11559         if (!RC)
11560           return std::make_pair(0U, nullptr);
11561         break;
11562       }
11563       break;
11564     }
11565     // We actually support i128, i16 and f16 as inline parameters
11566     // even if they are not reported as legal
11567     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11568                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11569       return std::make_pair(0U, RC);
11570   }
11571 
11572   if (Constraint.size() > 1) {
11573     if (Constraint[1] == 'v') {
11574       RC = &AMDGPU::VGPR_32RegClass;
11575     } else if (Constraint[1] == 's') {
11576       RC = &AMDGPU::SGPR_32RegClass;
11577     } else if (Constraint[1] == 'a') {
11578       RC = &AMDGPU::AGPR_32RegClass;
11579     }
11580 
11581     if (RC) {
11582       uint32_t Idx;
11583       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11584       if (!Failed && Idx < RC->getNumRegs())
11585         return std::make_pair(RC->getRegister(Idx), RC);
11586     }
11587   }
11588 
11589   // FIXME: Returns VS_32 for physical SGPR constraints
11590   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11591 }
11592 
11593 static bool isImmConstraint(StringRef Constraint) {
11594   if (Constraint.size() == 1) {
11595     switch (Constraint[0]) {
11596     default: break;
11597     case 'I':
11598     case 'J':
11599     case 'A':
11600     case 'B':
11601     case 'C':
11602       return true;
11603     }
11604   } else if (Constraint == "DA" ||
11605              Constraint == "DB") {
11606     return true;
11607   }
11608   return false;
11609 }
11610 
11611 SITargetLowering::ConstraintType
11612 SITargetLowering::getConstraintType(StringRef Constraint) const {
11613   if (Constraint.size() == 1) {
11614     switch (Constraint[0]) {
11615     default: break;
11616     case 's':
11617     case 'v':
11618     case 'a':
11619       return C_RegisterClass;
11620     }
11621   }
11622   if (isImmConstraint(Constraint)) {
11623     return C_Other;
11624   }
11625   return TargetLowering::getConstraintType(Constraint);
11626 }
11627 
11628 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11629   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11630     Val = Val & maskTrailingOnes<uint64_t>(Size);
11631   }
11632   return Val;
11633 }
11634 
11635 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11636                                                     std::string &Constraint,
11637                                                     std::vector<SDValue> &Ops,
11638                                                     SelectionDAG &DAG) const {
11639   if (isImmConstraint(Constraint)) {
11640     uint64_t Val;
11641     if (getAsmOperandConstVal(Op, Val) &&
11642         checkAsmConstraintVal(Op, Constraint, Val)) {
11643       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11644       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11645     }
11646   } else {
11647     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11648   }
11649 }
11650 
11651 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11652   unsigned Size = Op.getScalarValueSizeInBits();
11653   if (Size > 64)
11654     return false;
11655 
11656   if (Size == 16 && !Subtarget->has16BitInsts())
11657     return false;
11658 
11659   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11660     Val = C->getSExtValue();
11661     return true;
11662   }
11663   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11664     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11665     return true;
11666   }
11667   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11668     if (Size != 16 || Op.getNumOperands() != 2)
11669       return false;
11670     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11671       return false;
11672     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11673       Val = C->getSExtValue();
11674       return true;
11675     }
11676     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11677       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11678       return true;
11679     }
11680   }
11681 
11682   return false;
11683 }
11684 
11685 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11686                                              const std::string &Constraint,
11687                                              uint64_t Val) const {
11688   if (Constraint.size() == 1) {
11689     switch (Constraint[0]) {
11690     case 'I':
11691       return AMDGPU::isInlinableIntLiteral(Val);
11692     case 'J':
11693       return isInt<16>(Val);
11694     case 'A':
11695       return checkAsmConstraintValA(Op, Val);
11696     case 'B':
11697       return isInt<32>(Val);
11698     case 'C':
11699       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11700              AMDGPU::isInlinableIntLiteral(Val);
11701     default:
11702       break;
11703     }
11704   } else if (Constraint.size() == 2) {
11705     if (Constraint == "DA") {
11706       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11707       int64_t LoBits = static_cast<int32_t>(Val);
11708       return checkAsmConstraintValA(Op, HiBits, 32) &&
11709              checkAsmConstraintValA(Op, LoBits, 32);
11710     }
11711     if (Constraint == "DB") {
11712       return true;
11713     }
11714   }
11715   llvm_unreachable("Invalid asm constraint");
11716 }
11717 
11718 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11719                                               uint64_t Val,
11720                                               unsigned MaxSize) const {
11721   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11722   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11723   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11724       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11725       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11726     return true;
11727   }
11728   return false;
11729 }
11730 
11731 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11732   switch (UnalignedClassID) {
11733   case AMDGPU::VReg_64RegClassID:
11734     return AMDGPU::VReg_64_Align2RegClassID;
11735   case AMDGPU::VReg_96RegClassID:
11736     return AMDGPU::VReg_96_Align2RegClassID;
11737   case AMDGPU::VReg_128RegClassID:
11738     return AMDGPU::VReg_128_Align2RegClassID;
11739   case AMDGPU::VReg_160RegClassID:
11740     return AMDGPU::VReg_160_Align2RegClassID;
11741   case AMDGPU::VReg_192RegClassID:
11742     return AMDGPU::VReg_192_Align2RegClassID;
11743   case AMDGPU::VReg_224RegClassID:
11744     return AMDGPU::VReg_224_Align2RegClassID;
11745   case AMDGPU::VReg_256RegClassID:
11746     return AMDGPU::VReg_256_Align2RegClassID;
11747   case AMDGPU::VReg_512RegClassID:
11748     return AMDGPU::VReg_512_Align2RegClassID;
11749   case AMDGPU::VReg_1024RegClassID:
11750     return AMDGPU::VReg_1024_Align2RegClassID;
11751   case AMDGPU::AReg_64RegClassID:
11752     return AMDGPU::AReg_64_Align2RegClassID;
11753   case AMDGPU::AReg_96RegClassID:
11754     return AMDGPU::AReg_96_Align2RegClassID;
11755   case AMDGPU::AReg_128RegClassID:
11756     return AMDGPU::AReg_128_Align2RegClassID;
11757   case AMDGPU::AReg_160RegClassID:
11758     return AMDGPU::AReg_160_Align2RegClassID;
11759   case AMDGPU::AReg_192RegClassID:
11760     return AMDGPU::AReg_192_Align2RegClassID;
11761   case AMDGPU::AReg_256RegClassID:
11762     return AMDGPU::AReg_256_Align2RegClassID;
11763   case AMDGPU::AReg_512RegClassID:
11764     return AMDGPU::AReg_512_Align2RegClassID;
11765   case AMDGPU::AReg_1024RegClassID:
11766     return AMDGPU::AReg_1024_Align2RegClassID;
11767   default:
11768     return -1;
11769   }
11770 }
11771 
11772 // Figure out which registers should be reserved for stack access. Only after
11773 // the function is legalized do we know all of the non-spill stack objects or if
11774 // calls are present.
11775 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11776   MachineRegisterInfo &MRI = MF.getRegInfo();
11777   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11778   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11779   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11780   const SIInstrInfo *TII = ST.getInstrInfo();
11781 
11782   if (Info->isEntryFunction()) {
11783     // Callable functions have fixed registers used for stack access.
11784     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11785   }
11786 
11787   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11788                              Info->getStackPtrOffsetReg()));
11789   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11790     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11791 
11792   // We need to worry about replacing the default register with itself in case
11793   // of MIR testcases missing the MFI.
11794   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11795     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11796 
11797   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11798     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11799 
11800   Info->limitOccupancy(MF);
11801 
11802   if (ST.isWave32() && !MF.empty()) {
11803     for (auto &MBB : MF) {
11804       for (auto &MI : MBB) {
11805         TII->fixImplicitOperands(MI);
11806       }
11807     }
11808   }
11809 
11810   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11811   // classes if required. Ideally the register class constraints would differ
11812   // per-subtarget, but there's no easy way to achieve that right now. This is
11813   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11814   // from using them as the register class for legal types.
11815   if (ST.needsAlignedVGPRs()) {
11816     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11817       const Register Reg = Register::index2VirtReg(I);
11818       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11819       if (!RC)
11820         continue;
11821       int NewClassID = getAlignedAGPRClassID(RC->getID());
11822       if (NewClassID != -1)
11823         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11824     }
11825   }
11826 
11827   TargetLoweringBase::finalizeLowering(MF);
11828 
11829   // Allocate a VGPR for future SGPR Spill if
11830   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11831   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11832   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11833       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11834     Info->reserveVGPRforSGPRSpills(MF);
11835 }
11836 
11837 void SITargetLowering::computeKnownBitsForFrameIndex(
11838   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11839   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11840 
11841   // Set the high bits to zero based on the maximum allowed scratch size per
11842   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11843   // calculation won't overflow, so assume the sign bit is never set.
11844   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11845 }
11846 
11847 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11848                                    KnownBits &Known, unsigned Dim) {
11849   unsigned MaxValue =
11850       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11851   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11852 }
11853 
11854 void SITargetLowering::computeKnownBitsForTargetInstr(
11855     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11856     const MachineRegisterInfo &MRI, unsigned Depth) const {
11857   const MachineInstr *MI = MRI.getVRegDef(R);
11858   switch (MI->getOpcode()) {
11859   case AMDGPU::G_INTRINSIC: {
11860     switch (MI->getIntrinsicID()) {
11861     case Intrinsic::amdgcn_workitem_id_x:
11862       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11863       break;
11864     case Intrinsic::amdgcn_workitem_id_y:
11865       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11866       break;
11867     case Intrinsic::amdgcn_workitem_id_z:
11868       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11869       break;
11870     case Intrinsic::amdgcn_mbcnt_lo:
11871     case Intrinsic::amdgcn_mbcnt_hi: {
11872       // These return at most the wavefront size - 1.
11873       unsigned Size = MRI.getType(R).getSizeInBits();
11874       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11875       break;
11876     }
11877     case Intrinsic::amdgcn_groupstaticsize: {
11878       // We can report everything over the maximum size as 0. We can't report
11879       // based on the actual size because we don't know if it's accurate or not
11880       // at any given point.
11881       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11882       break;
11883     }
11884     }
11885     break;
11886   }
11887   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11888     Known.Zero.setHighBits(24);
11889     break;
11890   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11891     Known.Zero.setHighBits(16);
11892     break;
11893   }
11894 }
11895 
11896 Align SITargetLowering::computeKnownAlignForTargetInstr(
11897   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11898   unsigned Depth) const {
11899   const MachineInstr *MI = MRI.getVRegDef(R);
11900   switch (MI->getOpcode()) {
11901   case AMDGPU::G_INTRINSIC:
11902   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11903     // FIXME: Can this move to generic code? What about the case where the call
11904     // site specifies a lower alignment?
11905     Intrinsic::ID IID = MI->getIntrinsicID();
11906     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11907     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11908     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11909       return *RetAlign;
11910     return Align(1);
11911   }
11912   default:
11913     return Align(1);
11914   }
11915 }
11916 
11917 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11918   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11919   const Align CacheLineAlign = Align(64);
11920 
11921   // Pre-GFX10 target did not benefit from loop alignment
11922   if (!ML || DisableLoopAlignment ||
11923       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11924       getSubtarget()->hasInstFwdPrefetchBug())
11925     return PrefAlign;
11926 
11927   // On GFX10 I$ is 4 x 64 bytes cache lines.
11928   // By default prefetcher keeps one cache line behind and reads two ahead.
11929   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11930   // behind and one ahead.
11931   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11932   // If loop fits 64 bytes it always spans no more than two cache lines and
11933   // does not need an alignment.
11934   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11935   // Else if loop is less or equal 192 bytes we need two lines behind.
11936 
11937   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11938   const MachineBasicBlock *Header = ML->getHeader();
11939   if (Header->getAlignment() != PrefAlign)
11940     return Header->getAlignment(); // Already processed.
11941 
11942   unsigned LoopSize = 0;
11943   for (const MachineBasicBlock *MBB : ML->blocks()) {
11944     // If inner loop block is aligned assume in average half of the alignment
11945     // size to be added as nops.
11946     if (MBB != Header)
11947       LoopSize += MBB->getAlignment().value() / 2;
11948 
11949     for (const MachineInstr &MI : *MBB) {
11950       LoopSize += TII->getInstSizeInBytes(MI);
11951       if (LoopSize > 192)
11952         return PrefAlign;
11953     }
11954   }
11955 
11956   if (LoopSize <= 64)
11957     return PrefAlign;
11958 
11959   if (LoopSize <= 128)
11960     return CacheLineAlign;
11961 
11962   // If any of parent loops is surrounded by prefetch instructions do not
11963   // insert new for inner loop, which would reset parent's settings.
11964   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11965     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11966       auto I = Exit->getFirstNonDebugInstr();
11967       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11968         return CacheLineAlign;
11969     }
11970   }
11971 
11972   MachineBasicBlock *Pre = ML->getLoopPreheader();
11973   MachineBasicBlock *Exit = ML->getExitBlock();
11974 
11975   if (Pre && Exit) {
11976     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11977             TII->get(AMDGPU::S_INST_PREFETCH))
11978       .addImm(1); // prefetch 2 lines behind PC
11979 
11980     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11981             TII->get(AMDGPU::S_INST_PREFETCH))
11982       .addImm(2); // prefetch 1 line behind PC
11983   }
11984 
11985   return CacheLineAlign;
11986 }
11987 
11988 LLVM_ATTRIBUTE_UNUSED
11989 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11990   assert(N->getOpcode() == ISD::CopyFromReg);
11991   do {
11992     // Follow the chain until we find an INLINEASM node.
11993     N = N->getOperand(0).getNode();
11994     if (N->getOpcode() == ISD::INLINEASM ||
11995         N->getOpcode() == ISD::INLINEASM_BR)
11996       return true;
11997   } while (N->getOpcode() == ISD::CopyFromReg);
11998   return false;
11999 }
12000 
12001 bool SITargetLowering::isSDNodeSourceOfDivergence(
12002     const SDNode *N, FunctionLoweringInfo *FLI,
12003     LegacyDivergenceAnalysis *KDA) const {
12004   switch (N->getOpcode()) {
12005   case ISD::CopyFromReg: {
12006     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12007     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12008     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12009     Register Reg = R->getReg();
12010 
12011     // FIXME: Why does this need to consider isLiveIn?
12012     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12013       return !TRI->isSGPRReg(MRI, Reg);
12014 
12015     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12016       return KDA->isDivergent(V);
12017 
12018     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12019     return !TRI->isSGPRReg(MRI, Reg);
12020   }
12021   case ISD::LOAD: {
12022     const LoadSDNode *L = cast<LoadSDNode>(N);
12023     unsigned AS = L->getAddressSpace();
12024     // A flat load may access private memory.
12025     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12026   }
12027   case ISD::CALLSEQ_END:
12028     return true;
12029   case ISD::INTRINSIC_WO_CHAIN:
12030     return AMDGPU::isIntrinsicSourceOfDivergence(
12031         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12032   case ISD::INTRINSIC_W_CHAIN:
12033     return AMDGPU::isIntrinsicSourceOfDivergence(
12034         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12035   case AMDGPUISD::ATOMIC_CMP_SWAP:
12036   case AMDGPUISD::ATOMIC_INC:
12037   case AMDGPUISD::ATOMIC_DEC:
12038   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12039   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12040   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12041   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12042   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12043   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12044   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12045   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12046   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12047   case AMDGPUISD::BUFFER_ATOMIC_AND:
12048   case AMDGPUISD::BUFFER_ATOMIC_OR:
12049   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12050   case AMDGPUISD::BUFFER_ATOMIC_INC:
12051   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12052   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12053   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12054   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12055   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12056   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12057     // Target-specific read-modify-write atomics are sources of divergence.
12058     return true;
12059   default:
12060     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12061       // Generic read-modify-write atomics are sources of divergence.
12062       return A->readMem() && A->writeMem();
12063     }
12064     return false;
12065   }
12066 }
12067 
12068 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12069                                                EVT VT) const {
12070   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12071   case MVT::f32:
12072     return hasFP32Denormals(DAG.getMachineFunction());
12073   case MVT::f64:
12074   case MVT::f16:
12075     return hasFP64FP16Denormals(DAG.getMachineFunction());
12076   default:
12077     return false;
12078   }
12079 }
12080 
12081 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12082                                                MachineFunction &MF) const {
12083   switch (Ty.getScalarSizeInBits()) {
12084   case 32:
12085     return hasFP32Denormals(MF);
12086   case 64:
12087   case 16:
12088     return hasFP64FP16Denormals(MF);
12089   default:
12090     return false;
12091   }
12092 }
12093 
12094 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12095                                                     const SelectionDAG &DAG,
12096                                                     bool SNaN,
12097                                                     unsigned Depth) const {
12098   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12099     const MachineFunction &MF = DAG.getMachineFunction();
12100     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12101 
12102     if (Info->getMode().DX10Clamp)
12103       return true; // Clamped to 0.
12104     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12105   }
12106 
12107   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12108                                                             SNaN, Depth);
12109 }
12110 
12111 // Global FP atomic instructions have a hardcoded FP mode and do not support
12112 // FP32 denormals, and only support v2f16 denormals.
12113 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12114   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12115   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12116   if (&Flt == &APFloat::IEEEsingle())
12117     return DenormMode == DenormalMode::getPreserveSign();
12118   return DenormMode == DenormalMode::getIEEE();
12119 }
12120 
12121 TargetLowering::AtomicExpansionKind
12122 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12123   switch (RMW->getOperation()) {
12124   case AtomicRMWInst::FAdd: {
12125     Type *Ty = RMW->getType();
12126 
12127     // We don't have a way to support 16-bit atomics now, so just leave them
12128     // as-is.
12129     if (Ty->isHalfTy())
12130       return AtomicExpansionKind::None;
12131 
12132     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12133       return AtomicExpansionKind::CmpXChg;
12134 
12135     unsigned AS = RMW->getPointerAddressSpace();
12136 
12137     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12138          Subtarget->hasAtomicFaddInsts()) {
12139       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12140       // floating point atomic instructions. May generate more efficient code,
12141       // but may not respect rounding and denormal modes, and may give incorrect
12142       // results for certain memory destinations.
12143       if (RMW->getFunction()
12144               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12145               .getValueAsString() != "true")
12146         return AtomicExpansionKind::CmpXChg;
12147 
12148       if (Subtarget->hasGFX90AInsts()) {
12149         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12150           return AtomicExpansionKind::CmpXChg;
12151 
12152         auto SSID = RMW->getSyncScopeID();
12153         if (SSID == SyncScope::System ||
12154             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12155           return AtomicExpansionKind::CmpXChg;
12156 
12157         return AtomicExpansionKind::None;
12158       }
12159 
12160       if (AS == AMDGPUAS::FLAT_ADDRESS)
12161         return AtomicExpansionKind::CmpXChg;
12162 
12163       return RMW->use_empty() ? AtomicExpansionKind::None
12164                               : AtomicExpansionKind::CmpXChg;
12165     }
12166 
12167     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12168     // to round-to-nearest-even.
12169     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12170     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
12171       if (!Ty->isDoubleTy())
12172         return AtomicExpansionKind::None;
12173 
12174       return (fpModeMatchesGlobalFPAtomicMode(RMW) ||
12175               RMW->getFunction()
12176                       ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12177                       .getValueAsString() == "true")
12178                  ? AtomicExpansionKind::None
12179                  : AtomicExpansionKind::CmpXChg;
12180     }
12181 
12182     return AtomicExpansionKind::CmpXChg;
12183   }
12184   default:
12185     break;
12186   }
12187 
12188   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12189 }
12190 
12191 const TargetRegisterClass *
12192 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12193   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12194   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12195   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12196     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12197                                                : &AMDGPU::SReg_32RegClass;
12198   if (!TRI->isSGPRClass(RC) && !isDivergent)
12199     return TRI->getEquivalentSGPRClass(RC);
12200   else if (TRI->isSGPRClass(RC) && isDivergent)
12201     return TRI->getEquivalentVGPRClass(RC);
12202 
12203   return RC;
12204 }
12205 
12206 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12207 // uniform values (as produced by the mask results of control flow intrinsics)
12208 // used outside of divergent blocks. The phi users need to also be treated as
12209 // always uniform.
12210 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12211                       unsigned WaveSize) {
12212   // FIXME: We asssume we never cast the mask results of a control flow
12213   // intrinsic.
12214   // Early exit if the type won't be consistent as a compile time hack.
12215   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12216   if (!IT || IT->getBitWidth() != WaveSize)
12217     return false;
12218 
12219   if (!isa<Instruction>(V))
12220     return false;
12221   if (!Visited.insert(V).second)
12222     return false;
12223   bool Result = false;
12224   for (auto U : V->users()) {
12225     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12226       if (V == U->getOperand(1)) {
12227         switch (Intrinsic->getIntrinsicID()) {
12228         default:
12229           Result = false;
12230           break;
12231         case Intrinsic::amdgcn_if_break:
12232         case Intrinsic::amdgcn_if:
12233         case Intrinsic::amdgcn_else:
12234           Result = true;
12235           break;
12236         }
12237       }
12238       if (V == U->getOperand(0)) {
12239         switch (Intrinsic->getIntrinsicID()) {
12240         default:
12241           Result = false;
12242           break;
12243         case Intrinsic::amdgcn_end_cf:
12244         case Intrinsic::amdgcn_loop:
12245           Result = true;
12246           break;
12247         }
12248       }
12249     } else {
12250       Result = hasCFUser(U, Visited, WaveSize);
12251     }
12252     if (Result)
12253       break;
12254   }
12255   return Result;
12256 }
12257 
12258 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12259                                                const Value *V) const {
12260   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12261     if (CI->isInlineAsm()) {
12262       // FIXME: This cannot give a correct answer. This should only trigger in
12263       // the case where inline asm returns mixed SGPR and VGPR results, used
12264       // outside the defining block. We don't have a specific result to
12265       // consider, so this assumes if any value is SGPR, the overall register
12266       // also needs to be SGPR.
12267       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12268       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12269           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12270       for (auto &TC : TargetConstraints) {
12271         if (TC.Type == InlineAsm::isOutput) {
12272           ComputeConstraintToUse(TC, SDValue());
12273           unsigned AssignedReg;
12274           const TargetRegisterClass *RC;
12275           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12276               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12277           if (RC) {
12278             MachineRegisterInfo &MRI = MF.getRegInfo();
12279             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12280               return true;
12281             else if (SIRI->isSGPRClass(RC))
12282               return true;
12283           }
12284         }
12285       }
12286     }
12287   }
12288   SmallPtrSet<const Value *, 16> Visited;
12289   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12290 }
12291 
12292 std::pair<InstructionCost, MVT>
12293 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12294                                           Type *Ty) const {
12295   std::pair<InstructionCost, MVT> Cost =
12296       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12297   auto Size = DL.getTypeSizeInBits(Ty);
12298   // Maximum load or store can handle 8 dwords for scalar and 4 for
12299   // vector ALU. Let's assume anything above 8 dwords is expensive
12300   // even if legal.
12301   if (Size <= 256)
12302     return Cost;
12303 
12304   Cost.first = (Size + 255) / 256;
12305   return Cost;
12306 }
12307