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/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/IntrinsicsAMDGPU.h"
33 #include "llvm/IR/IntrinsicsR600.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "si-lower"
40 
41 STATISTIC(NumTailCalls, "Number of tail calls");
42 
43 static cl::opt<bool> DisableLoopAlignment(
44   "amdgpu-disable-loop-alignment",
45   cl::desc("Do not align and prefetch loops"),
46   cl::init(false));
47 
48 static cl::opt<bool> VGPRReserveforSGPRSpill(
49     "amdgpu-reserve-vgpr-for-sgpr-spill",
50     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
51 
52 static cl::opt<bool> UseDivergentRegisterIndexing(
53   "amdgpu-use-divergent-register-indexing",
54   cl::Hidden,
55   cl::desc("Use indirect register addressing for divergent indexes"),
56   cl::init(false));
57 
58 static bool hasFP32Denormals(const MachineFunction &MF) {
59   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
60   return Info->getMode().allFP32Denormals();
61 }
62 
63 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
64   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
65   return Info->getMode().allFP64FP16Denormals();
66 }
67 
68 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
69   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
70   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
71     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
72       return AMDGPU::SGPR0 + Reg;
73     }
74   }
75   llvm_unreachable("Cannot allocate sgpr");
76 }
77 
78 SITargetLowering::SITargetLowering(const TargetMachine &TM,
79                                    const GCNSubtarget &STI)
80     : AMDGPUTargetLowering(TM, STI),
81       Subtarget(&STI) {
82   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
83   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
84 
85   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
86   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
87 
88   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
89 
90   const SIRegisterInfo *TRI = STI.getRegisterInfo();
91   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
92 
93   addRegisterClass(MVT::f64, V64RegClass);
94   addRegisterClass(MVT::v2f32, V64RegClass);
95 
96   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
97   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
98 
99   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
100   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
101 
102   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
103   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
104 
105   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
106   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
107 
108   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
109   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
110 
111   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
112   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
113 
114   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
115   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
116 
117   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
118   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
119 
120   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
121   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
122 
123   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
124   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
125 
126   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
127   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
128 
129   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
130   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
131 
132   if (Subtarget->has16BitInsts()) {
133     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
134     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
135 
136     // Unless there are also VOP3P operations, not operations are really legal.
137     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
138     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
139     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
140     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
141   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::i1, Custom);
165   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
166 
167   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
175   setOperationAction(ISD::STORE, MVT::i1, Custom);
176   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
177 
178   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
179   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
180   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
181   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
183   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
184   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
185   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
186   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
187   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
188   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
189   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
190   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
191   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
192   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
193   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
194 
195   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
197   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
200   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
201   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
202 
203   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
204   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
205 
206   setOperationAction(ISD::SELECT, MVT::i1, Promote);
207   setOperationAction(ISD::SELECT, MVT::i64, Custom);
208   setOperationAction(ISD::SELECT, MVT::f64, Promote);
209   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
210 
211   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
216 
217   setOperationAction(ISD::SETCC, MVT::i1, Promote);
218   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
219   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
220   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
221 
222   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
236   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
237   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
238 
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
246   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
247 
248   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
253   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
254 
255   setOperationAction(ISD::UADDO, MVT::i32, Legal);
256   setOperationAction(ISD::USUBO, MVT::i32, Legal);
257 
258   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
259   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
260 
261   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
263   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
264 
265 #if 0
266   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
267   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
268 #endif
269 
270   // We only support LOAD/STORE and vector manipulation ops for vectors
271   // with > 4 elements.
272   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
273                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
274                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
275                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
276                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
277     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
278       switch (Op) {
279       case ISD::LOAD:
280       case ISD::STORE:
281       case ISD::BUILD_VECTOR:
282       case ISD::BITCAST:
283       case ISD::EXTRACT_VECTOR_ELT:
284       case ISD::INSERT_VECTOR_ELT:
285       case ISD::EXTRACT_SUBVECTOR:
286       case ISD::SCALAR_TO_VECTOR:
287         break;
288       case ISD::INSERT_SUBVECTOR:
289       case ISD::CONCAT_VECTORS:
290         setOperationAction(Op, VT, Custom);
291         break;
292       default:
293         setOperationAction(Op, VT, Expand);
294         break;
295       }
296     }
297   }
298 
299   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
300 
301   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
302   // is expanded to avoid having two separate loops in case the index is a VGPR.
303 
304   // Most operations are naturally 32-bit vector operations. We only support
305   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
306   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
307     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
308     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
309 
310     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
312 
313     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
314     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
315 
316     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
318   }
319 
320   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
321     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
322     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
323 
324     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
326 
327     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
329 
330     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
332   }
333 
334   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
335     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
337 
338     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
339     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
345     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
346   }
347 
348   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
349     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
351 
352     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
353     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
359     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
360   }
361 
362   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
363     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
365 
366     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
367     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
373     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
374   }
375 
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
380 
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
382   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
383 
384   // Avoid stack access for these.
385   // TODO: Generalize to more vector types.
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
390 
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
397 
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
402 
403   // Deal with vec3 vector operations when widened to vec4.
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
408 
409   // Deal with vec5/6/7 vector operations when widened to vec8.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
418 
419   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
420   // and output demarshalling
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
423 
424   // We can't return success/failure, only the old value,
425   // let LLVM add the comparison
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
428 
429   if (Subtarget->hasFlatAddressSpace()) {
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
432   }
433 
434   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
435   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
436 
437   // FIXME: This should be narrowed to i32, but that only happens if i64 is
438   // illegal.
439   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
440   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
441   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
442 
443   // On SI this is s_memtime and s_memrealtime on VI.
444   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
445   setOperationAction(ISD::TRAP, MVT::Other, Custom);
446   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
447 
448   if (Subtarget->has16BitInsts()) {
449     setOperationAction(ISD::FPOW, MVT::f16, Promote);
450     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   if (Subtarget->hasMadMacF32Insts())
457     setOperationAction(ISD::FMAD, MVT::f32, Legal);
458 
459   if (!Subtarget->hasBFI()) {
460     // fcopysign can be done in a single instruction with BFI.
461     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
462     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
463   }
464 
465   if (!Subtarget->hasBCNT(32))
466     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
467 
468   if (!Subtarget->hasBCNT(64))
469     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
470 
471   if (Subtarget->hasFFBH()) {
472     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
474   }
475 
476   if (Subtarget->hasFFBL()) {
477     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479   }
480 
481   // We only really have 32-bit BFE instructions (and 16-bit on VI).
482   //
483   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
484   // effort to match them now. We want this to be false for i64 cases when the
485   // extraction isn't restricted to the upper or lower half. Ideally we would
486   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
487   // span the midpoint are probably relatively rare, so don't worry about them
488   // for now.
489   if (Subtarget->hasBFE())
490     setHasExtractBitsInsn(true);
491 
492   // Clamp modifier on add/sub
493   if (Subtarget->hasIntClamp()) {
494     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
495     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
496   }
497 
498   if (Subtarget->hasAddNoCarry()) {
499     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
501     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
502     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
503   }
504 
505   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
507   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
508   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
509 
510 
511   // These are really only legal for ieee_mode functions. We should be avoiding
512   // them for functions that don't have ieee_mode enabled, so just say they are
513   // legal.
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
516   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
517   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
518 
519 
520   if (Subtarget->haveRoundOpsF64()) {
521     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
522     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
523     setOperationAction(ISD::FRINT, MVT::f64, Legal);
524   } else {
525     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
526     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
527     setOperationAction(ISD::FRINT, MVT::f64, Custom);
528     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
529   }
530 
531   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
532 
533   setOperationAction(ISD::FSIN, MVT::f32, Custom);
534   setOperationAction(ISD::FCOS, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f32, Custom);
536   setOperationAction(ISD::FDIV, MVT::f64, Custom);
537 
538   if (Subtarget->has16BitInsts()) {
539     setOperationAction(ISD::Constant, MVT::i16, Legal);
540 
541     setOperationAction(ISD::SMIN, MVT::i16, Legal);
542     setOperationAction(ISD::SMAX, MVT::i16, Legal);
543 
544     setOperationAction(ISD::UMIN, MVT::i16, Legal);
545     setOperationAction(ISD::UMAX, MVT::i16, Legal);
546 
547     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
548     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
549 
550     setOperationAction(ISD::ROTR, MVT::i16, Expand);
551     setOperationAction(ISD::ROTL, MVT::i16, Expand);
552 
553     setOperationAction(ISD::SDIV, MVT::i16, Promote);
554     setOperationAction(ISD::UDIV, MVT::i16, Promote);
555     setOperationAction(ISD::SREM, MVT::i16, Promote);
556     setOperationAction(ISD::UREM, MVT::i16, Promote);
557     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
558     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
559 
560     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
561 
562     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
565     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
566     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
567 
568     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
571 
572     setOperationAction(ISD::LOAD, MVT::i16, Custom);
573 
574     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
575 
576     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
578     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
579     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
580 
581     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
582     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
583 
584     // F16 - Constant Actions.
585     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
586 
587     // F16 - Load/Store Actions.
588     setOperationAction(ISD::LOAD, MVT::f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
590     setOperationAction(ISD::STORE, MVT::f16, Promote);
591     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
592 
593     // F16 - VOP1 Actions.
594     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
595     setOperationAction(ISD::FCOS, MVT::f16, Custom);
596     setOperationAction(ISD::FSIN, MVT::f16, Custom);
597 
598     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
599     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
600 
601     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
602     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
603     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
605     setOperationAction(ISD::FROUND, MVT::f16, Custom);
606 
607     // F16 - VOP2 Actions.
608     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
609     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
610 
611     setOperationAction(ISD::FDIV, MVT::f16, Custom);
612 
613     // F16 - VOP3 Actions.
614     setOperationAction(ISD::FMA, MVT::f16, Legal);
615     if (STI.hasMadF16())
616       setOperationAction(ISD::FMAD, MVT::f16, Legal);
617 
618     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
619       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
620         switch (Op) {
621         case ISD::LOAD:
622         case ISD::STORE:
623         case ISD::BUILD_VECTOR:
624         case ISD::BITCAST:
625         case ISD::EXTRACT_VECTOR_ELT:
626         case ISD::INSERT_VECTOR_ELT:
627         case ISD::INSERT_SUBVECTOR:
628         case ISD::EXTRACT_SUBVECTOR:
629         case ISD::SCALAR_TO_VECTOR:
630           break;
631         case ISD::CONCAT_VECTORS:
632           setOperationAction(Op, VT, Custom);
633           break;
634         default:
635           setOperationAction(Op, VT, Expand);
636           break;
637         }
638       }
639     }
640 
641     // v_perm_b32 can handle either of these.
642     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
644     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
645 
646     // XXX - Do these do anything? Vector constants turn into build_vector.
647     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
648     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
651     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
655     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
657 
658     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
660     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
662 
663     setOperationAction(ISD::AND, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::OR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
669 
670     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
672     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
674 
675     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
677     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
679 
680     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
683     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
684 
685     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
687     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
688 
689     if (!Subtarget->hasVOP3PInsts()) {
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
691       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
692     }
693 
694     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
695     // This isn't really legal, but this avoids the legalizer unrolling it (and
696     // allows matching fneg (fabs x) patterns)
697     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
698 
699     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
701     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
703 
704     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
705     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
706 
707     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
708     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
709   }
710 
711   if (Subtarget->hasVOP3PInsts()) {
712     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
713     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
714     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
717     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
720     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
721     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
722 
723     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
726     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
727 
728     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
730     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
731 
732     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
733     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
736 
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
738     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
739 
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
741     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
742 
743     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
745     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
746     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
747     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
748     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
749 
750     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
753     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
754 
755     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
758     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
759 
760     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
762     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
763 
764     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
765     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
766 
767     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
769     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
770 
771     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
773     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
774 
775     if (Subtarget->hasPackedFP32Ops()) {
776       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
777       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
778       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
779       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
780 
781       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
782         setOperationAction(ISD::FADD, VT, Custom);
783         setOperationAction(ISD::FMUL, VT, Custom);
784         setOperationAction(ISD::FMA, VT, Custom);
785       }
786     }
787   }
788 
789   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
790   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
791 
792   if (Subtarget->has16BitInsts()) {
793     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
794     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
795     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
796     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
797   } else {
798     // Legalization hack.
799     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
800     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
801 
802     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
803     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
804   }
805 
806   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
807     setOperationAction(ISD::SELECT, VT, Custom);
808   }
809 
810   setOperationAction(ISD::SMULO, MVT::i64, Custom);
811   setOperationAction(ISD::UMULO, MVT::i64, Custom);
812 
813   if (Subtarget->hasMad64_32()) {
814     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
815     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
816   }
817 
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
819   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
820   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
822   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
823   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
825 
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
831   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
832   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
833   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
834   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
835   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
836   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
837 
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
842   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
843   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
844   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
845   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
846   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
847   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
848 
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::ADDCARRY);
851   setTargetDAGCombine(ISD::SUB);
852   setTargetDAGCombine(ISD::SUBCARRY);
853   setTargetDAGCombine(ISD::FADD);
854   setTargetDAGCombine(ISD::FSUB);
855   setTargetDAGCombine(ISD::FMINNUM);
856   setTargetDAGCombine(ISD::FMAXNUM);
857   setTargetDAGCombine(ISD::FMINNUM_IEEE);
858   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
859   setTargetDAGCombine(ISD::FMA);
860   setTargetDAGCombine(ISD::SMIN);
861   setTargetDAGCombine(ISD::SMAX);
862   setTargetDAGCombine(ISD::UMIN);
863   setTargetDAGCombine(ISD::UMAX);
864   setTargetDAGCombine(ISD::SETCC);
865   setTargetDAGCombine(ISD::AND);
866   setTargetDAGCombine(ISD::OR);
867   setTargetDAGCombine(ISD::XOR);
868   setTargetDAGCombine(ISD::SINT_TO_FP);
869   setTargetDAGCombine(ISD::UINT_TO_FP);
870   setTargetDAGCombine(ISD::FCANONICALIZE);
871   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
872   setTargetDAGCombine(ISD::ZERO_EXTEND);
873   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
874   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
875   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
876 
877   // All memory operations. Some folding on the pointer operand is done to help
878   // matching the constant offsets in the addressing modes.
879   setTargetDAGCombine(ISD::LOAD);
880   setTargetDAGCombine(ISD::STORE);
881   setTargetDAGCombine(ISD::ATOMIC_LOAD);
882   setTargetDAGCombine(ISD::ATOMIC_STORE);
883   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
884   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
885   setTargetDAGCombine(ISD::ATOMIC_SWAP);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
891   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
892   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
893   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
894   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
895   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
896   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
897   setTargetDAGCombine(ISD::INTRINSIC_VOID);
898   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
899 
900   // FIXME: In other contexts we pretend this is a per-function property.
901   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
902 
903   setSchedulingPreference(Sched::RegPressure);
904 }
905 
906 const GCNSubtarget *SITargetLowering::getSubtarget() const {
907   return Subtarget;
908 }
909 
910 //===----------------------------------------------------------------------===//
911 // TargetLowering queries
912 //===----------------------------------------------------------------------===//
913 
914 // v_mad_mix* support a conversion from f16 to f32.
915 //
916 // There is only one special case when denormals are enabled we don't currently,
917 // where this is OK to use.
918 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
919                                        EVT DestVT, EVT SrcVT) const {
920   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
921           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
922     DestVT.getScalarType() == MVT::f32 &&
923     SrcVT.getScalarType() == MVT::f16 &&
924     // TODO: This probably only requires no input flushing?
925     !hasFP32Denormals(DAG.getMachineFunction());
926 }
927 
928 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
929                                        LLT DestTy, LLT SrcTy) const {
930   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
931           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
932          DestTy.getScalarSizeInBits() == 32 &&
933          SrcTy.getScalarSizeInBits() == 16 &&
934          // TODO: This probably only requires no input flushing?
935          !hasFP32Denormals(*MI.getMF());
936 }
937 
938 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
939   // SI has some legal vector types, but no legal vector operations. Say no
940   // shuffles are legal in order to prefer scalarizing some vector operations.
941   return false;
942 }
943 
944 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
945                                                     CallingConv::ID CC,
946                                                     EVT VT) const {
947   if (CC == CallingConv::AMDGPU_KERNEL)
948     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
949 
950   if (VT.isVector()) {
951     EVT ScalarVT = VT.getScalarType();
952     unsigned Size = ScalarVT.getSizeInBits();
953     if (Size == 16) {
954       if (Subtarget->has16BitInsts())
955         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
956       return VT.isInteger() ? MVT::i32 : MVT::f32;
957     }
958 
959     if (Size < 16)
960       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
961     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
962   }
963 
964   if (VT.getSizeInBits() > 32)
965     return MVT::i32;
966 
967   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
968 }
969 
970 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
971                                                          CallingConv::ID CC,
972                                                          EVT VT) const {
973   if (CC == CallingConv::AMDGPU_KERNEL)
974     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
975 
976   if (VT.isVector()) {
977     unsigned NumElts = VT.getVectorNumElements();
978     EVT ScalarVT = VT.getScalarType();
979     unsigned Size = ScalarVT.getSizeInBits();
980 
981     // FIXME: Should probably promote 8-bit vectors to i16.
982     if (Size == 16 && Subtarget->has16BitInsts())
983       return (NumElts + 1) / 2;
984 
985     if (Size <= 32)
986       return NumElts;
987 
988     if (Size > 32)
989       return NumElts * ((Size + 31) / 32);
990   } else if (VT.getSizeInBits() > 32)
991     return (VT.getSizeInBits() + 31) / 32;
992 
993   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
994 }
995 
996 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
997   LLVMContext &Context, CallingConv::ID CC,
998   EVT VT, EVT &IntermediateVT,
999   unsigned &NumIntermediates, MVT &RegisterVT) const {
1000   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1001     unsigned NumElts = VT.getVectorNumElements();
1002     EVT ScalarVT = VT.getScalarType();
1003     unsigned Size = ScalarVT.getSizeInBits();
1004     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1005     // support, but unless we can properly handle 3-vectors, it will be still be
1006     // inconsistent.
1007     if (Size == 16 && Subtarget->has16BitInsts()) {
1008       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1009       IntermediateVT = RegisterVT;
1010       NumIntermediates = (NumElts + 1) / 2;
1011       return NumIntermediates;
1012     }
1013 
1014     if (Size == 32) {
1015       RegisterVT = ScalarVT.getSimpleVT();
1016       IntermediateVT = RegisterVT;
1017       NumIntermediates = NumElts;
1018       return NumIntermediates;
1019     }
1020 
1021     if (Size < 16 && Subtarget->has16BitInsts()) {
1022       // FIXME: Should probably form v2i16 pieces
1023       RegisterVT = MVT::i16;
1024       IntermediateVT = ScalarVT;
1025       NumIntermediates = NumElts;
1026       return NumIntermediates;
1027     }
1028 
1029 
1030     if (Size != 16 && Size <= 32) {
1031       RegisterVT = MVT::i32;
1032       IntermediateVT = ScalarVT;
1033       NumIntermediates = NumElts;
1034       return NumIntermediates;
1035     }
1036 
1037     if (Size > 32) {
1038       RegisterVT = MVT::i32;
1039       IntermediateVT = RegisterVT;
1040       NumIntermediates = NumElts * ((Size + 31) / 32);
1041       return NumIntermediates;
1042     }
1043   }
1044 
1045   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1046     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1047 }
1048 
1049 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1050   assert(DMaskLanes != 0);
1051 
1052   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1053     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1054     return EVT::getVectorVT(Ty->getContext(),
1055                             EVT::getEVT(VT->getElementType()),
1056                             NumElts);
1057   }
1058 
1059   return EVT::getEVT(Ty);
1060 }
1061 
1062 // Peek through TFE struct returns to only use the data size.
1063 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1064   auto *ST = dyn_cast<StructType>(Ty);
1065   if (!ST)
1066     return memVTFromImageData(Ty, DMaskLanes);
1067 
1068   // Some intrinsics return an aggregate type - special case to work out the
1069   // correct memVT.
1070   //
1071   // Only limited forms of aggregate type currently expected.
1072   if (ST->getNumContainedTypes() != 2 ||
1073       !ST->getContainedType(1)->isIntegerTy(32))
1074     return EVT();
1075   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1076 }
1077 
1078 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1079                                           const CallInst &CI,
1080                                           MachineFunction &MF,
1081                                           unsigned IntrID) const {
1082   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1083           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1084     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1085                                                   (Intrinsic::ID)IntrID);
1086     if (Attr.hasFnAttr(Attribute::ReadNone))
1087       return false;
1088 
1089     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1090 
1091     if (RsrcIntr->IsImage) {
1092       Info.ptrVal =
1093           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1094       Info.align.reset();
1095     } else {
1096       Info.ptrVal =
1097           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1098     }
1099 
1100     Info.flags = MachineMemOperand::MODereferenceable;
1101     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1102       unsigned DMaskLanes = 4;
1103 
1104       if (RsrcIntr->IsImage) {
1105         const AMDGPU::ImageDimIntrinsicInfo *Intr
1106           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1107         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1108           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1109 
1110         if (!BaseOpcode->Gather4) {
1111           // If this isn't a gather, we may have excess loaded elements in the
1112           // IR type. Check the dmask for the real number of elements loaded.
1113           unsigned DMask
1114             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1115           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1116         }
1117 
1118         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1119       } else
1120         Info.memVT = EVT::getEVT(CI.getType());
1121 
1122       // FIXME: What does alignment mean for an image?
1123       Info.opc = ISD::INTRINSIC_W_CHAIN;
1124       Info.flags |= MachineMemOperand::MOLoad;
1125     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1126       Info.opc = ISD::INTRINSIC_VOID;
1127 
1128       Type *DataTy = CI.getArgOperand(0)->getType();
1129       if (RsrcIntr->IsImage) {
1130         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1131         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1132         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1133       } else
1134         Info.memVT = EVT::getEVT(DataTy);
1135 
1136       Info.flags |= MachineMemOperand::MOStore;
1137     } else {
1138       // Atomic
1139       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1140                                             ISD::INTRINSIC_W_CHAIN;
1141       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1142       Info.flags = MachineMemOperand::MOLoad |
1143                    MachineMemOperand::MOStore |
1144                    MachineMemOperand::MODereferenceable;
1145 
1146       // XXX - Should this be volatile without known ordering?
1147       Info.flags |= MachineMemOperand::MOVolatile;
1148     }
1149     return true;
1150   }
1151 
1152   switch (IntrID) {
1153   case Intrinsic::amdgcn_atomic_inc:
1154   case Intrinsic::amdgcn_atomic_dec:
1155   case Intrinsic::amdgcn_ds_ordered_add:
1156   case Intrinsic::amdgcn_ds_ordered_swap:
1157   case Intrinsic::amdgcn_ds_fadd:
1158   case Intrinsic::amdgcn_ds_fmin:
1159   case Intrinsic::amdgcn_ds_fmax: {
1160     Info.opc = ISD::INTRINSIC_W_CHAIN;
1161     Info.memVT = MVT::getVT(CI.getType());
1162     Info.ptrVal = CI.getOperand(0);
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1165 
1166     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1167     if (!Vol->isZero())
1168       Info.flags |= MachineMemOperand::MOVolatile;
1169 
1170     return true;
1171   }
1172   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1173     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1174 
1175     Info.opc = ISD::INTRINSIC_W_CHAIN;
1176     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1177     Info.ptrVal =
1178         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1179     Info.align.reset();
1180     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1181 
1182     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1183     if (!Vol || !Vol->isZero())
1184       Info.flags |= MachineMemOperand::MOVolatile;
1185 
1186     return true;
1187   }
1188   case Intrinsic::amdgcn_ds_append:
1189   case Intrinsic::amdgcn_ds_consume: {
1190     Info.opc = ISD::INTRINSIC_W_CHAIN;
1191     Info.memVT = MVT::getVT(CI.getType());
1192     Info.ptrVal = CI.getOperand(0);
1193     Info.align.reset();
1194     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1195 
1196     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1197     if (!Vol->isZero())
1198       Info.flags |= MachineMemOperand::MOVolatile;
1199 
1200     return true;
1201   }
1202   case Intrinsic::amdgcn_global_atomic_csub: {
1203     Info.opc = ISD::INTRINSIC_W_CHAIN;
1204     Info.memVT = MVT::getVT(CI.getType());
1205     Info.ptrVal = CI.getOperand(0);
1206     Info.align.reset();
1207     Info.flags = MachineMemOperand::MOLoad |
1208                  MachineMemOperand::MOStore |
1209                  MachineMemOperand::MOVolatile;
1210     return true;
1211   }
1212   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1213     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1214     Info.opc = ISD::INTRINSIC_W_CHAIN;
1215     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1216     Info.ptrVal =
1217         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1218     Info.align.reset();
1219     Info.flags = MachineMemOperand::MOLoad |
1220                  MachineMemOperand::MODereferenceable;
1221     return true;
1222   }
1223   case Intrinsic::amdgcn_global_atomic_fadd:
1224   case Intrinsic::amdgcn_global_atomic_fmin:
1225   case Intrinsic::amdgcn_global_atomic_fmax:
1226   case Intrinsic::amdgcn_flat_atomic_fadd:
1227   case Intrinsic::amdgcn_flat_atomic_fmin:
1228   case Intrinsic::amdgcn_flat_atomic_fmax: {
1229     Info.opc = ISD::INTRINSIC_W_CHAIN;
1230     Info.memVT = MVT::getVT(CI.getType());
1231     Info.ptrVal = CI.getOperand(0);
1232     Info.align.reset();
1233     Info.flags = MachineMemOperand::MOLoad |
1234                  MachineMemOperand::MOStore |
1235                  MachineMemOperand::MODereferenceable |
1236                  MachineMemOperand::MOVolatile;
1237     return true;
1238   }
1239   case Intrinsic::amdgcn_ds_gws_init:
1240   case Intrinsic::amdgcn_ds_gws_barrier:
1241   case Intrinsic::amdgcn_ds_gws_sema_v:
1242   case Intrinsic::amdgcn_ds_gws_sema_br:
1243   case Intrinsic::amdgcn_ds_gws_sema_p:
1244   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1245     Info.opc = ISD::INTRINSIC_VOID;
1246 
1247     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1248     Info.ptrVal =
1249         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1250 
1251     // This is an abstract access, but we need to specify a type and size.
1252     Info.memVT = MVT::i32;
1253     Info.size = 4;
1254     Info.align = Align(4);
1255 
1256     Info.flags = MachineMemOperand::MOStore;
1257     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1258       Info.flags = MachineMemOperand::MOLoad;
1259     return true;
1260   }
1261   default:
1262     return false;
1263   }
1264 }
1265 
1266 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1267                                             SmallVectorImpl<Value*> &Ops,
1268                                             Type *&AccessTy) const {
1269   switch (II->getIntrinsicID()) {
1270   case Intrinsic::amdgcn_atomic_inc:
1271   case Intrinsic::amdgcn_atomic_dec:
1272   case Intrinsic::amdgcn_ds_ordered_add:
1273   case Intrinsic::amdgcn_ds_ordered_swap:
1274   case Intrinsic::amdgcn_ds_append:
1275   case Intrinsic::amdgcn_ds_consume:
1276   case Intrinsic::amdgcn_ds_fadd:
1277   case Intrinsic::amdgcn_ds_fmin:
1278   case Intrinsic::amdgcn_ds_fmax:
1279   case Intrinsic::amdgcn_global_atomic_fadd:
1280   case Intrinsic::amdgcn_flat_atomic_fadd:
1281   case Intrinsic::amdgcn_flat_atomic_fmin:
1282   case Intrinsic::amdgcn_flat_atomic_fmax:
1283   case Intrinsic::amdgcn_global_atomic_csub: {
1284     Value *Ptr = II->getArgOperand(0);
1285     AccessTy = II->getType();
1286     Ops.push_back(Ptr);
1287     return true;
1288   }
1289   default:
1290     return false;
1291   }
1292 }
1293 
1294 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1295   if (!Subtarget->hasFlatInstOffsets()) {
1296     // Flat instructions do not have offsets, and only have the register
1297     // address.
1298     return AM.BaseOffs == 0 && AM.Scale == 0;
1299   }
1300 
1301   return AM.Scale == 0 &&
1302          (AM.BaseOffs == 0 ||
1303           Subtarget->getInstrInfo()->isLegalFLATOffset(
1304               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1305 }
1306 
1307 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1308   if (Subtarget->hasFlatGlobalInsts())
1309     return AM.Scale == 0 &&
1310            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1311                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1312                                     SIInstrFlags::FlatGlobal));
1313 
1314   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1315       // Assume the we will use FLAT for all global memory accesses
1316       // on VI.
1317       // FIXME: This assumption is currently wrong.  On VI we still use
1318       // MUBUF instructions for the r + i addressing mode.  As currently
1319       // implemented, the MUBUF instructions only work on buffer < 4GB.
1320       // It may be possible to support > 4GB buffers with MUBUF instructions,
1321       // by setting the stride value in the resource descriptor which would
1322       // increase the size limit to (stride * 4GB).  However, this is risky,
1323       // because it has never been validated.
1324     return isLegalFlatAddressingMode(AM);
1325   }
1326 
1327   return isLegalMUBUFAddressingMode(AM);
1328 }
1329 
1330 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1331   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1332   // additionally can do r + r + i with addr64. 32-bit has more addressing
1333   // mode options. Depending on the resource constant, it can also do
1334   // (i64 r0) + (i32 r1) * (i14 i).
1335   //
1336   // Private arrays end up using a scratch buffer most of the time, so also
1337   // assume those use MUBUF instructions. Scratch loads / stores are currently
1338   // implemented as mubuf instructions with offen bit set, so slightly
1339   // different than the normal addr64.
1340   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1341     return false;
1342 
1343   // FIXME: Since we can split immediate into soffset and immediate offset,
1344   // would it make sense to allow any immediate?
1345 
1346   switch (AM.Scale) {
1347   case 0: // r + i or just i, depending on HasBaseReg.
1348     return true;
1349   case 1:
1350     return true; // We have r + r or r + i.
1351   case 2:
1352     if (AM.HasBaseReg) {
1353       // Reject 2 * r + r.
1354       return false;
1355     }
1356 
1357     // Allow 2 * r as r + r
1358     // Or  2 * r + i is allowed as r + r + i.
1359     return true;
1360   default: // Don't allow n * r
1361     return false;
1362   }
1363 }
1364 
1365 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1366                                              const AddrMode &AM, Type *Ty,
1367                                              unsigned AS, Instruction *I) const {
1368   // No global is ever allowed as a base.
1369   if (AM.BaseGV)
1370     return false;
1371 
1372   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1373     return isLegalGlobalAddressingMode(AM);
1374 
1375   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1376       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1377       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1378     // If the offset isn't a multiple of 4, it probably isn't going to be
1379     // correctly aligned.
1380     // FIXME: Can we get the real alignment here?
1381     if (AM.BaseOffs % 4 != 0)
1382       return isLegalMUBUFAddressingMode(AM);
1383 
1384     // There are no SMRD extloads, so if we have to do a small type access we
1385     // will use a MUBUF load.
1386     // FIXME?: We also need to do this if unaligned, but we don't know the
1387     // alignment here.
1388     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1389       return isLegalGlobalAddressingMode(AM);
1390 
1391     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1392       // SMRD instructions have an 8-bit, dword offset on SI.
1393       if (!isUInt<8>(AM.BaseOffs / 4))
1394         return false;
1395     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1396       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1397       // in 8-bits, it can use a smaller encoding.
1398       if (!isUInt<32>(AM.BaseOffs / 4))
1399         return false;
1400     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1401       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1402       if (!isUInt<20>(AM.BaseOffs))
1403         return false;
1404     } else
1405       llvm_unreachable("unhandled generation");
1406 
1407     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1408       return true;
1409 
1410     if (AM.Scale == 1 && AM.HasBaseReg)
1411       return true;
1412 
1413     return false;
1414 
1415   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1416     return isLegalMUBUFAddressingMode(AM);
1417   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1418              AS == AMDGPUAS::REGION_ADDRESS) {
1419     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1420     // field.
1421     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1422     // an 8-bit dword offset but we don't know the alignment here.
1423     if (!isUInt<16>(AM.BaseOffs))
1424       return false;
1425 
1426     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1427       return true;
1428 
1429     if (AM.Scale == 1 && AM.HasBaseReg)
1430       return true;
1431 
1432     return false;
1433   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1434              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1435     // For an unknown address space, this usually means that this is for some
1436     // reason being used for pure arithmetic, and not based on some addressing
1437     // computation. We don't have instructions that compute pointers with any
1438     // addressing modes, so treat them as having no offset like flat
1439     // instructions.
1440     return isLegalFlatAddressingMode(AM);
1441   }
1442 
1443   // Assume a user alias of global for unknown address spaces.
1444   return isLegalGlobalAddressingMode(AM);
1445 }
1446 
1447 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1448                                         const MachineFunction &MF) const {
1449   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1450     return (MemVT.getSizeInBits() <= 4 * 32);
1451   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1452     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1453     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1454   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1455     return (MemVT.getSizeInBits() <= 2 * 32);
1456   }
1457   return true;
1458 }
1459 
1460 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1461     unsigned Size, unsigned AddrSpace, Align Alignment,
1462     MachineMemOperand::Flags Flags, bool *IsFast) const {
1463   if (IsFast)
1464     *IsFast = false;
1465 
1466   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1467       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1468     // Check if alignment requirements for ds_read/write instructions are
1469     // disabled.
1470     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1471         !Subtarget->hasLDSMisalignedBug()) {
1472       if (IsFast)
1473         *IsFast = Alignment != Align(2);
1474       return true;
1475     }
1476 
1477     // Either, the alignment requirements are "enabled", or there is an
1478     // unaligned LDS access related hardware bug though alignment requirements
1479     // are "disabled". In either case, we need to check for proper alignment
1480     // requirements.
1481     //
1482     if (Size == 64) {
1483       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1484       // can do a 4 byte aligned, 8 byte access in a single operation using
1485       // ds_read2/write2_b32 with adjacent offsets.
1486       bool AlignedBy4 = Alignment >= Align(4);
1487       if (IsFast)
1488         *IsFast = AlignedBy4;
1489 
1490       return AlignedBy4;
1491     }
1492     if (Size == 96) {
1493       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1494       // gfx8 and older.
1495       bool AlignedBy16 = Alignment >= Align(16);
1496       if (IsFast)
1497         *IsFast = AlignedBy16;
1498 
1499       return AlignedBy16;
1500     }
1501     if (Size == 128) {
1502       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1503       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1504       // single operation using ds_read2/write2_b64.
1505       bool AlignedBy8 = Alignment >= Align(8);
1506       if (IsFast)
1507         *IsFast = AlignedBy8;
1508 
1509       return AlignedBy8;
1510     }
1511   }
1512 
1513   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1514     bool AlignedBy4 = Alignment >= Align(4);
1515     if (IsFast)
1516       *IsFast = AlignedBy4;
1517 
1518     return AlignedBy4 ||
1519            Subtarget->enableFlatScratch() ||
1520            Subtarget->hasUnalignedScratchAccess();
1521   }
1522 
1523   // FIXME: We have to be conservative here and assume that flat operations
1524   // will access scratch.  If we had access to the IR function, then we
1525   // could determine if any private memory was used in the function.
1526   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1527       !Subtarget->hasUnalignedScratchAccess()) {
1528     bool AlignedBy4 = Alignment >= Align(4);
1529     if (IsFast)
1530       *IsFast = AlignedBy4;
1531 
1532     return AlignedBy4;
1533   }
1534 
1535   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1536       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1537         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1538     // If we have an uniform constant load, it still requires using a slow
1539     // buffer instruction if unaligned.
1540     if (IsFast) {
1541       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1542       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1543       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1544                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1545         Alignment >= Align(4) : Alignment != Align(2);
1546     }
1547 
1548     return true;
1549   }
1550 
1551   // Smaller than dword value must be aligned.
1552   if (Size < 32)
1553     return false;
1554 
1555   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1556   // byte-address are ignored, thus forcing Dword alignment.
1557   // This applies to private, global, and constant memory.
1558   if (IsFast)
1559     *IsFast = true;
1560 
1561   return Size >= 32 && Alignment >= Align(4);
1562 }
1563 
1564 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1565     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1566     bool *IsFast) const {
1567   if (IsFast)
1568     *IsFast = false;
1569 
1570   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1571   // which isn't a simple VT.
1572   // Until MVT is extended to handle this, simply check for the size and
1573   // rely on the condition below: allow accesses if the size is a multiple of 4.
1574   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1575                            VT.getStoreSize() > 16)) {
1576     return false;
1577   }
1578 
1579   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1580                                             Alignment, Flags, IsFast);
1581 }
1582 
1583 EVT SITargetLowering::getOptimalMemOpType(
1584     const MemOp &Op, const AttributeList &FuncAttributes) const {
1585   // FIXME: Should account for address space here.
1586 
1587   // The default fallback uses the private pointer size as a guess for a type to
1588   // use. Make sure we switch these to 64-bit accesses.
1589 
1590   if (Op.size() >= 16 &&
1591       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1592     return MVT::v4i32;
1593 
1594   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1595     return MVT::v2i32;
1596 
1597   // Use the default.
1598   return MVT::Other;
1599 }
1600 
1601 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1602   const MemSDNode *MemNode = cast<MemSDNode>(N);
1603   const Value *Ptr = MemNode->getMemOperand()->getValue();
1604   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1605   return I && I->getMetadata("amdgpu.noclobber");
1606 }
1607 
1608 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1609   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1610          AS == AMDGPUAS::PRIVATE_ADDRESS;
1611 }
1612 
1613 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1614                                            unsigned DestAS) const {
1615   // Flat -> private/local is a simple truncate.
1616   // Flat -> global is no-op
1617   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1618     return true;
1619 
1620   const GCNTargetMachine &TM =
1621       static_cast<const GCNTargetMachine &>(getTargetMachine());
1622   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1623 }
1624 
1625 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1626   const MemSDNode *MemNode = cast<MemSDNode>(N);
1627 
1628   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1629 }
1630 
1631 TargetLoweringBase::LegalizeTypeAction
1632 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1633   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1634       VT.getScalarType().bitsLE(MVT::i16))
1635     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1636   return TargetLoweringBase::getPreferredVectorAction(VT);
1637 }
1638 
1639 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1640                                                          Type *Ty) const {
1641   // FIXME: Could be smarter if called for vector constants.
1642   return true;
1643 }
1644 
1645 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1646   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1647     switch (Op) {
1648     case ISD::LOAD:
1649     case ISD::STORE:
1650 
1651     // These operations are done with 32-bit instructions anyway.
1652     case ISD::AND:
1653     case ISD::OR:
1654     case ISD::XOR:
1655     case ISD::SELECT:
1656       // TODO: Extensions?
1657       return true;
1658     default:
1659       return false;
1660     }
1661   }
1662 
1663   // SimplifySetCC uses this function to determine whether or not it should
1664   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1665   if (VT == MVT::i1 && Op == ISD::SETCC)
1666     return false;
1667 
1668   return TargetLowering::isTypeDesirableForOp(Op, VT);
1669 }
1670 
1671 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1672                                                    const SDLoc &SL,
1673                                                    SDValue Chain,
1674                                                    uint64_t Offset) const {
1675   const DataLayout &DL = DAG.getDataLayout();
1676   MachineFunction &MF = DAG.getMachineFunction();
1677   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1678 
1679   const ArgDescriptor *InputPtrReg;
1680   const TargetRegisterClass *RC;
1681   LLT ArgTy;
1682   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   std::tie(InputPtrReg, RC, ArgTy) =
1685       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1686 
1687   // We may not have the kernarg segment argument if we have no kernel
1688   // arguments.
1689   if (!InputPtrReg)
1690     return DAG.getConstant(0, SL, PtrVT);
1691 
1692   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1693   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1694     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1695 
1696   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1697 }
1698 
1699 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1700                                             const SDLoc &SL) const {
1701   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1702                                                FIRST_IMPLICIT);
1703   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1704 }
1705 
1706 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1707                                          const SDLoc &SL, SDValue Val,
1708                                          bool Signed,
1709                                          const ISD::InputArg *Arg) const {
1710   // First, if it is a widened vector, narrow it.
1711   if (VT.isVector() &&
1712       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1713     EVT NarrowedVT =
1714         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1715                          VT.getVectorNumElements());
1716     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1717                       DAG.getConstant(0, SL, MVT::i32));
1718   }
1719 
1720   // Then convert the vector elements or scalar value.
1721   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1722       VT.bitsLT(MemVT)) {
1723     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1724     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1725   }
1726 
1727   if (MemVT.isFloatingPoint())
1728     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1729   else if (Signed)
1730     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1731   else
1732     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1733 
1734   return Val;
1735 }
1736 
1737 SDValue SITargetLowering::lowerKernargMemParameter(
1738     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1739     uint64_t Offset, Align Alignment, bool Signed,
1740     const ISD::InputArg *Arg) const {
1741   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1742 
1743   // Try to avoid using an extload by loading earlier than the argument address,
1744   // and extracting the relevant bits. The load should hopefully be merged with
1745   // the previous argument.
1746   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1747     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1748     int64_t AlignDownOffset = alignDown(Offset, 4);
1749     int64_t OffsetDiff = Offset - AlignDownOffset;
1750 
1751     EVT IntVT = MemVT.changeTypeToInteger();
1752 
1753     // TODO: If we passed in the base kernel offset we could have a better
1754     // alignment than 4, but we don't really need it.
1755     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1756     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1757                                MachineMemOperand::MODereferenceable |
1758                                    MachineMemOperand::MOInvariant);
1759 
1760     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1761     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1762 
1763     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1764     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1765     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1766 
1767 
1768     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1769   }
1770 
1771   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1772   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1773                              MachineMemOperand::MODereferenceable |
1774                                  MachineMemOperand::MOInvariant);
1775 
1776   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1777   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1778 }
1779 
1780 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1781                                               const SDLoc &SL, SDValue Chain,
1782                                               const ISD::InputArg &Arg) const {
1783   MachineFunction &MF = DAG.getMachineFunction();
1784   MachineFrameInfo &MFI = MF.getFrameInfo();
1785 
1786   if (Arg.Flags.isByVal()) {
1787     unsigned Size = Arg.Flags.getByValSize();
1788     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1789     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1790   }
1791 
1792   unsigned ArgOffset = VA.getLocMemOffset();
1793   unsigned ArgSize = VA.getValVT().getStoreSize();
1794 
1795   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1796 
1797   // Create load nodes to retrieve arguments from the stack.
1798   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1799   SDValue ArgValue;
1800 
1801   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1802   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1803   MVT MemVT = VA.getValVT();
1804 
1805   switch (VA.getLocInfo()) {
1806   default:
1807     break;
1808   case CCValAssign::BCvt:
1809     MemVT = VA.getLocVT();
1810     break;
1811   case CCValAssign::SExt:
1812     ExtType = ISD::SEXTLOAD;
1813     break;
1814   case CCValAssign::ZExt:
1815     ExtType = ISD::ZEXTLOAD;
1816     break;
1817   case CCValAssign::AExt:
1818     ExtType = ISD::EXTLOAD;
1819     break;
1820   }
1821 
1822   ArgValue = DAG.getExtLoad(
1823     ExtType, SL, VA.getLocVT(), Chain, FIN,
1824     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1825     MemVT);
1826   return ArgValue;
1827 }
1828 
1829 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1830   const SIMachineFunctionInfo &MFI,
1831   EVT VT,
1832   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1833   const ArgDescriptor *Reg;
1834   const TargetRegisterClass *RC;
1835   LLT Ty;
1836 
1837   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1838   if (!Reg) {
1839     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1840       // It's possible for a kernarg intrinsic call to appear in a kernel with
1841       // no allocated segment, in which case we do not add the user sgpr
1842       // argument, so just return null.
1843       return DAG.getConstant(0, SDLoc(), VT);
1844     }
1845 
1846     // It's undefined behavior if a function marked with the amdgpu-no-*
1847     // attributes uses the corresponding intrinsic.
1848     return DAG.getUNDEF(VT);
1849   }
1850 
1851   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1852 }
1853 
1854 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1855                                CallingConv::ID CallConv,
1856                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1857                                FunctionType *FType,
1858                                SIMachineFunctionInfo *Info) {
1859   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1860     const ISD::InputArg *Arg = &Ins[I];
1861 
1862     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1863            "vector type argument should have been split");
1864 
1865     // First check if it's a PS input addr.
1866     if (CallConv == CallingConv::AMDGPU_PS &&
1867         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1868       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1869 
1870       // Inconveniently only the first part of the split is marked as isSplit,
1871       // so skip to the end. We only want to increment PSInputNum once for the
1872       // entire split argument.
1873       if (Arg->Flags.isSplit()) {
1874         while (!Arg->Flags.isSplitEnd()) {
1875           assert((!Arg->VT.isVector() ||
1876                   Arg->VT.getScalarSizeInBits() == 16) &&
1877                  "unexpected vector split in ps argument type");
1878           if (!SkipArg)
1879             Splits.push_back(*Arg);
1880           Arg = &Ins[++I];
1881         }
1882       }
1883 
1884       if (SkipArg) {
1885         // We can safely skip PS inputs.
1886         Skipped.set(Arg->getOrigArgIndex());
1887         ++PSInputNum;
1888         continue;
1889       }
1890 
1891       Info->markPSInputAllocated(PSInputNum);
1892       if (Arg->Used)
1893         Info->markPSInputEnabled(PSInputNum);
1894 
1895       ++PSInputNum;
1896     }
1897 
1898     Splits.push_back(*Arg);
1899   }
1900 }
1901 
1902 // Allocate special inputs passed in VGPRs.
1903 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1904                                                       MachineFunction &MF,
1905                                                       const SIRegisterInfo &TRI,
1906                                                       SIMachineFunctionInfo &Info) const {
1907   const LLT S32 = LLT::scalar(32);
1908   MachineRegisterInfo &MRI = MF.getRegInfo();
1909 
1910   if (Info.hasWorkItemIDX()) {
1911     Register Reg = AMDGPU::VGPR0;
1912     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1913 
1914     CCInfo.AllocateReg(Reg);
1915     unsigned Mask = (Subtarget->hasPackedTID() &&
1916                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1917     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1918   }
1919 
1920   if (Info.hasWorkItemIDY()) {
1921     assert(Info.hasWorkItemIDX());
1922     if (Subtarget->hasPackedTID()) {
1923       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1924                                                         0x3ff << 10));
1925     } else {
1926       unsigned Reg = AMDGPU::VGPR1;
1927       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1928 
1929       CCInfo.AllocateReg(Reg);
1930       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1931     }
1932   }
1933 
1934   if (Info.hasWorkItemIDZ()) {
1935     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1936     if (Subtarget->hasPackedTID()) {
1937       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1938                                                         0x3ff << 20));
1939     } else {
1940       unsigned Reg = AMDGPU::VGPR2;
1941       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1942 
1943       CCInfo.AllocateReg(Reg);
1944       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1945     }
1946   }
1947 }
1948 
1949 // Try to allocate a VGPR at the end of the argument list, or if no argument
1950 // VGPRs are left allocating a stack slot.
1951 // If \p Mask is is given it indicates bitfield position in the register.
1952 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1953 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1954                                          ArgDescriptor Arg = ArgDescriptor()) {
1955   if (Arg.isSet())
1956     return ArgDescriptor::createArg(Arg, Mask);
1957 
1958   ArrayRef<MCPhysReg> ArgVGPRs
1959     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1960   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1961   if (RegIdx == ArgVGPRs.size()) {
1962     // Spill to stack required.
1963     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1964 
1965     return ArgDescriptor::createStack(Offset, Mask);
1966   }
1967 
1968   unsigned Reg = ArgVGPRs[RegIdx];
1969   Reg = CCInfo.AllocateReg(Reg);
1970   assert(Reg != AMDGPU::NoRegister);
1971 
1972   MachineFunction &MF = CCInfo.getMachineFunction();
1973   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1974   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1975   return ArgDescriptor::createRegister(Reg, Mask);
1976 }
1977 
1978 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1979                                              const TargetRegisterClass *RC,
1980                                              unsigned NumArgRegs) {
1981   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1982   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1983   if (RegIdx == ArgSGPRs.size())
1984     report_fatal_error("ran out of SGPRs for arguments");
1985 
1986   unsigned Reg = ArgSGPRs[RegIdx];
1987   Reg = CCInfo.AllocateReg(Reg);
1988   assert(Reg != AMDGPU::NoRegister);
1989 
1990   MachineFunction &MF = CCInfo.getMachineFunction();
1991   MF.addLiveIn(Reg, RC);
1992   return ArgDescriptor::createRegister(Reg);
1993 }
1994 
1995 // If this has a fixed position, we still should allocate the register in the
1996 // CCInfo state. Technically we could get away with this for values passed
1997 // outside of the normal argument range.
1998 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1999                                        const TargetRegisterClass *RC,
2000                                        MCRegister Reg) {
2001   Reg = CCInfo.AllocateReg(Reg);
2002   assert(Reg != AMDGPU::NoRegister);
2003   MachineFunction &MF = CCInfo.getMachineFunction();
2004   MF.addLiveIn(Reg, RC);
2005 }
2006 
2007 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2008   if (Arg) {
2009     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2010                                Arg.getRegister());
2011   } else
2012     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2013 }
2014 
2015 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2016   if (Arg) {
2017     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2018                                Arg.getRegister());
2019   } else
2020     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2021 }
2022 
2023 /// Allocate implicit function VGPR arguments at the end of allocated user
2024 /// arguments.
2025 void SITargetLowering::allocateSpecialInputVGPRs(
2026   CCState &CCInfo, MachineFunction &MF,
2027   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2028   const unsigned Mask = 0x3ff;
2029   ArgDescriptor Arg;
2030 
2031   if (Info.hasWorkItemIDX()) {
2032     Arg = allocateVGPR32Input(CCInfo, Mask);
2033     Info.setWorkItemIDX(Arg);
2034   }
2035 
2036   if (Info.hasWorkItemIDY()) {
2037     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2038     Info.setWorkItemIDY(Arg);
2039   }
2040 
2041   if (Info.hasWorkItemIDZ())
2042     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2043 }
2044 
2045 /// Allocate implicit function VGPR arguments in fixed registers.
2046 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2047   CCState &CCInfo, MachineFunction &MF,
2048   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2049   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2050   if (!Reg)
2051     report_fatal_error("failed to allocated VGPR for implicit arguments");
2052 
2053   const unsigned Mask = 0x3ff;
2054   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2055   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2056   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2057 }
2058 
2059 void SITargetLowering::allocateSpecialInputSGPRs(
2060   CCState &CCInfo,
2061   MachineFunction &MF,
2062   const SIRegisterInfo &TRI,
2063   SIMachineFunctionInfo &Info) const {
2064   auto &ArgInfo = Info.getArgInfo();
2065 
2066   // TODO: Unify handling with private memory pointers.
2067   if (Info.hasDispatchPtr())
2068     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2069 
2070   if (Info.hasQueuePtr())
2071     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2072 
2073   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2074   // constant offset from the kernarg segment.
2075   if (Info.hasImplicitArgPtr())
2076     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2077 
2078   if (Info.hasDispatchID())
2079     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2080 
2081   // flat_scratch_init is not applicable for non-kernel functions.
2082 
2083   if (Info.hasWorkGroupIDX())
2084     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2085 
2086   if (Info.hasWorkGroupIDY())
2087     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2088 
2089   if (Info.hasWorkGroupIDZ())
2090     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2091 }
2092 
2093 // Allocate special inputs passed in user SGPRs.
2094 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2095                                             MachineFunction &MF,
2096                                             const SIRegisterInfo &TRI,
2097                                             SIMachineFunctionInfo &Info) const {
2098   if (Info.hasImplicitBufferPtr()) {
2099     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2100     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2101     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2102   }
2103 
2104   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2105   if (Info.hasPrivateSegmentBuffer()) {
2106     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2107     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2108     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2109   }
2110 
2111   if (Info.hasDispatchPtr()) {
2112     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2113     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2114     CCInfo.AllocateReg(DispatchPtrReg);
2115   }
2116 
2117   if (Info.hasQueuePtr()) {
2118     Register QueuePtrReg = Info.addQueuePtr(TRI);
2119     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2120     CCInfo.AllocateReg(QueuePtrReg);
2121   }
2122 
2123   if (Info.hasKernargSegmentPtr()) {
2124     MachineRegisterInfo &MRI = MF.getRegInfo();
2125     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2126     CCInfo.AllocateReg(InputPtrReg);
2127 
2128     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2129     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2130   }
2131 
2132   if (Info.hasDispatchID()) {
2133     Register DispatchIDReg = Info.addDispatchID(TRI);
2134     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2135     CCInfo.AllocateReg(DispatchIDReg);
2136   }
2137 
2138   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2139     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2140     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2141     CCInfo.AllocateReg(FlatScratchInitReg);
2142   }
2143 
2144   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2145   // these from the dispatch pointer.
2146 }
2147 
2148 // Allocate special input registers that are initialized per-wave.
2149 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2150                                            MachineFunction &MF,
2151                                            SIMachineFunctionInfo &Info,
2152                                            CallingConv::ID CallConv,
2153                                            bool IsShader) const {
2154   if (Info.hasWorkGroupIDX()) {
2155     Register Reg = Info.addWorkGroupIDX();
2156     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2157     CCInfo.AllocateReg(Reg);
2158   }
2159 
2160   if (Info.hasWorkGroupIDY()) {
2161     Register Reg = Info.addWorkGroupIDY();
2162     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2163     CCInfo.AllocateReg(Reg);
2164   }
2165 
2166   if (Info.hasWorkGroupIDZ()) {
2167     Register Reg = Info.addWorkGroupIDZ();
2168     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2169     CCInfo.AllocateReg(Reg);
2170   }
2171 
2172   if (Info.hasWorkGroupInfo()) {
2173     Register Reg = Info.addWorkGroupInfo();
2174     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2175     CCInfo.AllocateReg(Reg);
2176   }
2177 
2178   if (Info.hasPrivateSegmentWaveByteOffset()) {
2179     // Scratch wave offset passed in system SGPR.
2180     unsigned PrivateSegmentWaveByteOffsetReg;
2181 
2182     if (IsShader) {
2183       PrivateSegmentWaveByteOffsetReg =
2184         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2185 
2186       // This is true if the scratch wave byte offset doesn't have a fixed
2187       // location.
2188       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2189         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2190         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2191       }
2192     } else
2193       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2194 
2195     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2197   }
2198 }
2199 
2200 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2201                                      MachineFunction &MF,
2202                                      const SIRegisterInfo &TRI,
2203                                      SIMachineFunctionInfo &Info) {
2204   // Now that we've figured out where the scratch register inputs are, see if
2205   // should reserve the arguments and use them directly.
2206   MachineFrameInfo &MFI = MF.getFrameInfo();
2207   bool HasStackObjects = MFI.hasStackObjects();
2208   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2209 
2210   // Record that we know we have non-spill stack objects so we don't need to
2211   // check all stack objects later.
2212   if (HasStackObjects)
2213     Info.setHasNonSpillStackObjects(true);
2214 
2215   // Everything live out of a block is spilled with fast regalloc, so it's
2216   // almost certain that spilling will be required.
2217   if (TM.getOptLevel() == CodeGenOpt::None)
2218     HasStackObjects = true;
2219 
2220   // For now assume stack access is needed in any callee functions, so we need
2221   // the scratch registers to pass in.
2222   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2223 
2224   if (!ST.enableFlatScratch()) {
2225     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2226       // If we have stack objects, we unquestionably need the private buffer
2227       // resource. For the Code Object V2 ABI, this will be the first 4 user
2228       // SGPR inputs. We can reserve those and use them directly.
2229 
2230       Register PrivateSegmentBufferReg =
2231           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2232       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2233     } else {
2234       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2235       // We tentatively reserve the last registers (skipping the last registers
2236       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2237       // we'll replace these with the ones immediately after those which were
2238       // really allocated. In the prologue copies will be inserted from the
2239       // argument to these reserved registers.
2240 
2241       // Without HSA, relocations are used for the scratch pointer and the
2242       // buffer resource setup is always inserted in the prologue. Scratch wave
2243       // offset is still in an input SGPR.
2244       Info.setScratchRSrcReg(ReservedBufferReg);
2245     }
2246   }
2247 
2248   MachineRegisterInfo &MRI = MF.getRegInfo();
2249 
2250   // For entry functions we have to set up the stack pointer if we use it,
2251   // whereas non-entry functions get this "for free". This means there is no
2252   // intrinsic advantage to using S32 over S34 in cases where we do not have
2253   // calls but do need a frame pointer (i.e. if we are requested to have one
2254   // because frame pointer elimination is disabled). To keep things simple we
2255   // only ever use S32 as the call ABI stack pointer, and so using it does not
2256   // imply we need a separate frame pointer.
2257   //
2258   // Try to use s32 as the SP, but move it if it would interfere with input
2259   // arguments. This won't work with calls though.
2260   //
2261   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2262   // registers.
2263   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2264     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2265   } else {
2266     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2267 
2268     if (MFI.hasCalls())
2269       report_fatal_error("call in graphics shader with too many input SGPRs");
2270 
2271     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2272       if (!MRI.isLiveIn(Reg)) {
2273         Info.setStackPtrOffsetReg(Reg);
2274         break;
2275       }
2276     }
2277 
2278     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2279       report_fatal_error("failed to find register for SP");
2280   }
2281 
2282   // hasFP should be accurate for entry functions even before the frame is
2283   // finalized, because it does not rely on the known stack size, only
2284   // properties like whether variable sized objects are present.
2285   if (ST.getFrameLowering()->hasFP(MF)) {
2286     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2287   }
2288 }
2289 
2290 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2291   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2292   return !Info->isEntryFunction();
2293 }
2294 
2295 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2296 
2297 }
2298 
2299 void SITargetLowering::insertCopiesSplitCSR(
2300   MachineBasicBlock *Entry,
2301   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2302   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2303 
2304   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2305   if (!IStart)
2306     return;
2307 
2308   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2309   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2310   MachineBasicBlock::iterator MBBI = Entry->begin();
2311   for (const MCPhysReg *I = IStart; *I; ++I) {
2312     const TargetRegisterClass *RC = nullptr;
2313     if (AMDGPU::SReg_64RegClass.contains(*I))
2314       RC = &AMDGPU::SGPR_64RegClass;
2315     else if (AMDGPU::SReg_32RegClass.contains(*I))
2316       RC = &AMDGPU::SGPR_32RegClass;
2317     else
2318       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2319 
2320     Register NewVR = MRI->createVirtualRegister(RC);
2321     // Create copy from CSR to a virtual register.
2322     Entry->addLiveIn(*I);
2323     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2324       .addReg(*I);
2325 
2326     // Insert the copy-back instructions right before the terminator.
2327     for (auto *Exit : Exits)
2328       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2329               TII->get(TargetOpcode::COPY), *I)
2330         .addReg(NewVR);
2331   }
2332 }
2333 
2334 SDValue SITargetLowering::LowerFormalArguments(
2335     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2336     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2337     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2338   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2339 
2340   MachineFunction &MF = DAG.getMachineFunction();
2341   const Function &Fn = MF.getFunction();
2342   FunctionType *FType = MF.getFunction().getFunctionType();
2343   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2344 
2345   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2346     DiagnosticInfoUnsupported NoGraphicsHSA(
2347         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2348     DAG.getContext()->diagnose(NoGraphicsHSA);
2349     return DAG.getEntryNode();
2350   }
2351 
2352   Info->allocateModuleLDSGlobal(Fn.getParent());
2353 
2354   SmallVector<ISD::InputArg, 16> Splits;
2355   SmallVector<CCValAssign, 16> ArgLocs;
2356   BitVector Skipped(Ins.size());
2357   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2358                  *DAG.getContext());
2359 
2360   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2361   bool IsKernel = AMDGPU::isKernel(CallConv);
2362   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2363 
2364   if (IsGraphics) {
2365     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2366            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2367            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2368            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2369            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2370            !Info->hasWorkItemIDZ());
2371   }
2372 
2373   if (CallConv == CallingConv::AMDGPU_PS) {
2374     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2375 
2376     // At least one interpolation mode must be enabled or else the GPU will
2377     // hang.
2378     //
2379     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2380     // set PSInputAddr, the user wants to enable some bits after the compilation
2381     // based on run-time states. Since we can't know what the final PSInputEna
2382     // will look like, so we shouldn't do anything here and the user should take
2383     // responsibility for the correct programming.
2384     //
2385     // Otherwise, the following restrictions apply:
2386     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2387     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2388     //   enabled too.
2389     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2390         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2391       CCInfo.AllocateReg(AMDGPU::VGPR0);
2392       CCInfo.AllocateReg(AMDGPU::VGPR1);
2393       Info->markPSInputAllocated(0);
2394       Info->markPSInputEnabled(0);
2395     }
2396     if (Subtarget->isAmdPalOS()) {
2397       // For isAmdPalOS, the user does not enable some bits after compilation
2398       // based on run-time states; the register values being generated here are
2399       // the final ones set in hardware. Therefore we need to apply the
2400       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2401       // a bit is set in PSInputAddr but not PSInputEnable is where the
2402       // frontend set up an input arg for a particular interpolation mode, but
2403       // nothing uses that input arg. Really we should have an earlier pass
2404       // that removes such an arg.)
2405       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2406       if ((PsInputBits & 0x7F) == 0 ||
2407           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2408         Info->markPSInputEnabled(
2409             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2410     }
2411   } else if (IsKernel) {
2412     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2413   } else {
2414     Splits.append(Ins.begin(), Ins.end());
2415   }
2416 
2417   if (IsEntryFunc) {
2418     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2419     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2420   } else if (!IsGraphics) {
2421     // For the fixed ABI, pass workitem IDs in the last argument register.
2422     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2423   }
2424 
2425   if (IsKernel) {
2426     analyzeFormalArgumentsCompute(CCInfo, Ins);
2427   } else {
2428     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2429     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2430   }
2431 
2432   SmallVector<SDValue, 16> Chains;
2433 
2434   // FIXME: This is the minimum kernel argument alignment. We should improve
2435   // this to the maximum alignment of the arguments.
2436   //
2437   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2438   // kern arg offset.
2439   const Align KernelArgBaseAlign = Align(16);
2440 
2441   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2442     const ISD::InputArg &Arg = Ins[i];
2443     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2444       InVals.push_back(DAG.getUNDEF(Arg.VT));
2445       continue;
2446     }
2447 
2448     CCValAssign &VA = ArgLocs[ArgIdx++];
2449     MVT VT = VA.getLocVT();
2450 
2451     if (IsEntryFunc && VA.isMemLoc()) {
2452       VT = Ins[i].VT;
2453       EVT MemVT = VA.getLocVT();
2454 
2455       const uint64_t Offset = VA.getLocMemOffset();
2456       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2457 
2458       if (Arg.Flags.isByRef()) {
2459         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2460 
2461         const GCNTargetMachine &TM =
2462             static_cast<const GCNTargetMachine &>(getTargetMachine());
2463         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2464                                     Arg.Flags.getPointerAddrSpace())) {
2465           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2466                                      Arg.Flags.getPointerAddrSpace());
2467         }
2468 
2469         InVals.push_back(Ptr);
2470         continue;
2471       }
2472 
2473       SDValue Arg = lowerKernargMemParameter(
2474         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2475       Chains.push_back(Arg.getValue(1));
2476 
2477       auto *ParamTy =
2478         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2479       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2480           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2481                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2482         // On SI local pointers are just offsets into LDS, so they are always
2483         // less than 16-bits.  On CI and newer they could potentially be
2484         // real pointers, so we can't guarantee their size.
2485         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2486                           DAG.getValueType(MVT::i16));
2487       }
2488 
2489       InVals.push_back(Arg);
2490       continue;
2491     } else if (!IsEntryFunc && VA.isMemLoc()) {
2492       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2493       InVals.push_back(Val);
2494       if (!Arg.Flags.isByVal())
2495         Chains.push_back(Val.getValue(1));
2496       continue;
2497     }
2498 
2499     assert(VA.isRegLoc() && "Parameter must be in a register!");
2500 
2501     Register Reg = VA.getLocReg();
2502     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2503     EVT ValVT = VA.getValVT();
2504 
2505     Reg = MF.addLiveIn(Reg, RC);
2506     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2507 
2508     if (Arg.Flags.isSRet()) {
2509       // The return object should be reasonably addressable.
2510 
2511       // FIXME: This helps when the return is a real sret. If it is a
2512       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2513       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2514       unsigned NumBits
2515         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2516       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2517         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2518     }
2519 
2520     // If this is an 8 or 16-bit value, it is really passed promoted
2521     // to 32 bits. Insert an assert[sz]ext to capture this, then
2522     // truncate to the right size.
2523     switch (VA.getLocInfo()) {
2524     case CCValAssign::Full:
2525       break;
2526     case CCValAssign::BCvt:
2527       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2528       break;
2529     case CCValAssign::SExt:
2530       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2531                         DAG.getValueType(ValVT));
2532       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2533       break;
2534     case CCValAssign::ZExt:
2535       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2536                         DAG.getValueType(ValVT));
2537       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2538       break;
2539     case CCValAssign::AExt:
2540       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2541       break;
2542     default:
2543       llvm_unreachable("Unknown loc info!");
2544     }
2545 
2546     InVals.push_back(Val);
2547   }
2548 
2549   // Start adding system SGPRs.
2550   if (IsEntryFunc) {
2551     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2552   } else {
2553     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2554     if (!IsGraphics)
2555       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2556   }
2557 
2558   auto &ArgUsageInfo =
2559     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2560   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2561 
2562   unsigned StackArgSize = CCInfo.getNextStackOffset();
2563   Info->setBytesInStackArgArea(StackArgSize);
2564 
2565   return Chains.empty() ? Chain :
2566     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2567 }
2568 
2569 // TODO: If return values can't fit in registers, we should return as many as
2570 // possible in registers before passing on stack.
2571 bool SITargetLowering::CanLowerReturn(
2572   CallingConv::ID CallConv,
2573   MachineFunction &MF, bool IsVarArg,
2574   const SmallVectorImpl<ISD::OutputArg> &Outs,
2575   LLVMContext &Context) const {
2576   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2577   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2578   // for shaders. Vector types should be explicitly handled by CC.
2579   if (AMDGPU::isEntryFunctionCC(CallConv))
2580     return true;
2581 
2582   SmallVector<CCValAssign, 16> RVLocs;
2583   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2584   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2585 }
2586 
2587 SDValue
2588 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2589                               bool isVarArg,
2590                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2591                               const SmallVectorImpl<SDValue> &OutVals,
2592                               const SDLoc &DL, SelectionDAG &DAG) const {
2593   MachineFunction &MF = DAG.getMachineFunction();
2594   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2595 
2596   if (AMDGPU::isKernel(CallConv)) {
2597     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2598                                              OutVals, DL, DAG);
2599   }
2600 
2601   bool IsShader = AMDGPU::isShader(CallConv);
2602 
2603   Info->setIfReturnsVoid(Outs.empty());
2604   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2605 
2606   // CCValAssign - represent the assignment of the return value to a location.
2607   SmallVector<CCValAssign, 48> RVLocs;
2608   SmallVector<ISD::OutputArg, 48> Splits;
2609 
2610   // CCState - Info about the registers and stack slots.
2611   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2612                  *DAG.getContext());
2613 
2614   // Analyze outgoing return values.
2615   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2616 
2617   SDValue Flag;
2618   SmallVector<SDValue, 48> RetOps;
2619   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2620 
2621   // Add return address for callable functions.
2622   if (!Info->isEntryFunction()) {
2623     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2624     SDValue ReturnAddrReg = CreateLiveInRegister(
2625       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2626 
2627     SDValue ReturnAddrVirtualReg =
2628         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2629                             CallConv != CallingConv::AMDGPU_Gfx
2630                                 ? &AMDGPU::CCR_SGPR_64RegClass
2631                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2632                         MVT::i64);
2633     Chain =
2634         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2635     Flag = Chain.getValue(1);
2636     RetOps.push_back(ReturnAddrVirtualReg);
2637   }
2638 
2639   // Copy the result values into the output registers.
2640   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2641        ++I, ++RealRVLocIdx) {
2642     CCValAssign &VA = RVLocs[I];
2643     assert(VA.isRegLoc() && "Can only return in registers!");
2644     // TODO: Partially return in registers if return values don't fit.
2645     SDValue Arg = OutVals[RealRVLocIdx];
2646 
2647     // Copied from other backends.
2648     switch (VA.getLocInfo()) {
2649     case CCValAssign::Full:
2650       break;
2651     case CCValAssign::BCvt:
2652       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2653       break;
2654     case CCValAssign::SExt:
2655       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2656       break;
2657     case CCValAssign::ZExt:
2658       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2659       break;
2660     case CCValAssign::AExt:
2661       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2662       break;
2663     default:
2664       llvm_unreachable("Unknown loc info!");
2665     }
2666 
2667     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2668     Flag = Chain.getValue(1);
2669     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2670   }
2671 
2672   // FIXME: Does sret work properly?
2673   if (!Info->isEntryFunction()) {
2674     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2675     const MCPhysReg *I =
2676       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2677     if (I) {
2678       for (; *I; ++I) {
2679         if (AMDGPU::SReg_64RegClass.contains(*I))
2680           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2681         else if (AMDGPU::SReg_32RegClass.contains(*I))
2682           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2683         else
2684           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2685       }
2686     }
2687   }
2688 
2689   // Update chain and glue.
2690   RetOps[0] = Chain;
2691   if (Flag.getNode())
2692     RetOps.push_back(Flag);
2693 
2694   unsigned Opc = AMDGPUISD::ENDPGM;
2695   if (!IsWaveEnd) {
2696     if (IsShader)
2697       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2698     else if (CallConv == CallingConv::AMDGPU_Gfx)
2699       Opc = AMDGPUISD::RET_GFX_FLAG;
2700     else
2701       Opc = AMDGPUISD::RET_FLAG;
2702   }
2703 
2704   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2705 }
2706 
2707 SDValue SITargetLowering::LowerCallResult(
2708     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2709     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2710     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2711     SDValue ThisVal) const {
2712   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2713 
2714   // Assign locations to each value returned by this call.
2715   SmallVector<CCValAssign, 16> RVLocs;
2716   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2717                  *DAG.getContext());
2718   CCInfo.AnalyzeCallResult(Ins, RetCC);
2719 
2720   // Copy all of the result registers out of their specified physreg.
2721   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2722     CCValAssign VA = RVLocs[i];
2723     SDValue Val;
2724 
2725     if (VA.isRegLoc()) {
2726       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2727       Chain = Val.getValue(1);
2728       InFlag = Val.getValue(2);
2729     } else if (VA.isMemLoc()) {
2730       report_fatal_error("TODO: return values in memory");
2731     } else
2732       llvm_unreachable("unknown argument location type");
2733 
2734     switch (VA.getLocInfo()) {
2735     case CCValAssign::Full:
2736       break;
2737     case CCValAssign::BCvt:
2738       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2739       break;
2740     case CCValAssign::ZExt:
2741       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2742                         DAG.getValueType(VA.getValVT()));
2743       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2744       break;
2745     case CCValAssign::SExt:
2746       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2747                         DAG.getValueType(VA.getValVT()));
2748       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2749       break;
2750     case CCValAssign::AExt:
2751       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2752       break;
2753     default:
2754       llvm_unreachable("Unknown loc info!");
2755     }
2756 
2757     InVals.push_back(Val);
2758   }
2759 
2760   return Chain;
2761 }
2762 
2763 // Add code to pass special inputs required depending on used features separate
2764 // from the explicit user arguments present in the IR.
2765 void SITargetLowering::passSpecialInputs(
2766     CallLoweringInfo &CLI,
2767     CCState &CCInfo,
2768     const SIMachineFunctionInfo &Info,
2769     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2770     SmallVectorImpl<SDValue> &MemOpChains,
2771     SDValue Chain) const {
2772   // If we don't have a call site, this was a call inserted by
2773   // legalization. These can never use special inputs.
2774   if (!CLI.CB)
2775     return;
2776 
2777   SelectionDAG &DAG = CLI.DAG;
2778   const SDLoc &DL = CLI.DL;
2779 
2780   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2781   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2782 
2783   const AMDGPUFunctionArgInfo *CalleeArgInfo
2784     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2785   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2786     auto &ArgUsageInfo =
2787       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2788     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2789   }
2790 
2791   // TODO: Unify with private memory register handling. This is complicated by
2792   // the fact that at least in kernels, the input argument is not necessarily
2793   // in the same location as the input.
2794   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2795                              StringLiteral> ImplicitAttrs[] = {
2796     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2797     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2798     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2799     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2800     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2801     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2802     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2803   };
2804 
2805   for (auto Attr : ImplicitAttrs) {
2806     const ArgDescriptor *OutgoingArg;
2807     const TargetRegisterClass *ArgRC;
2808     LLT ArgTy;
2809 
2810     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2811 
2812     // If the callee does not use the attribute value, skip copying the value.
2813     if (CLI.CB->hasFnAttr(Attr.second))
2814       continue;
2815 
2816     std::tie(OutgoingArg, ArgRC, ArgTy) =
2817         CalleeArgInfo->getPreloadedValue(InputID);
2818     if (!OutgoingArg)
2819       continue;
2820 
2821     const ArgDescriptor *IncomingArg;
2822     const TargetRegisterClass *IncomingArgRC;
2823     LLT Ty;
2824     std::tie(IncomingArg, IncomingArgRC, Ty) =
2825         CallerArgInfo.getPreloadedValue(InputID);
2826     assert(IncomingArgRC == ArgRC);
2827 
2828     // All special arguments are ints for now.
2829     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2830     SDValue InputReg;
2831 
2832     if (IncomingArg) {
2833       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2834     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2835       // The implicit arg ptr is special because it doesn't have a corresponding
2836       // input for kernels, and is computed from the kernarg segment pointer.
2837       InputReg = getImplicitArgPtr(DAG, DL);
2838     } else {
2839       // We may have proven the input wasn't needed, although the ABI is
2840       // requiring it. We just need to allocate the register appropriately.
2841       InputReg = DAG.getUNDEF(ArgVT);
2842     }
2843 
2844     if (OutgoingArg->isRegister()) {
2845       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2846       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2847         report_fatal_error("failed to allocate implicit input argument");
2848     } else {
2849       unsigned SpecialArgOffset =
2850           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2851       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2852                                               SpecialArgOffset);
2853       MemOpChains.push_back(ArgStore);
2854     }
2855   }
2856 
2857   // Pack workitem IDs into a single register or pass it as is if already
2858   // packed.
2859   const ArgDescriptor *OutgoingArg;
2860   const TargetRegisterClass *ArgRC;
2861   LLT Ty;
2862 
2863   std::tie(OutgoingArg, ArgRC, Ty) =
2864       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2865   if (!OutgoingArg)
2866     std::tie(OutgoingArg, ArgRC, Ty) =
2867         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2868   if (!OutgoingArg)
2869     std::tie(OutgoingArg, ArgRC, Ty) =
2870         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2871   if (!OutgoingArg)
2872     return;
2873 
2874   const ArgDescriptor *IncomingArgX = std::get<0>(
2875       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2876   const ArgDescriptor *IncomingArgY = std::get<0>(
2877       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2878   const ArgDescriptor *IncomingArgZ = std::get<0>(
2879       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2880 
2881   SDValue InputReg;
2882   SDLoc SL;
2883 
2884   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2885   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2886   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2887 
2888   // If incoming ids are not packed we need to pack them.
2889   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2890       NeedWorkItemIDX)
2891     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2892 
2893   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2894       NeedWorkItemIDY) {
2895     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2896     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2897                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2898     InputReg = InputReg.getNode() ?
2899                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2900   }
2901 
2902   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2903       NeedWorkItemIDZ) {
2904     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2905     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2906                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2907     InputReg = InputReg.getNode() ?
2908                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2909   }
2910 
2911   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2912     // Workitem ids are already packed, any of present incoming arguments
2913     // will carry all required fields.
2914     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2915       IncomingArgX ? *IncomingArgX :
2916       IncomingArgY ? *IncomingArgY :
2917                      *IncomingArgZ, ~0u);
2918     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2919   }
2920 
2921   if (OutgoingArg->isRegister()) {
2922     if (InputReg)
2923       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2924 
2925     CCInfo.AllocateReg(OutgoingArg->getRegister());
2926   } else {
2927     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2928     if (InputReg) {
2929       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2930                                               SpecialArgOffset);
2931       MemOpChains.push_back(ArgStore);
2932     }
2933   }
2934 }
2935 
2936 static bool canGuaranteeTCO(CallingConv::ID CC) {
2937   return CC == CallingConv::Fast;
2938 }
2939 
2940 /// Return true if we might ever do TCO for calls with this calling convention.
2941 static bool mayTailCallThisCC(CallingConv::ID CC) {
2942   switch (CC) {
2943   case CallingConv::C:
2944   case CallingConv::AMDGPU_Gfx:
2945     return true;
2946   default:
2947     return canGuaranteeTCO(CC);
2948   }
2949 }
2950 
2951 bool SITargetLowering::isEligibleForTailCallOptimization(
2952     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2953     const SmallVectorImpl<ISD::OutputArg> &Outs,
2954     const SmallVectorImpl<SDValue> &OutVals,
2955     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2956   if (!mayTailCallThisCC(CalleeCC))
2957     return false;
2958 
2959   // For a divergent call target, we need to do a waterfall loop over the
2960   // possible callees which precludes us from using a simple jump.
2961   if (Callee->isDivergent())
2962     return false;
2963 
2964   MachineFunction &MF = DAG.getMachineFunction();
2965   const Function &CallerF = MF.getFunction();
2966   CallingConv::ID CallerCC = CallerF.getCallingConv();
2967   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2968   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2969 
2970   // Kernels aren't callable, and don't have a live in return address so it
2971   // doesn't make sense to do a tail call with entry functions.
2972   if (!CallerPreserved)
2973     return false;
2974 
2975   bool CCMatch = CallerCC == CalleeCC;
2976 
2977   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2978     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2979       return true;
2980     return false;
2981   }
2982 
2983   // TODO: Can we handle var args?
2984   if (IsVarArg)
2985     return false;
2986 
2987   for (const Argument &Arg : CallerF.args()) {
2988     if (Arg.hasByValAttr())
2989       return false;
2990   }
2991 
2992   LLVMContext &Ctx = *DAG.getContext();
2993 
2994   // Check that the call results are passed in the same way.
2995   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2996                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2997                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2998     return false;
2999 
3000   // The callee has to preserve all registers the caller needs to preserve.
3001   if (!CCMatch) {
3002     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3003     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3004       return false;
3005   }
3006 
3007   // Nothing more to check if the callee is taking no arguments.
3008   if (Outs.empty())
3009     return true;
3010 
3011   SmallVector<CCValAssign, 16> ArgLocs;
3012   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3013 
3014   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3015 
3016   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3017   // If the stack arguments for this call do not fit into our own save area then
3018   // the call cannot be made tail.
3019   // TODO: Is this really necessary?
3020   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3021     return false;
3022 
3023   const MachineRegisterInfo &MRI = MF.getRegInfo();
3024   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3025 }
3026 
3027 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3028   if (!CI->isTailCall())
3029     return false;
3030 
3031   const Function *ParentFn = CI->getParent()->getParent();
3032   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3033     return false;
3034   return true;
3035 }
3036 
3037 // The wave scratch offset register is used as the global base pointer.
3038 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3039                                     SmallVectorImpl<SDValue> &InVals) const {
3040   SelectionDAG &DAG = CLI.DAG;
3041   const SDLoc &DL = CLI.DL;
3042   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3043   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3044   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3045   SDValue Chain = CLI.Chain;
3046   SDValue Callee = CLI.Callee;
3047   bool &IsTailCall = CLI.IsTailCall;
3048   CallingConv::ID CallConv = CLI.CallConv;
3049   bool IsVarArg = CLI.IsVarArg;
3050   bool IsSibCall = false;
3051   bool IsThisReturn = false;
3052   MachineFunction &MF = DAG.getMachineFunction();
3053 
3054   if (Callee.isUndef() || isNullConstant(Callee)) {
3055     if (!CLI.IsTailCall) {
3056       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3057         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3058     }
3059 
3060     return Chain;
3061   }
3062 
3063   if (IsVarArg) {
3064     return lowerUnhandledCall(CLI, InVals,
3065                               "unsupported call to variadic function ");
3066   }
3067 
3068   if (!CLI.CB)
3069     report_fatal_error("unsupported libcall legalization");
3070 
3071   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3072     return lowerUnhandledCall(CLI, InVals,
3073                               "unsupported required tail call to function ");
3074   }
3075 
3076   if (AMDGPU::isShader(CallConv)) {
3077     // Note the issue is with the CC of the called function, not of the call
3078     // itself.
3079     return lowerUnhandledCall(CLI, InVals,
3080                               "unsupported call to a shader function ");
3081   }
3082 
3083   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3084       CallConv != CallingConv::AMDGPU_Gfx) {
3085     // Only allow calls with specific calling conventions.
3086     return lowerUnhandledCall(CLI, InVals,
3087                               "unsupported calling convention for call from "
3088                               "graphics shader of function ");
3089   }
3090 
3091   if (IsTailCall) {
3092     IsTailCall = isEligibleForTailCallOptimization(
3093       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3094     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3095       report_fatal_error("failed to perform tail call elimination on a call "
3096                          "site marked musttail");
3097     }
3098 
3099     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3100 
3101     // A sibling call is one where we're under the usual C ABI and not planning
3102     // to change that but can still do a tail call:
3103     if (!TailCallOpt && IsTailCall)
3104       IsSibCall = true;
3105 
3106     if (IsTailCall)
3107       ++NumTailCalls;
3108   }
3109 
3110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3111   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3112   SmallVector<SDValue, 8> MemOpChains;
3113 
3114   // Analyze operands of the call, assigning locations to each operand.
3115   SmallVector<CCValAssign, 16> ArgLocs;
3116   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3117   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3118 
3119   if (CallConv != CallingConv::AMDGPU_Gfx) {
3120     // With a fixed ABI, allocate fixed registers before user arguments.
3121     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3122   }
3123 
3124   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3125 
3126   // Get a count of how many bytes are to be pushed on the stack.
3127   unsigned NumBytes = CCInfo.getNextStackOffset();
3128 
3129   if (IsSibCall) {
3130     // Since we're not changing the ABI to make this a tail call, the memory
3131     // operands are already available in the caller's incoming argument space.
3132     NumBytes = 0;
3133   }
3134 
3135   // FPDiff is the byte offset of the call's argument area from the callee's.
3136   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3137   // by this amount for a tail call. In a sibling call it must be 0 because the
3138   // caller will deallocate the entire stack and the callee still expects its
3139   // arguments to begin at SP+0. Completely unused for non-tail calls.
3140   int32_t FPDiff = 0;
3141   MachineFrameInfo &MFI = MF.getFrameInfo();
3142 
3143   // Adjust the stack pointer for the new arguments...
3144   // These operations are automatically eliminated by the prolog/epilog pass
3145   if (!IsSibCall) {
3146     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3147 
3148     if (!Subtarget->enableFlatScratch()) {
3149       SmallVector<SDValue, 4> CopyFromChains;
3150 
3151       // In the HSA case, this should be an identity copy.
3152       SDValue ScratchRSrcReg
3153         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3154       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3155       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3156       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3157     }
3158   }
3159 
3160   MVT PtrVT = MVT::i32;
3161 
3162   // Walk the register/memloc assignments, inserting copies/loads.
3163   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3164     CCValAssign &VA = ArgLocs[i];
3165     SDValue Arg = OutVals[i];
3166 
3167     // Promote the value if needed.
3168     switch (VA.getLocInfo()) {
3169     case CCValAssign::Full:
3170       break;
3171     case CCValAssign::BCvt:
3172       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3173       break;
3174     case CCValAssign::ZExt:
3175       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3176       break;
3177     case CCValAssign::SExt:
3178       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3179       break;
3180     case CCValAssign::AExt:
3181       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3182       break;
3183     case CCValAssign::FPExt:
3184       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3185       break;
3186     default:
3187       llvm_unreachable("Unknown loc info!");
3188     }
3189 
3190     if (VA.isRegLoc()) {
3191       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3192     } else {
3193       assert(VA.isMemLoc());
3194 
3195       SDValue DstAddr;
3196       MachinePointerInfo DstInfo;
3197 
3198       unsigned LocMemOffset = VA.getLocMemOffset();
3199       int32_t Offset = LocMemOffset;
3200 
3201       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3202       MaybeAlign Alignment;
3203 
3204       if (IsTailCall) {
3205         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3206         unsigned OpSize = Flags.isByVal() ?
3207           Flags.getByValSize() : VA.getValVT().getStoreSize();
3208 
3209         // FIXME: We can have better than the minimum byval required alignment.
3210         Alignment =
3211             Flags.isByVal()
3212                 ? Flags.getNonZeroByValAlign()
3213                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3214 
3215         Offset = Offset + FPDiff;
3216         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3217 
3218         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3219         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3220 
3221         // Make sure any stack arguments overlapping with where we're storing
3222         // are loaded before this eventual operation. Otherwise they'll be
3223         // clobbered.
3224 
3225         // FIXME: Why is this really necessary? This seems to just result in a
3226         // lot of code to copy the stack and write them back to the same
3227         // locations, which are supposed to be immutable?
3228         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3229       } else {
3230         // Stores to the argument stack area are relative to the stack pointer.
3231         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3232                                         MVT::i32);
3233         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3234         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3235         Alignment =
3236             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3237       }
3238 
3239       if (Outs[i].Flags.isByVal()) {
3240         SDValue SizeNode =
3241             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3242         SDValue Cpy =
3243             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3244                           Outs[i].Flags.getNonZeroByValAlign(),
3245                           /*isVol = */ false, /*AlwaysInline = */ true,
3246                           /*isTailCall = */ false, DstInfo,
3247                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3248 
3249         MemOpChains.push_back(Cpy);
3250       } else {
3251         SDValue Store =
3252             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3253         MemOpChains.push_back(Store);
3254       }
3255     }
3256   }
3257 
3258   if (!MemOpChains.empty())
3259     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3260 
3261   // Build a sequence of copy-to-reg nodes chained together with token chain
3262   // and flag operands which copy the outgoing args into the appropriate regs.
3263   SDValue InFlag;
3264   for (auto &RegToPass : RegsToPass) {
3265     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3266                              RegToPass.second, InFlag);
3267     InFlag = Chain.getValue(1);
3268   }
3269 
3270 
3271   SDValue PhysReturnAddrReg;
3272   if (IsTailCall) {
3273     // Since the return is being combined with the call, we need to pass on the
3274     // return address.
3275 
3276     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3277     SDValue ReturnAddrReg = CreateLiveInRegister(
3278       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3279 
3280     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3281                                         MVT::i64);
3282     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3283     InFlag = Chain.getValue(1);
3284   }
3285 
3286   // We don't usually want to end the call-sequence here because we would tidy
3287   // the frame up *after* the call, however in the ABI-changing tail-call case
3288   // we've carefully laid out the parameters so that when sp is reset they'll be
3289   // in the correct location.
3290   if (IsTailCall && !IsSibCall) {
3291     Chain = DAG.getCALLSEQ_END(Chain,
3292                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3293                                DAG.getTargetConstant(0, DL, MVT::i32),
3294                                InFlag, DL);
3295     InFlag = Chain.getValue(1);
3296   }
3297 
3298   std::vector<SDValue> Ops;
3299   Ops.push_back(Chain);
3300   Ops.push_back(Callee);
3301   // Add a redundant copy of the callee global which will not be legalized, as
3302   // we need direct access to the callee later.
3303   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3304     const GlobalValue *GV = GSD->getGlobal();
3305     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3306   } else {
3307     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3308   }
3309 
3310   if (IsTailCall) {
3311     // Each tail call may have to adjust the stack by a different amount, so
3312     // this information must travel along with the operation for eventual
3313     // consumption by emitEpilogue.
3314     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3315 
3316     Ops.push_back(PhysReturnAddrReg);
3317   }
3318 
3319   // Add argument registers to the end of the list so that they are known live
3320   // into the call.
3321   for (auto &RegToPass : RegsToPass) {
3322     Ops.push_back(DAG.getRegister(RegToPass.first,
3323                                   RegToPass.second.getValueType()));
3324   }
3325 
3326   // Add a register mask operand representing the call-preserved registers.
3327 
3328   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3329   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3330   assert(Mask && "Missing call preserved mask for calling convention");
3331   Ops.push_back(DAG.getRegisterMask(Mask));
3332 
3333   if (InFlag.getNode())
3334     Ops.push_back(InFlag);
3335 
3336   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3337 
3338   // If we're doing a tall call, use a TC_RETURN here rather than an
3339   // actual call instruction.
3340   if (IsTailCall) {
3341     MFI.setHasTailCall();
3342     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3343   }
3344 
3345   // Returns a chain and a flag for retval copy to use.
3346   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3347   Chain = Call.getValue(0);
3348   InFlag = Call.getValue(1);
3349 
3350   uint64_t CalleePopBytes = NumBytes;
3351   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3352                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3353                              InFlag, DL);
3354   if (!Ins.empty())
3355     InFlag = Chain.getValue(1);
3356 
3357   // Handle result values, copying them out of physregs into vregs that we
3358   // return.
3359   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3360                          InVals, IsThisReturn,
3361                          IsThisReturn ? OutVals[0] : SDValue());
3362 }
3363 
3364 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3365 // except for applying the wave size scale to the increment amount.
3366 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3367     SDValue Op, SelectionDAG &DAG) const {
3368   const MachineFunction &MF = DAG.getMachineFunction();
3369   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3370 
3371   SDLoc dl(Op);
3372   EVT VT = Op.getValueType();
3373   SDValue Tmp1 = Op;
3374   SDValue Tmp2 = Op.getValue(1);
3375   SDValue Tmp3 = Op.getOperand(2);
3376   SDValue Chain = Tmp1.getOperand(0);
3377 
3378   Register SPReg = Info->getStackPtrOffsetReg();
3379 
3380   // Chain the dynamic stack allocation so that it doesn't modify the stack
3381   // pointer when other instructions are using the stack.
3382   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3383 
3384   SDValue Size  = Tmp2.getOperand(1);
3385   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3386   Chain = SP.getValue(1);
3387   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3388   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3389   const TargetFrameLowering *TFL = ST.getFrameLowering();
3390   unsigned Opc =
3391     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3392     ISD::ADD : ISD::SUB;
3393 
3394   SDValue ScaledSize = DAG.getNode(
3395       ISD::SHL, dl, VT, Size,
3396       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3397 
3398   Align StackAlign = TFL->getStackAlign();
3399   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3400   if (Alignment && *Alignment > StackAlign) {
3401     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3402                        DAG.getConstant(-(uint64_t)Alignment->value()
3403                                            << ST.getWavefrontSizeLog2(),
3404                                        dl, VT));
3405   }
3406 
3407   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3408   Tmp2 = DAG.getCALLSEQ_END(
3409       Chain, DAG.getIntPtrConstant(0, dl, true),
3410       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3411 
3412   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3413 }
3414 
3415 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3416                                                   SelectionDAG &DAG) const {
3417   // We only handle constant sizes here to allow non-entry block, static sized
3418   // allocas. A truly dynamic value is more difficult to support because we
3419   // don't know if the size value is uniform or not. If the size isn't uniform,
3420   // we would need to do a wave reduction to get the maximum size to know how
3421   // much to increment the uniform stack pointer.
3422   SDValue Size = Op.getOperand(1);
3423   if (isa<ConstantSDNode>(Size))
3424       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3425 
3426   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3427 }
3428 
3429 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3430                                              const MachineFunction &MF) const {
3431   Register Reg = StringSwitch<Register>(RegName)
3432     .Case("m0", AMDGPU::M0)
3433     .Case("exec", AMDGPU::EXEC)
3434     .Case("exec_lo", AMDGPU::EXEC_LO)
3435     .Case("exec_hi", AMDGPU::EXEC_HI)
3436     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3437     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3438     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3439     .Default(Register());
3440 
3441   if (Reg == AMDGPU::NoRegister) {
3442     report_fatal_error(Twine("invalid register name \""
3443                              + StringRef(RegName)  + "\"."));
3444 
3445   }
3446 
3447   if (!Subtarget->hasFlatScrRegister() &&
3448        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3449     report_fatal_error(Twine("invalid register \""
3450                              + StringRef(RegName)  + "\" for subtarget."));
3451   }
3452 
3453   switch (Reg) {
3454   case AMDGPU::M0:
3455   case AMDGPU::EXEC_LO:
3456   case AMDGPU::EXEC_HI:
3457   case AMDGPU::FLAT_SCR_LO:
3458   case AMDGPU::FLAT_SCR_HI:
3459     if (VT.getSizeInBits() == 32)
3460       return Reg;
3461     break;
3462   case AMDGPU::EXEC:
3463   case AMDGPU::FLAT_SCR:
3464     if (VT.getSizeInBits() == 64)
3465       return Reg;
3466     break;
3467   default:
3468     llvm_unreachable("missing register type checking");
3469   }
3470 
3471   report_fatal_error(Twine("invalid type for register \""
3472                            + StringRef(RegName) + "\"."));
3473 }
3474 
3475 // If kill is not the last instruction, split the block so kill is always a
3476 // proper terminator.
3477 MachineBasicBlock *
3478 SITargetLowering::splitKillBlock(MachineInstr &MI,
3479                                  MachineBasicBlock *BB) const {
3480   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3481   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3482   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3483   return SplitBB;
3484 }
3485 
3486 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3487 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3488 // be the first instruction in the remainder block.
3489 //
3490 /// \returns { LoopBody, Remainder }
3491 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3492 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3493   MachineFunction *MF = MBB.getParent();
3494   MachineBasicBlock::iterator I(&MI);
3495 
3496   // To insert the loop we need to split the block. Move everything after this
3497   // point to a new block, and insert a new empty block between the two.
3498   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3499   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3500   MachineFunction::iterator MBBI(MBB);
3501   ++MBBI;
3502 
3503   MF->insert(MBBI, LoopBB);
3504   MF->insert(MBBI, RemainderBB);
3505 
3506   LoopBB->addSuccessor(LoopBB);
3507   LoopBB->addSuccessor(RemainderBB);
3508 
3509   // Move the rest of the block into a new block.
3510   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3511 
3512   if (InstInLoop) {
3513     auto Next = std::next(I);
3514 
3515     // Move instruction to loop body.
3516     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3517 
3518     // Move the rest of the block.
3519     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3520   } else {
3521     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3522   }
3523 
3524   MBB.addSuccessor(LoopBB);
3525 
3526   return std::make_pair(LoopBB, RemainderBB);
3527 }
3528 
3529 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3530 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3531   MachineBasicBlock *MBB = MI.getParent();
3532   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3533   auto I = MI.getIterator();
3534   auto E = std::next(I);
3535 
3536   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3537     .addImm(0);
3538 
3539   MIBundleBuilder Bundler(*MBB, I, E);
3540   finalizeBundle(*MBB, Bundler.begin());
3541 }
3542 
3543 MachineBasicBlock *
3544 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3545                                          MachineBasicBlock *BB) const {
3546   const DebugLoc &DL = MI.getDebugLoc();
3547 
3548   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3549 
3550   MachineBasicBlock *LoopBB;
3551   MachineBasicBlock *RemainderBB;
3552   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3553 
3554   // Apparently kill flags are only valid if the def is in the same block?
3555   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3556     Src->setIsKill(false);
3557 
3558   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3559 
3560   MachineBasicBlock::iterator I = LoopBB->end();
3561 
3562   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3563     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3564 
3565   // Clear TRAP_STS.MEM_VIOL
3566   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3567     .addImm(0)
3568     .addImm(EncodedReg);
3569 
3570   bundleInstWithWaitcnt(MI);
3571 
3572   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3573 
3574   // Load and check TRAP_STS.MEM_VIOL
3575   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3576     .addImm(EncodedReg);
3577 
3578   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3579   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3580     .addReg(Reg, RegState::Kill)
3581     .addImm(0);
3582   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3583     .addMBB(LoopBB);
3584 
3585   return RemainderBB;
3586 }
3587 
3588 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3589 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3590 // will only do one iteration. In the worst case, this will loop 64 times.
3591 //
3592 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3593 static MachineBasicBlock::iterator
3594 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3595                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3596                        const DebugLoc &DL, const MachineOperand &Idx,
3597                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3598                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3599                        Register &SGPRIdxReg) {
3600 
3601   MachineFunction *MF = OrigBB.getParent();
3602   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3603   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3604   MachineBasicBlock::iterator I = LoopBB.begin();
3605 
3606   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3607   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3608   Register NewExec = MRI.createVirtualRegister(BoolRC);
3609   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3610   Register CondReg = MRI.createVirtualRegister(BoolRC);
3611 
3612   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3613     .addReg(InitReg)
3614     .addMBB(&OrigBB)
3615     .addReg(ResultReg)
3616     .addMBB(&LoopBB);
3617 
3618   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3619     .addReg(InitSaveExecReg)
3620     .addMBB(&OrigBB)
3621     .addReg(NewExec)
3622     .addMBB(&LoopBB);
3623 
3624   // Read the next variant <- also loop target.
3625   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3626       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3627 
3628   // Compare the just read M0 value to all possible Idx values.
3629   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3630       .addReg(CurrentIdxReg)
3631       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3632 
3633   // Update EXEC, save the original EXEC value to VCC.
3634   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3635                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3636           NewExec)
3637     .addReg(CondReg, RegState::Kill);
3638 
3639   MRI.setSimpleHint(NewExec, CondReg);
3640 
3641   if (UseGPRIdxMode) {
3642     if (Offset == 0) {
3643       SGPRIdxReg = CurrentIdxReg;
3644     } else {
3645       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3646       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3647           .addReg(CurrentIdxReg, RegState::Kill)
3648           .addImm(Offset);
3649     }
3650   } else {
3651     // Move index from VCC into M0
3652     if (Offset == 0) {
3653       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3654         .addReg(CurrentIdxReg, RegState::Kill);
3655     } else {
3656       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3657         .addReg(CurrentIdxReg, RegState::Kill)
3658         .addImm(Offset);
3659     }
3660   }
3661 
3662   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3663   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3664   MachineInstr *InsertPt =
3665     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3666                                                   : AMDGPU::S_XOR_B64_term), Exec)
3667       .addReg(Exec)
3668       .addReg(NewExec);
3669 
3670   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3671   // s_cbranch_scc0?
3672 
3673   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3674   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3675     .addMBB(&LoopBB);
3676 
3677   return InsertPt->getIterator();
3678 }
3679 
3680 // This has slightly sub-optimal regalloc when the source vector is killed by
3681 // the read. The register allocator does not understand that the kill is
3682 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3683 // subregister from it, using 1 more VGPR than necessary. This was saved when
3684 // this was expanded after register allocation.
3685 static MachineBasicBlock::iterator
3686 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3687                unsigned InitResultReg, unsigned PhiReg, int Offset,
3688                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3689   MachineFunction *MF = MBB.getParent();
3690   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3691   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3692   MachineRegisterInfo &MRI = MF->getRegInfo();
3693   const DebugLoc &DL = MI.getDebugLoc();
3694   MachineBasicBlock::iterator I(&MI);
3695 
3696   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3697   Register DstReg = MI.getOperand(0).getReg();
3698   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3699   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3700   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3701   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3702 
3703   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3704 
3705   // Save the EXEC mask
3706   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3707     .addReg(Exec);
3708 
3709   MachineBasicBlock *LoopBB;
3710   MachineBasicBlock *RemainderBB;
3711   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3712 
3713   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3714 
3715   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3716                                       InitResultReg, DstReg, PhiReg, TmpExec,
3717                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3718 
3719   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3720   MachineFunction::iterator MBBI(LoopBB);
3721   ++MBBI;
3722   MF->insert(MBBI, LandingPad);
3723   LoopBB->removeSuccessor(RemainderBB);
3724   LandingPad->addSuccessor(RemainderBB);
3725   LoopBB->addSuccessor(LandingPad);
3726   MachineBasicBlock::iterator First = LandingPad->begin();
3727   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3728     .addReg(SaveExec);
3729 
3730   return InsPt;
3731 }
3732 
3733 // Returns subreg index, offset
3734 static std::pair<unsigned, int>
3735 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3736                             const TargetRegisterClass *SuperRC,
3737                             unsigned VecReg,
3738                             int Offset) {
3739   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3740 
3741   // Skip out of bounds offsets, or else we would end up using an undefined
3742   // register.
3743   if (Offset >= NumElts || Offset < 0)
3744     return std::make_pair(AMDGPU::sub0, Offset);
3745 
3746   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3747 }
3748 
3749 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3750                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3751                                  int Offset) {
3752   MachineBasicBlock *MBB = MI.getParent();
3753   const DebugLoc &DL = MI.getDebugLoc();
3754   MachineBasicBlock::iterator I(&MI);
3755 
3756   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3757 
3758   assert(Idx->getReg() != AMDGPU::NoRegister);
3759 
3760   if (Offset == 0) {
3761     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3762   } else {
3763     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3764         .add(*Idx)
3765         .addImm(Offset);
3766   }
3767 }
3768 
3769 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3770                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3771                                    int Offset) {
3772   MachineBasicBlock *MBB = MI.getParent();
3773   const DebugLoc &DL = MI.getDebugLoc();
3774   MachineBasicBlock::iterator I(&MI);
3775 
3776   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3777 
3778   if (Offset == 0)
3779     return Idx->getReg();
3780 
3781   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3782   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3783       .add(*Idx)
3784       .addImm(Offset);
3785   return Tmp;
3786 }
3787 
3788 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3789                                           MachineBasicBlock &MBB,
3790                                           const GCNSubtarget &ST) {
3791   const SIInstrInfo *TII = ST.getInstrInfo();
3792   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3793   MachineFunction *MF = MBB.getParent();
3794   MachineRegisterInfo &MRI = MF->getRegInfo();
3795 
3796   Register Dst = MI.getOperand(0).getReg();
3797   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3798   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3799   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3800 
3801   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3802   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3803 
3804   unsigned SubReg;
3805   std::tie(SubReg, Offset)
3806     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3807 
3808   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3809 
3810   // Check for a SGPR index.
3811   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3812     MachineBasicBlock::iterator I(&MI);
3813     const DebugLoc &DL = MI.getDebugLoc();
3814 
3815     if (UseGPRIdxMode) {
3816       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3817       // to avoid interfering with other uses, so probably requires a new
3818       // optimization pass.
3819       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3820 
3821       const MCInstrDesc &GPRIDXDesc =
3822           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3823       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3824           .addReg(SrcReg)
3825           .addReg(Idx)
3826           .addImm(SubReg);
3827     } else {
3828       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3829 
3830       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3831         .addReg(SrcReg, 0, SubReg)
3832         .addReg(SrcReg, RegState::Implicit);
3833     }
3834 
3835     MI.eraseFromParent();
3836 
3837     return &MBB;
3838   }
3839 
3840   // Control flow needs to be inserted if indexing with a VGPR.
3841   const DebugLoc &DL = MI.getDebugLoc();
3842   MachineBasicBlock::iterator I(&MI);
3843 
3844   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3845   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3846 
3847   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3848 
3849   Register SGPRIdxReg;
3850   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3851                               UseGPRIdxMode, SGPRIdxReg);
3852 
3853   MachineBasicBlock *LoopBB = InsPt->getParent();
3854 
3855   if (UseGPRIdxMode) {
3856     const MCInstrDesc &GPRIDXDesc =
3857         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3858 
3859     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3860         .addReg(SrcReg)
3861         .addReg(SGPRIdxReg)
3862         .addImm(SubReg);
3863   } else {
3864     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3865       .addReg(SrcReg, 0, SubReg)
3866       .addReg(SrcReg, RegState::Implicit);
3867   }
3868 
3869   MI.eraseFromParent();
3870 
3871   return LoopBB;
3872 }
3873 
3874 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3875                                           MachineBasicBlock &MBB,
3876                                           const GCNSubtarget &ST) {
3877   const SIInstrInfo *TII = ST.getInstrInfo();
3878   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3879   MachineFunction *MF = MBB.getParent();
3880   MachineRegisterInfo &MRI = MF->getRegInfo();
3881 
3882   Register Dst = MI.getOperand(0).getReg();
3883   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3884   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3885   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3886   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3887   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3888   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3889 
3890   // This can be an immediate, but will be folded later.
3891   assert(Val->getReg());
3892 
3893   unsigned SubReg;
3894   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3895                                                          SrcVec->getReg(),
3896                                                          Offset);
3897   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3898 
3899   if (Idx->getReg() == AMDGPU::NoRegister) {
3900     MachineBasicBlock::iterator I(&MI);
3901     const DebugLoc &DL = MI.getDebugLoc();
3902 
3903     assert(Offset == 0);
3904 
3905     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3906         .add(*SrcVec)
3907         .add(*Val)
3908         .addImm(SubReg);
3909 
3910     MI.eraseFromParent();
3911     return &MBB;
3912   }
3913 
3914   // Check for a SGPR index.
3915   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3916     MachineBasicBlock::iterator I(&MI);
3917     const DebugLoc &DL = MI.getDebugLoc();
3918 
3919     if (UseGPRIdxMode) {
3920       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3921 
3922       const MCInstrDesc &GPRIDXDesc =
3923           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3924       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3925           .addReg(SrcVec->getReg())
3926           .add(*Val)
3927           .addReg(Idx)
3928           .addImm(SubReg);
3929     } else {
3930       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3931 
3932       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3933           TRI.getRegSizeInBits(*VecRC), 32, false);
3934       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3935           .addReg(SrcVec->getReg())
3936           .add(*Val)
3937           .addImm(SubReg);
3938     }
3939     MI.eraseFromParent();
3940     return &MBB;
3941   }
3942 
3943   // Control flow needs to be inserted if indexing with a VGPR.
3944   if (Val->isReg())
3945     MRI.clearKillFlags(Val->getReg());
3946 
3947   const DebugLoc &DL = MI.getDebugLoc();
3948 
3949   Register PhiReg = MRI.createVirtualRegister(VecRC);
3950 
3951   Register SGPRIdxReg;
3952   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3953                               UseGPRIdxMode, SGPRIdxReg);
3954   MachineBasicBlock *LoopBB = InsPt->getParent();
3955 
3956   if (UseGPRIdxMode) {
3957     const MCInstrDesc &GPRIDXDesc =
3958         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3959 
3960     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3961         .addReg(PhiReg)
3962         .add(*Val)
3963         .addReg(SGPRIdxReg)
3964         .addImm(AMDGPU::sub0);
3965   } else {
3966     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3967         TRI.getRegSizeInBits(*VecRC), 32, false);
3968     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3969         .addReg(PhiReg)
3970         .add(*Val)
3971         .addImm(AMDGPU::sub0);
3972   }
3973 
3974   MI.eraseFromParent();
3975   return LoopBB;
3976 }
3977 
3978 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3979   MachineInstr &MI, MachineBasicBlock *BB) const {
3980 
3981   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3982   MachineFunction *MF = BB->getParent();
3983   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3984 
3985   switch (MI.getOpcode()) {
3986   case AMDGPU::S_UADDO_PSEUDO:
3987   case AMDGPU::S_USUBO_PSEUDO: {
3988     const DebugLoc &DL = MI.getDebugLoc();
3989     MachineOperand &Dest0 = MI.getOperand(0);
3990     MachineOperand &Dest1 = MI.getOperand(1);
3991     MachineOperand &Src0 = MI.getOperand(2);
3992     MachineOperand &Src1 = MI.getOperand(3);
3993 
3994     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3995                        ? AMDGPU::S_ADD_I32
3996                        : AMDGPU::S_SUB_I32;
3997     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3998 
3999     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4000         .addImm(1)
4001         .addImm(0);
4002 
4003     MI.eraseFromParent();
4004     return BB;
4005   }
4006   case AMDGPU::S_ADD_U64_PSEUDO:
4007   case AMDGPU::S_SUB_U64_PSEUDO: {
4008     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4009     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4010     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4011     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4012     const DebugLoc &DL = MI.getDebugLoc();
4013 
4014     MachineOperand &Dest = MI.getOperand(0);
4015     MachineOperand &Src0 = MI.getOperand(1);
4016     MachineOperand &Src1 = MI.getOperand(2);
4017 
4018     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4019     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4020 
4021     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4022         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4023     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4024         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4025 
4026     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4027         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4028     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4029         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4030 
4031     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4032 
4033     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4034     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4035     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4036     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4037     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4038         .addReg(DestSub0)
4039         .addImm(AMDGPU::sub0)
4040         .addReg(DestSub1)
4041         .addImm(AMDGPU::sub1);
4042     MI.eraseFromParent();
4043     return BB;
4044   }
4045   case AMDGPU::V_ADD_U64_PSEUDO:
4046   case AMDGPU::V_SUB_U64_PSEUDO: {
4047     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4048     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4049     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4050     const DebugLoc &DL = MI.getDebugLoc();
4051 
4052     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4053 
4054     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4055 
4056     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4057     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4058 
4059     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4060     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4061 
4062     MachineOperand &Dest = MI.getOperand(0);
4063     MachineOperand &Src0 = MI.getOperand(1);
4064     MachineOperand &Src1 = MI.getOperand(2);
4065 
4066     const TargetRegisterClass *Src0RC = Src0.isReg()
4067                                             ? MRI.getRegClass(Src0.getReg())
4068                                             : &AMDGPU::VReg_64RegClass;
4069     const TargetRegisterClass *Src1RC = Src1.isReg()
4070                                             ? MRI.getRegClass(Src1.getReg())
4071                                             : &AMDGPU::VReg_64RegClass;
4072 
4073     const TargetRegisterClass *Src0SubRC =
4074         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4075     const TargetRegisterClass *Src1SubRC =
4076         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4077 
4078     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4079         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4080     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4081         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4082 
4083     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4085     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4087 
4088     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4089     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4090                                .addReg(CarryReg, RegState::Define)
4091                                .add(SrcReg0Sub0)
4092                                .add(SrcReg1Sub0)
4093                                .addImm(0); // clamp bit
4094 
4095     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4096     MachineInstr *HiHalf =
4097         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4098             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4099             .add(SrcReg0Sub1)
4100             .add(SrcReg1Sub1)
4101             .addReg(CarryReg, RegState::Kill)
4102             .addImm(0); // clamp bit
4103 
4104     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4105         .addReg(DestSub0)
4106         .addImm(AMDGPU::sub0)
4107         .addReg(DestSub1)
4108         .addImm(AMDGPU::sub1);
4109     TII->legalizeOperands(*LoHalf);
4110     TII->legalizeOperands(*HiHalf);
4111     MI.eraseFromParent();
4112     return BB;
4113   }
4114   case AMDGPU::S_ADD_CO_PSEUDO:
4115   case AMDGPU::S_SUB_CO_PSEUDO: {
4116     // This pseudo has a chance to be selected
4117     // only from uniform add/subcarry node. All the VGPR operands
4118     // therefore assumed to be splat vectors.
4119     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4120     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4121     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4122     MachineBasicBlock::iterator MII = MI;
4123     const DebugLoc &DL = MI.getDebugLoc();
4124     MachineOperand &Dest = MI.getOperand(0);
4125     MachineOperand &CarryDest = MI.getOperand(1);
4126     MachineOperand &Src0 = MI.getOperand(2);
4127     MachineOperand &Src1 = MI.getOperand(3);
4128     MachineOperand &Src2 = MI.getOperand(4);
4129     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4130                        ? AMDGPU::S_ADDC_U32
4131                        : AMDGPU::S_SUBB_U32;
4132     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4133       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4134       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4135           .addReg(Src0.getReg());
4136       Src0.setReg(RegOp0);
4137     }
4138     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4139       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4140       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4141           .addReg(Src1.getReg());
4142       Src1.setReg(RegOp1);
4143     }
4144     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4145     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4146       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4147           .addReg(Src2.getReg());
4148       Src2.setReg(RegOp2);
4149     }
4150 
4151     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4152     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4153     assert(WaveSize == 64 || WaveSize == 32);
4154 
4155     if (WaveSize == 64) {
4156       if (ST.hasScalarCompareEq64()) {
4157         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4158             .addReg(Src2.getReg())
4159             .addImm(0);
4160       } else {
4161         const TargetRegisterClass *SubRC =
4162             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4163         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4164             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4165         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4166             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4167         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4168 
4169         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4170             .add(Src2Sub0)
4171             .add(Src2Sub1);
4172 
4173         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4174             .addReg(Src2_32, RegState::Kill)
4175             .addImm(0);
4176       }
4177     } else {
4178       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4179           .addReg(Src2.getReg())
4180           .addImm(0);
4181     }
4182 
4183     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4184 
4185     unsigned SelOpc =
4186         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4187 
4188     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4189         .addImm(-1)
4190         .addImm(0);
4191 
4192     MI.eraseFromParent();
4193     return BB;
4194   }
4195   case AMDGPU::SI_INIT_M0: {
4196     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4197             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4198         .add(MI.getOperand(0));
4199     MI.eraseFromParent();
4200     return BB;
4201   }
4202   case AMDGPU::GET_GROUPSTATICSIZE: {
4203     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4204            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4205     DebugLoc DL = MI.getDebugLoc();
4206     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4207         .add(MI.getOperand(0))
4208         .addImm(MFI->getLDSSize());
4209     MI.eraseFromParent();
4210     return BB;
4211   }
4212   case AMDGPU::SI_INDIRECT_SRC_V1:
4213   case AMDGPU::SI_INDIRECT_SRC_V2:
4214   case AMDGPU::SI_INDIRECT_SRC_V4:
4215   case AMDGPU::SI_INDIRECT_SRC_V8:
4216   case AMDGPU::SI_INDIRECT_SRC_V16:
4217   case AMDGPU::SI_INDIRECT_SRC_V32:
4218     return emitIndirectSrc(MI, *BB, *getSubtarget());
4219   case AMDGPU::SI_INDIRECT_DST_V1:
4220   case AMDGPU::SI_INDIRECT_DST_V2:
4221   case AMDGPU::SI_INDIRECT_DST_V4:
4222   case AMDGPU::SI_INDIRECT_DST_V8:
4223   case AMDGPU::SI_INDIRECT_DST_V16:
4224   case AMDGPU::SI_INDIRECT_DST_V32:
4225     return emitIndirectDst(MI, *BB, *getSubtarget());
4226   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4227   case AMDGPU::SI_KILL_I1_PSEUDO:
4228     return splitKillBlock(MI, BB);
4229   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4230     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4231     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4232     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4233 
4234     Register Dst = MI.getOperand(0).getReg();
4235     Register Src0 = MI.getOperand(1).getReg();
4236     Register Src1 = MI.getOperand(2).getReg();
4237     const DebugLoc &DL = MI.getDebugLoc();
4238     Register SrcCond = MI.getOperand(3).getReg();
4239 
4240     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4241     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4242     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4243     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4244 
4245     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4246       .addReg(SrcCond);
4247     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4248       .addImm(0)
4249       .addReg(Src0, 0, AMDGPU::sub0)
4250       .addImm(0)
4251       .addReg(Src1, 0, AMDGPU::sub0)
4252       .addReg(SrcCondCopy);
4253     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4254       .addImm(0)
4255       .addReg(Src0, 0, AMDGPU::sub1)
4256       .addImm(0)
4257       .addReg(Src1, 0, AMDGPU::sub1)
4258       .addReg(SrcCondCopy);
4259 
4260     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4261       .addReg(DstLo)
4262       .addImm(AMDGPU::sub0)
4263       .addReg(DstHi)
4264       .addImm(AMDGPU::sub1);
4265     MI.eraseFromParent();
4266     return BB;
4267   }
4268   case AMDGPU::SI_BR_UNDEF: {
4269     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4270     const DebugLoc &DL = MI.getDebugLoc();
4271     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4272                            .add(MI.getOperand(0));
4273     Br->getOperand(1).setIsUndef(true); // read undef SCC
4274     MI.eraseFromParent();
4275     return BB;
4276   }
4277   case AMDGPU::ADJCALLSTACKUP:
4278   case AMDGPU::ADJCALLSTACKDOWN: {
4279     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4280     MachineInstrBuilder MIB(*MF, &MI);
4281     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4282        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4283     return BB;
4284   }
4285   case AMDGPU::SI_CALL_ISEL: {
4286     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4287     const DebugLoc &DL = MI.getDebugLoc();
4288 
4289     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4290 
4291     MachineInstrBuilder MIB;
4292     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4293 
4294     for (const MachineOperand &MO : MI.operands())
4295       MIB.add(MO);
4296 
4297     MIB.cloneMemRefs(MI);
4298     MI.eraseFromParent();
4299     return BB;
4300   }
4301   case AMDGPU::V_ADD_CO_U32_e32:
4302   case AMDGPU::V_SUB_CO_U32_e32:
4303   case AMDGPU::V_SUBREV_CO_U32_e32: {
4304     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4305     const DebugLoc &DL = MI.getDebugLoc();
4306     unsigned Opc = MI.getOpcode();
4307 
4308     bool NeedClampOperand = false;
4309     if (TII->pseudoToMCOpcode(Opc) == -1) {
4310       Opc = AMDGPU::getVOPe64(Opc);
4311       NeedClampOperand = true;
4312     }
4313 
4314     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4315     if (TII->isVOP3(*I)) {
4316       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4317       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4318       I.addReg(TRI->getVCC(), RegState::Define);
4319     }
4320     I.add(MI.getOperand(1))
4321      .add(MI.getOperand(2));
4322     if (NeedClampOperand)
4323       I.addImm(0); // clamp bit for e64 encoding
4324 
4325     TII->legalizeOperands(*I);
4326 
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::V_ADDC_U32_e32:
4331   case AMDGPU::V_SUBB_U32_e32:
4332   case AMDGPU::V_SUBBREV_U32_e32:
4333     // These instructions have an implicit use of vcc which counts towards the
4334     // constant bus limit.
4335     TII->legalizeOperands(MI);
4336     return BB;
4337   case AMDGPU::DS_GWS_INIT:
4338   case AMDGPU::DS_GWS_SEMA_BR:
4339   case AMDGPU::DS_GWS_BARRIER:
4340     if (Subtarget->needsAlignedVGPRs()) {
4341       // Add implicit aligned super-reg to force alignment on the data operand.
4342       const DebugLoc &DL = MI.getDebugLoc();
4343       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4344       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4345       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4346       Register DataReg = Op->getReg();
4347       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4348       Register Undef = MRI.createVirtualRegister(
4349           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4350       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4351       Register NewVR =
4352           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4353                                            : &AMDGPU::VReg_64_Align2RegClass);
4354       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4355           .addReg(DataReg, 0, Op->getSubReg())
4356           .addImm(AMDGPU::sub0)
4357           .addReg(Undef)
4358           .addImm(AMDGPU::sub1);
4359       Op->setReg(NewVR);
4360       Op->setSubReg(AMDGPU::sub0);
4361       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4362     }
4363     LLVM_FALLTHROUGH;
4364   case AMDGPU::DS_GWS_SEMA_V:
4365   case AMDGPU::DS_GWS_SEMA_P:
4366   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4367     // A s_waitcnt 0 is required to be the instruction immediately following.
4368     if (getSubtarget()->hasGWSAutoReplay()) {
4369       bundleInstWithWaitcnt(MI);
4370       return BB;
4371     }
4372 
4373     return emitGWSMemViolTestLoop(MI, BB);
4374   case AMDGPU::S_SETREG_B32: {
4375     // Try to optimize cases that only set the denormal mode or rounding mode.
4376     //
4377     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4378     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4379     // instead.
4380     //
4381     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4382     // allow you to have a no side effect instruction in the output of a
4383     // sideeffecting pattern.
4384     unsigned ID, Offset, Width;
4385     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4386     if (ID != AMDGPU::Hwreg::ID_MODE)
4387       return BB;
4388 
4389     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4390     const unsigned SetMask = WidthMask << Offset;
4391 
4392     if (getSubtarget()->hasDenormModeInst()) {
4393       unsigned SetDenormOp = 0;
4394       unsigned SetRoundOp = 0;
4395 
4396       // The dedicated instructions can only set the whole denorm or round mode
4397       // at once, not a subset of bits in either.
4398       if (SetMask ==
4399           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4400         // If this fully sets both the round and denorm mode, emit the two
4401         // dedicated instructions for these.
4402         SetRoundOp = AMDGPU::S_ROUND_MODE;
4403         SetDenormOp = AMDGPU::S_DENORM_MODE;
4404       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4405         SetRoundOp = AMDGPU::S_ROUND_MODE;
4406       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4407         SetDenormOp = AMDGPU::S_DENORM_MODE;
4408       }
4409 
4410       if (SetRoundOp || SetDenormOp) {
4411         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4412         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4413         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4414           unsigned ImmVal = Def->getOperand(1).getImm();
4415           if (SetRoundOp) {
4416             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4417                 .addImm(ImmVal & 0xf);
4418 
4419             // If we also have the denorm mode, get just the denorm mode bits.
4420             ImmVal >>= 4;
4421           }
4422 
4423           if (SetDenormOp) {
4424             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4425                 .addImm(ImmVal & 0xf);
4426           }
4427 
4428           MI.eraseFromParent();
4429           return BB;
4430         }
4431       }
4432     }
4433 
4434     // If only FP bits are touched, used the no side effects pseudo.
4435     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4436                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4437       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4438 
4439     return BB;
4440   }
4441   default:
4442     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4443   }
4444 }
4445 
4446 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4447   return isTypeLegal(VT.getScalarType());
4448 }
4449 
4450 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4451   // This currently forces unfolding various combinations of fsub into fma with
4452   // free fneg'd operands. As long as we have fast FMA (controlled by
4453   // isFMAFasterThanFMulAndFAdd), we should perform these.
4454 
4455   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4456   // most of these combines appear to be cycle neutral but save on instruction
4457   // count / code size.
4458   return true;
4459 }
4460 
4461 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4462 
4463 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4464                                          EVT VT) const {
4465   if (!VT.isVector()) {
4466     return MVT::i1;
4467   }
4468   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4469 }
4470 
4471 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4472   // TODO: Should i16 be used always if legal? For now it would force VALU
4473   // shifts.
4474   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4475 }
4476 
4477 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4478   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4479              ? Ty.changeElementSize(16)
4480              : Ty.changeElementSize(32);
4481 }
4482 
4483 // Answering this is somewhat tricky and depends on the specific device which
4484 // have different rates for fma or all f64 operations.
4485 //
4486 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4487 // regardless of which device (although the number of cycles differs between
4488 // devices), so it is always profitable for f64.
4489 //
4490 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4491 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4492 // which we can always do even without fused FP ops since it returns the same
4493 // result as the separate operations and since it is always full
4494 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4495 // however does not support denormals, so we do report fma as faster if we have
4496 // a fast fma device and require denormals.
4497 //
4498 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4499                                                   EVT VT) const {
4500   VT = VT.getScalarType();
4501 
4502   switch (VT.getSimpleVT().SimpleTy) {
4503   case MVT::f32: {
4504     // If mad is not available this depends only on if f32 fma is full rate.
4505     if (!Subtarget->hasMadMacF32Insts())
4506       return Subtarget->hasFastFMAF32();
4507 
4508     // Otherwise f32 mad is always full rate and returns the same result as
4509     // the separate operations so should be preferred over fma.
4510     // However does not support denomals.
4511     if (hasFP32Denormals(MF))
4512       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4513 
4514     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4515     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4516   }
4517   case MVT::f64:
4518     return true;
4519   case MVT::f16:
4520     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4521   default:
4522     break;
4523   }
4524 
4525   return false;
4526 }
4527 
4528 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4529                                                   LLT Ty) const {
4530   switch (Ty.getScalarSizeInBits()) {
4531   case 16:
4532     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4533   case 32:
4534     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4535   case 64:
4536     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4537   default:
4538     break;
4539   }
4540 
4541   return false;
4542 }
4543 
4544 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4545   if (!Ty.isScalar())
4546     return false;
4547 
4548   if (Ty.getScalarSizeInBits() == 16)
4549     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4550   if (Ty.getScalarSizeInBits() == 32)
4551     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4552 
4553   return false;
4554 }
4555 
4556 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4557                                    const SDNode *N) const {
4558   // TODO: Check future ftz flag
4559   // v_mad_f32/v_mac_f32 do not support denormals.
4560   EVT VT = N->getValueType(0);
4561   if (VT == MVT::f32)
4562     return Subtarget->hasMadMacF32Insts() &&
4563            !hasFP32Denormals(DAG.getMachineFunction());
4564   if (VT == MVT::f16) {
4565     return Subtarget->hasMadF16() &&
4566            !hasFP64FP16Denormals(DAG.getMachineFunction());
4567   }
4568 
4569   return false;
4570 }
4571 
4572 //===----------------------------------------------------------------------===//
4573 // Custom DAG Lowering Operations
4574 //===----------------------------------------------------------------------===//
4575 
4576 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4577 // wider vector type is legal.
4578 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4579                                              SelectionDAG &DAG) const {
4580   unsigned Opc = Op.getOpcode();
4581   EVT VT = Op.getValueType();
4582   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4583 
4584   SDValue Lo, Hi;
4585   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4586 
4587   SDLoc SL(Op);
4588   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4589                              Op->getFlags());
4590   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4591                              Op->getFlags());
4592 
4593   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4594 }
4595 
4596 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4597 // wider vector type is legal.
4598 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4599                                               SelectionDAG &DAG) const {
4600   unsigned Opc = Op.getOpcode();
4601   EVT VT = Op.getValueType();
4602   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4603          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4604 
4605   SDValue Lo0, Hi0;
4606   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4607   SDValue Lo1, Hi1;
4608   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4609 
4610   SDLoc SL(Op);
4611 
4612   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4613                              Op->getFlags());
4614   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4615                              Op->getFlags());
4616 
4617   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4618 }
4619 
4620 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4621                                               SelectionDAG &DAG) const {
4622   unsigned Opc = Op.getOpcode();
4623   EVT VT = Op.getValueType();
4624   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4625          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4626 
4627   SDValue Lo0, Hi0;
4628   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4629   SDValue Lo1, Hi1;
4630   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4631   SDValue Lo2, Hi2;
4632   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4633 
4634   SDLoc SL(Op);
4635 
4636   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4637                              Op->getFlags());
4638   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4639                              Op->getFlags());
4640 
4641   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4642 }
4643 
4644 
4645 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4646   switch (Op.getOpcode()) {
4647   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4648   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4649   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4650   case ISD::LOAD: {
4651     SDValue Result = LowerLOAD(Op, DAG);
4652     assert((!Result.getNode() ||
4653             Result.getNode()->getNumValues() == 2) &&
4654            "Load should return a value and a chain");
4655     return Result;
4656   }
4657 
4658   case ISD::FSIN:
4659   case ISD::FCOS:
4660     return LowerTrig(Op, DAG);
4661   case ISD::SELECT: return LowerSELECT(Op, DAG);
4662   case ISD::FDIV: return LowerFDIV(Op, DAG);
4663   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4664   case ISD::STORE: return LowerSTORE(Op, DAG);
4665   case ISD::GlobalAddress: {
4666     MachineFunction &MF = DAG.getMachineFunction();
4667     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4668     return LowerGlobalAddress(MFI, Op, DAG);
4669   }
4670   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4671   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4672   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4673   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4674   case ISD::INSERT_SUBVECTOR:
4675     return lowerINSERT_SUBVECTOR(Op, DAG);
4676   case ISD::INSERT_VECTOR_ELT:
4677     return lowerINSERT_VECTOR_ELT(Op, DAG);
4678   case ISD::EXTRACT_VECTOR_ELT:
4679     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4680   case ISD::VECTOR_SHUFFLE:
4681     return lowerVECTOR_SHUFFLE(Op, DAG);
4682   case ISD::BUILD_VECTOR:
4683     return lowerBUILD_VECTOR(Op, DAG);
4684   case ISD::FP_ROUND:
4685     return lowerFP_ROUND(Op, DAG);
4686   case ISD::TRAP:
4687     return lowerTRAP(Op, DAG);
4688   case ISD::DEBUGTRAP:
4689     return lowerDEBUGTRAP(Op, DAG);
4690   case ISD::FABS:
4691   case ISD::FNEG:
4692   case ISD::FCANONICALIZE:
4693   case ISD::BSWAP:
4694     return splitUnaryVectorOp(Op, DAG);
4695   case ISD::FMINNUM:
4696   case ISD::FMAXNUM:
4697     return lowerFMINNUM_FMAXNUM(Op, DAG);
4698   case ISD::FMA:
4699     return splitTernaryVectorOp(Op, DAG);
4700   case ISD::FP_TO_SINT:
4701   case ISD::FP_TO_UINT:
4702     return LowerFP_TO_INT(Op, DAG);
4703   case ISD::SHL:
4704   case ISD::SRA:
4705   case ISD::SRL:
4706   case ISD::ADD:
4707   case ISD::SUB:
4708   case ISD::MUL:
4709   case ISD::SMIN:
4710   case ISD::SMAX:
4711   case ISD::UMIN:
4712   case ISD::UMAX:
4713   case ISD::FADD:
4714   case ISD::FMUL:
4715   case ISD::FMINNUM_IEEE:
4716   case ISD::FMAXNUM_IEEE:
4717   case ISD::UADDSAT:
4718   case ISD::USUBSAT:
4719   case ISD::SADDSAT:
4720   case ISD::SSUBSAT:
4721     return splitBinaryVectorOp(Op, DAG);
4722   case ISD::SMULO:
4723   case ISD::UMULO:
4724     return lowerXMULO(Op, DAG);
4725   case ISD::SMUL_LOHI:
4726   case ISD::UMUL_LOHI:
4727     return lowerXMUL_LOHI(Op, DAG);
4728   case ISD::DYNAMIC_STACKALLOC:
4729     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4730   }
4731   return SDValue();
4732 }
4733 
4734 // Used for D16: Casts the result of an instruction into the right vector,
4735 // packs values if loads return unpacked values.
4736 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4737                                        const SDLoc &DL,
4738                                        SelectionDAG &DAG, bool Unpacked) {
4739   if (!LoadVT.isVector())
4740     return Result;
4741 
4742   // Cast back to the original packed type or to a larger type that is a
4743   // multiple of 32 bit for D16. Widening the return type is a required for
4744   // legalization.
4745   EVT FittingLoadVT = LoadVT;
4746   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4747     FittingLoadVT =
4748         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4749                          LoadVT.getVectorNumElements() + 1);
4750   }
4751 
4752   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4753     // Truncate to v2i16/v4i16.
4754     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4755 
4756     // Workaround legalizer not scalarizing truncate after vector op
4757     // legalization but not creating intermediate vector trunc.
4758     SmallVector<SDValue, 4> Elts;
4759     DAG.ExtractVectorElements(Result, Elts);
4760     for (SDValue &Elt : Elts)
4761       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4762 
4763     // Pad illegal v1i16/v3fi6 to v4i16
4764     if ((LoadVT.getVectorNumElements() % 2) == 1)
4765       Elts.push_back(DAG.getUNDEF(MVT::i16));
4766 
4767     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4768 
4769     // Bitcast to original type (v2f16/v4f16).
4770     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4771   }
4772 
4773   // Cast back to the original packed type.
4774   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4775 }
4776 
4777 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4778                                               MemSDNode *M,
4779                                               SelectionDAG &DAG,
4780                                               ArrayRef<SDValue> Ops,
4781                                               bool IsIntrinsic) const {
4782   SDLoc DL(M);
4783 
4784   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4785   EVT LoadVT = M->getValueType(0);
4786 
4787   EVT EquivLoadVT = LoadVT;
4788   if (LoadVT.isVector()) {
4789     if (Unpacked) {
4790       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4791                                      LoadVT.getVectorNumElements());
4792     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4793       // Widen v3f16 to legal type
4794       EquivLoadVT =
4795           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4796                            LoadVT.getVectorNumElements() + 1);
4797     }
4798   }
4799 
4800   // Change from v4f16/v2f16 to EquivLoadVT.
4801   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4802 
4803   SDValue Load
4804     = DAG.getMemIntrinsicNode(
4805       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4806       VTList, Ops, M->getMemoryVT(),
4807       M->getMemOperand());
4808 
4809   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4810 
4811   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4812 }
4813 
4814 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4815                                              SelectionDAG &DAG,
4816                                              ArrayRef<SDValue> Ops) const {
4817   SDLoc DL(M);
4818   EVT LoadVT = M->getValueType(0);
4819   EVT EltType = LoadVT.getScalarType();
4820   EVT IntVT = LoadVT.changeTypeToInteger();
4821 
4822   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4823 
4824   unsigned Opc =
4825       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4826 
4827   if (IsD16) {
4828     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4829   }
4830 
4831   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4832   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4833     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4834 
4835   if (isTypeLegal(LoadVT)) {
4836     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4837                                M->getMemOperand(), DAG);
4838   }
4839 
4840   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4841   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4842   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4843                                         M->getMemOperand(), DAG);
4844   return DAG.getMergeValues(
4845       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4846       DL);
4847 }
4848 
4849 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4850                                   SDNode *N, SelectionDAG &DAG) {
4851   EVT VT = N->getValueType(0);
4852   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4853   unsigned CondCode = CD->getZExtValue();
4854   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4855     return DAG.getUNDEF(VT);
4856 
4857   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4858 
4859   SDValue LHS = N->getOperand(1);
4860   SDValue RHS = N->getOperand(2);
4861 
4862   SDLoc DL(N);
4863 
4864   EVT CmpVT = LHS.getValueType();
4865   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4866     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4867       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4868     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4869     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4870   }
4871 
4872   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4873 
4874   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4875   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4876 
4877   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4878                               DAG.getCondCode(CCOpcode));
4879   if (VT.bitsEq(CCVT))
4880     return SetCC;
4881   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4882 }
4883 
4884 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4885                                   SDNode *N, SelectionDAG &DAG) {
4886   EVT VT = N->getValueType(0);
4887   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4888 
4889   unsigned CondCode = CD->getZExtValue();
4890   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4891     return DAG.getUNDEF(VT);
4892 
4893   SDValue Src0 = N->getOperand(1);
4894   SDValue Src1 = N->getOperand(2);
4895   EVT CmpVT = Src0.getValueType();
4896   SDLoc SL(N);
4897 
4898   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4899     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4900     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4901   }
4902 
4903   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4904   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4905   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4906   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4907   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4908                               Src1, DAG.getCondCode(CCOpcode));
4909   if (VT.bitsEq(CCVT))
4910     return SetCC;
4911   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4912 }
4913 
4914 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4915                                     SelectionDAG &DAG) {
4916   EVT VT = N->getValueType(0);
4917   SDValue Src = N->getOperand(1);
4918   SDLoc SL(N);
4919 
4920   if (Src.getOpcode() == ISD::SETCC) {
4921     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4922     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4923                        Src.getOperand(1), Src.getOperand(2));
4924   }
4925   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4926     // (ballot 0) -> 0
4927     if (Arg->isZero())
4928       return DAG.getConstant(0, SL, VT);
4929 
4930     // (ballot 1) -> EXEC/EXEC_LO
4931     if (Arg->isOne()) {
4932       Register Exec;
4933       if (VT.getScalarSizeInBits() == 32)
4934         Exec = AMDGPU::EXEC_LO;
4935       else if (VT.getScalarSizeInBits() == 64)
4936         Exec = AMDGPU::EXEC;
4937       else
4938         return SDValue();
4939 
4940       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4941     }
4942   }
4943 
4944   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4945   // ISD::SETNE)
4946   return DAG.getNode(
4947       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4948       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4949 }
4950 
4951 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4952                                           SmallVectorImpl<SDValue> &Results,
4953                                           SelectionDAG &DAG) const {
4954   switch (N->getOpcode()) {
4955   case ISD::INSERT_VECTOR_ELT: {
4956     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4957       Results.push_back(Res);
4958     return;
4959   }
4960   case ISD::EXTRACT_VECTOR_ELT: {
4961     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4962       Results.push_back(Res);
4963     return;
4964   }
4965   case ISD::INTRINSIC_WO_CHAIN: {
4966     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4967     switch (IID) {
4968     case Intrinsic::amdgcn_cvt_pkrtz: {
4969       SDValue Src0 = N->getOperand(1);
4970       SDValue Src1 = N->getOperand(2);
4971       SDLoc SL(N);
4972       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4973                                 Src0, Src1);
4974       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4975       return;
4976     }
4977     case Intrinsic::amdgcn_cvt_pknorm_i16:
4978     case Intrinsic::amdgcn_cvt_pknorm_u16:
4979     case Intrinsic::amdgcn_cvt_pk_i16:
4980     case Intrinsic::amdgcn_cvt_pk_u16: {
4981       SDValue Src0 = N->getOperand(1);
4982       SDValue Src1 = N->getOperand(2);
4983       SDLoc SL(N);
4984       unsigned Opcode;
4985 
4986       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4987         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4988       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4989         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4990       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4991         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4992       else
4993         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4994 
4995       EVT VT = N->getValueType(0);
4996       if (isTypeLegal(VT))
4997         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4998       else {
4999         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5000         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5001       }
5002       return;
5003     }
5004     }
5005     break;
5006   }
5007   case ISD::INTRINSIC_W_CHAIN: {
5008     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5009       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5010         // FIXME: Hacky
5011         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5012           Results.push_back(Res.getOperand(I));
5013         }
5014       } else {
5015         Results.push_back(Res);
5016         Results.push_back(Res.getValue(1));
5017       }
5018       return;
5019     }
5020 
5021     break;
5022   }
5023   case ISD::SELECT: {
5024     SDLoc SL(N);
5025     EVT VT = N->getValueType(0);
5026     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5027     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5028     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5029 
5030     EVT SelectVT = NewVT;
5031     if (NewVT.bitsLT(MVT::i32)) {
5032       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5033       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5034       SelectVT = MVT::i32;
5035     }
5036 
5037     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5038                                     N->getOperand(0), LHS, RHS);
5039 
5040     if (NewVT != SelectVT)
5041       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5042     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5043     return;
5044   }
5045   case ISD::FNEG: {
5046     if (N->getValueType(0) != MVT::v2f16)
5047       break;
5048 
5049     SDLoc SL(N);
5050     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5051 
5052     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5053                              BC,
5054                              DAG.getConstant(0x80008000, SL, MVT::i32));
5055     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5056     return;
5057   }
5058   case ISD::FABS: {
5059     if (N->getValueType(0) != MVT::v2f16)
5060       break;
5061 
5062     SDLoc SL(N);
5063     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5064 
5065     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5066                              BC,
5067                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5068     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5069     return;
5070   }
5071   default:
5072     break;
5073   }
5074 }
5075 
5076 /// Helper function for LowerBRCOND
5077 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5078 
5079   SDNode *Parent = Value.getNode();
5080   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5081        I != E; ++I) {
5082 
5083     if (I.getUse().get() != Value)
5084       continue;
5085 
5086     if (I->getOpcode() == Opcode)
5087       return *I;
5088   }
5089   return nullptr;
5090 }
5091 
5092 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5093   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5094     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5095     case Intrinsic::amdgcn_if:
5096       return AMDGPUISD::IF;
5097     case Intrinsic::amdgcn_else:
5098       return AMDGPUISD::ELSE;
5099     case Intrinsic::amdgcn_loop:
5100       return AMDGPUISD::LOOP;
5101     case Intrinsic::amdgcn_end_cf:
5102       llvm_unreachable("should not occur");
5103     default:
5104       return 0;
5105     }
5106   }
5107 
5108   // break, if_break, else_break are all only used as inputs to loop, not
5109   // directly as branch conditions.
5110   return 0;
5111 }
5112 
5113 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5114   const Triple &TT = getTargetMachine().getTargetTriple();
5115   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5116           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5117          AMDGPU::shouldEmitConstantsToTextSection(TT);
5118 }
5119 
5120 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5121   // FIXME: Either avoid relying on address space here or change the default
5122   // address space for functions to avoid the explicit check.
5123   return (GV->getValueType()->isFunctionTy() ||
5124           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5125          !shouldEmitFixup(GV) &&
5126          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5127 }
5128 
5129 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5130   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5131 }
5132 
5133 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5134   if (!GV->hasExternalLinkage())
5135     return true;
5136 
5137   const auto OS = getTargetMachine().getTargetTriple().getOS();
5138   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5139 }
5140 
5141 /// This transforms the control flow intrinsics to get the branch destination as
5142 /// last parameter, also switches branch target with BR if the need arise
5143 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5144                                       SelectionDAG &DAG) const {
5145   SDLoc DL(BRCOND);
5146 
5147   SDNode *Intr = BRCOND.getOperand(1).getNode();
5148   SDValue Target = BRCOND.getOperand(2);
5149   SDNode *BR = nullptr;
5150   SDNode *SetCC = nullptr;
5151 
5152   if (Intr->getOpcode() == ISD::SETCC) {
5153     // As long as we negate the condition everything is fine
5154     SetCC = Intr;
5155     Intr = SetCC->getOperand(0).getNode();
5156 
5157   } else {
5158     // Get the target from BR if we don't negate the condition
5159     BR = findUser(BRCOND, ISD::BR);
5160     assert(BR && "brcond missing unconditional branch user");
5161     Target = BR->getOperand(1);
5162   }
5163 
5164   unsigned CFNode = isCFIntrinsic(Intr);
5165   if (CFNode == 0) {
5166     // This is a uniform branch so we don't need to legalize.
5167     return BRCOND;
5168   }
5169 
5170   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5171                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5172 
5173   assert(!SetCC ||
5174         (SetCC->getConstantOperandVal(1) == 1 &&
5175          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5176                                                              ISD::SETNE));
5177 
5178   // operands of the new intrinsic call
5179   SmallVector<SDValue, 4> Ops;
5180   if (HaveChain)
5181     Ops.push_back(BRCOND.getOperand(0));
5182 
5183   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5184   Ops.push_back(Target);
5185 
5186   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5187 
5188   // build the new intrinsic call
5189   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5190 
5191   if (!HaveChain) {
5192     SDValue Ops[] =  {
5193       SDValue(Result, 0),
5194       BRCOND.getOperand(0)
5195     };
5196 
5197     Result = DAG.getMergeValues(Ops, DL).getNode();
5198   }
5199 
5200   if (BR) {
5201     // Give the branch instruction our target
5202     SDValue Ops[] = {
5203       BR->getOperand(0),
5204       BRCOND.getOperand(2)
5205     };
5206     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5207     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5208   }
5209 
5210   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5211 
5212   // Copy the intrinsic results to registers
5213   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5214     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5215     if (!CopyToReg)
5216       continue;
5217 
5218     Chain = DAG.getCopyToReg(
5219       Chain, DL,
5220       CopyToReg->getOperand(1),
5221       SDValue(Result, i - 1),
5222       SDValue());
5223 
5224     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5225   }
5226 
5227   // Remove the old intrinsic from the chain
5228   DAG.ReplaceAllUsesOfValueWith(
5229     SDValue(Intr, Intr->getNumValues() - 1),
5230     Intr->getOperand(0));
5231 
5232   return Chain;
5233 }
5234 
5235 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5236                                           SelectionDAG &DAG) const {
5237   MVT VT = Op.getSimpleValueType();
5238   SDLoc DL(Op);
5239   // Checking the depth
5240   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5241     return DAG.getConstant(0, DL, VT);
5242 
5243   MachineFunction &MF = DAG.getMachineFunction();
5244   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5245   // Check for kernel and shader functions
5246   if (Info->isEntryFunction())
5247     return DAG.getConstant(0, DL, VT);
5248 
5249   MachineFrameInfo &MFI = MF.getFrameInfo();
5250   // There is a call to @llvm.returnaddress in this function
5251   MFI.setReturnAddressIsTaken(true);
5252 
5253   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5254   // Get the return address reg and mark it as an implicit live-in
5255   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5256 
5257   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5258 }
5259 
5260 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5261                                             SDValue Op,
5262                                             const SDLoc &DL,
5263                                             EVT VT) const {
5264   return Op.getValueType().bitsLE(VT) ?
5265       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5266     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5267                 DAG.getTargetConstant(0, DL, MVT::i32));
5268 }
5269 
5270 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5271   assert(Op.getValueType() == MVT::f16 &&
5272          "Do not know how to custom lower FP_ROUND for non-f16 type");
5273 
5274   SDValue Src = Op.getOperand(0);
5275   EVT SrcVT = Src.getValueType();
5276   if (SrcVT != MVT::f64)
5277     return Op;
5278 
5279   SDLoc DL(Op);
5280 
5281   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5282   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5283   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5284 }
5285 
5286 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5287                                                SelectionDAG &DAG) const {
5288   EVT VT = Op.getValueType();
5289   const MachineFunction &MF = DAG.getMachineFunction();
5290   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5291   bool IsIEEEMode = Info->getMode().IEEE;
5292 
5293   // FIXME: Assert during selection that this is only selected for
5294   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5295   // mode functions, but this happens to be OK since it's only done in cases
5296   // where there is known no sNaN.
5297   if (IsIEEEMode)
5298     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5299 
5300   if (VT == MVT::v4f16)
5301     return splitBinaryVectorOp(Op, DAG);
5302   return Op;
5303 }
5304 
5305 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5306   EVT VT = Op.getValueType();
5307   SDLoc SL(Op);
5308   SDValue LHS = Op.getOperand(0);
5309   SDValue RHS = Op.getOperand(1);
5310   bool isSigned = Op.getOpcode() == ISD::SMULO;
5311 
5312   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5313     const APInt &C = RHSC->getAPIntValue();
5314     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5315     if (C.isPowerOf2()) {
5316       // smulo(x, signed_min) is same as umulo(x, signed_min).
5317       bool UseArithShift = isSigned && !C.isMinSignedValue();
5318       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5319       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5320       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5321           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5322                       SL, VT, Result, ShiftAmt),
5323           LHS, ISD::SETNE);
5324       return DAG.getMergeValues({ Result, Overflow }, SL);
5325     }
5326   }
5327 
5328   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5329   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5330                             SL, VT, LHS, RHS);
5331 
5332   SDValue Sign = isSigned
5333     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5334                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5335     : DAG.getConstant(0, SL, VT);
5336   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5337 
5338   return DAG.getMergeValues({ Result, Overflow }, SL);
5339 }
5340 
5341 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5342   if (Op->isDivergent()) {
5343     // Select to V_MAD_[IU]64_[IU]32.
5344     return Op;
5345   }
5346   if (Subtarget->hasSMulHi()) {
5347     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5348     return SDValue();
5349   }
5350   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5351   // calculate the high part, so we might as well do the whole thing with
5352   // V_MAD_[IU]64_[IU]32.
5353   return Op;
5354 }
5355 
5356 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5357   if (!Subtarget->isTrapHandlerEnabled() ||
5358       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5359     return lowerTrapEndpgm(Op, DAG);
5360 
5361   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5362     switch (*HsaAbiVer) {
5363     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5364     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5365       return lowerTrapHsaQueuePtr(Op, DAG);
5366     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5367       return Subtarget->supportsGetDoorbellID() ?
5368           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5369     }
5370   }
5371 
5372   llvm_unreachable("Unknown trap handler");
5373 }
5374 
5375 SDValue SITargetLowering::lowerTrapEndpgm(
5376     SDValue Op, SelectionDAG &DAG) const {
5377   SDLoc SL(Op);
5378   SDValue Chain = Op.getOperand(0);
5379   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5380 }
5381 
5382 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5383     SDValue Op, SelectionDAG &DAG) const {
5384   SDLoc SL(Op);
5385   SDValue Chain = Op.getOperand(0);
5386 
5387   MachineFunction &MF = DAG.getMachineFunction();
5388   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5389   Register UserSGPR = Info->getQueuePtrUserSGPR();
5390 
5391   SDValue QueuePtr;
5392   if (UserSGPR == AMDGPU::NoRegister) {
5393     // We probably are in a function incorrectly marked with
5394     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5395     // so just use a null pointer.
5396     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5397   } else {
5398     QueuePtr = CreateLiveInRegister(
5399       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5400   }
5401 
5402   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5403   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5404                                    QueuePtr, SDValue());
5405 
5406   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5407   SDValue Ops[] = {
5408     ToReg,
5409     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5410     SGPR01,
5411     ToReg.getValue(1)
5412   };
5413   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5414 }
5415 
5416 SDValue SITargetLowering::lowerTrapHsa(
5417     SDValue Op, SelectionDAG &DAG) const {
5418   SDLoc SL(Op);
5419   SDValue Chain = Op.getOperand(0);
5420 
5421   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5422   SDValue Ops[] = {
5423     Chain,
5424     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5425   };
5426   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5427 }
5428 
5429 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5430   SDLoc SL(Op);
5431   SDValue Chain = Op.getOperand(0);
5432   MachineFunction &MF = DAG.getMachineFunction();
5433 
5434   if (!Subtarget->isTrapHandlerEnabled() ||
5435       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5436     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5437                                      "debugtrap handler not supported",
5438                                      Op.getDebugLoc(),
5439                                      DS_Warning);
5440     LLVMContext &Ctx = MF.getFunction().getContext();
5441     Ctx.diagnose(NoTrap);
5442     return Chain;
5443   }
5444 
5445   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5446   SDValue Ops[] = {
5447     Chain,
5448     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5449   };
5450   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5451 }
5452 
5453 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5454                                              SelectionDAG &DAG) const {
5455   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5456   if (Subtarget->hasApertureRegs()) {
5457     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5458         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5459         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5460     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5461         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5462         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5463     unsigned Encoding =
5464         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5465         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5466         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5467 
5468     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5469     SDValue ApertureReg = SDValue(
5470         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5471     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5472     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5473   }
5474 
5475   MachineFunction &MF = DAG.getMachineFunction();
5476   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5477   Register UserSGPR = Info->getQueuePtrUserSGPR();
5478   if (UserSGPR == AMDGPU::NoRegister) {
5479     // We probably are in a function incorrectly marked with
5480     // amdgpu-no-queue-ptr. This is undefined.
5481     return DAG.getUNDEF(MVT::i32);
5482   }
5483 
5484   SDValue QueuePtr = CreateLiveInRegister(
5485     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5486 
5487   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5488   // private_segment_aperture_base_hi.
5489   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5490 
5491   SDValue Ptr =
5492       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5493 
5494   // TODO: Use custom target PseudoSourceValue.
5495   // TODO: We should use the value from the IR intrinsic call, but it might not
5496   // be available and how do we get it?
5497   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5498   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5499                      commonAlignment(Align(64), StructOffset),
5500                      MachineMemOperand::MODereferenceable |
5501                          MachineMemOperand::MOInvariant);
5502 }
5503 
5504 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5505                                              SelectionDAG &DAG) const {
5506   SDLoc SL(Op);
5507   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5508 
5509   SDValue Src = ASC->getOperand(0);
5510   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5511 
5512   const AMDGPUTargetMachine &TM =
5513     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5514 
5515   // flat -> local/private
5516   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5517     unsigned DestAS = ASC->getDestAddressSpace();
5518 
5519     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5520         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5521       unsigned NullVal = TM.getNullPointerValue(DestAS);
5522       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5523       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5524       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5525 
5526       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5527                          NonNull, Ptr, SegmentNullPtr);
5528     }
5529   }
5530 
5531   // local/private -> flat
5532   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5533     unsigned SrcAS = ASC->getSrcAddressSpace();
5534 
5535     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5536         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5537       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5538       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5539 
5540       SDValue NonNull
5541         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5542 
5543       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5544       SDValue CvtPtr
5545         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5546 
5547       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5548                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5549                          FlatNullPtr);
5550     }
5551   }
5552 
5553   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5554       Src.getValueType() == MVT::i64)
5555     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5556 
5557   // global <-> flat are no-ops and never emitted.
5558 
5559   const MachineFunction &MF = DAG.getMachineFunction();
5560   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5561     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5562   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5563 
5564   return DAG.getUNDEF(ASC->getValueType(0));
5565 }
5566 
5567 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5568 // the small vector and inserting them into the big vector. That is better than
5569 // the default expansion of doing it via a stack slot. Even though the use of
5570 // the stack slot would be optimized away afterwards, the stack slot itself
5571 // remains.
5572 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5573                                                 SelectionDAG &DAG) const {
5574   SDValue Vec = Op.getOperand(0);
5575   SDValue Ins = Op.getOperand(1);
5576   SDValue Idx = Op.getOperand(2);
5577   EVT VecVT = Vec.getValueType();
5578   EVT InsVT = Ins.getValueType();
5579   EVT EltVT = VecVT.getVectorElementType();
5580   unsigned InsNumElts = InsVT.getVectorNumElements();
5581   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5582   SDLoc SL(Op);
5583 
5584   for (unsigned I = 0; I != InsNumElts; ++I) {
5585     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5586                               DAG.getConstant(I, SL, MVT::i32));
5587     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5588                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5589   }
5590   return Vec;
5591 }
5592 
5593 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5594                                                  SelectionDAG &DAG) const {
5595   SDValue Vec = Op.getOperand(0);
5596   SDValue InsVal = Op.getOperand(1);
5597   SDValue Idx = Op.getOperand(2);
5598   EVT VecVT = Vec.getValueType();
5599   EVT EltVT = VecVT.getVectorElementType();
5600   unsigned VecSize = VecVT.getSizeInBits();
5601   unsigned EltSize = EltVT.getSizeInBits();
5602 
5603 
5604   assert(VecSize <= 64);
5605 
5606   unsigned NumElts = VecVT.getVectorNumElements();
5607   SDLoc SL(Op);
5608   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5609 
5610   if (NumElts == 4 && EltSize == 16 && KIdx) {
5611     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5612 
5613     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5614                                  DAG.getConstant(0, SL, MVT::i32));
5615     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5616                                  DAG.getConstant(1, SL, MVT::i32));
5617 
5618     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5619     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5620 
5621     unsigned Idx = KIdx->getZExtValue();
5622     bool InsertLo = Idx < 2;
5623     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5624       InsertLo ? LoVec : HiVec,
5625       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5626       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5627 
5628     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5629 
5630     SDValue Concat = InsertLo ?
5631       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5632       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5633 
5634     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5635   }
5636 
5637   if (isa<ConstantSDNode>(Idx))
5638     return SDValue();
5639 
5640   MVT IntVT = MVT::getIntegerVT(VecSize);
5641 
5642   // Avoid stack access for dynamic indexing.
5643   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5644 
5645   // Create a congruent vector with the target value in each element so that
5646   // the required element can be masked and ORed into the target vector.
5647   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5648                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5649 
5650   assert(isPowerOf2_32(EltSize));
5651   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5652 
5653   // Convert vector index to bit-index.
5654   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5655 
5656   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5657   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5658                             DAG.getConstant(0xffff, SL, IntVT),
5659                             ScaledIdx);
5660 
5661   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5662   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5663                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5664 
5665   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5666   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5667 }
5668 
5669 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5670                                                   SelectionDAG &DAG) const {
5671   SDLoc SL(Op);
5672 
5673   EVT ResultVT = Op.getValueType();
5674   SDValue Vec = Op.getOperand(0);
5675   SDValue Idx = Op.getOperand(1);
5676   EVT VecVT = Vec.getValueType();
5677   unsigned VecSize = VecVT.getSizeInBits();
5678   EVT EltVT = VecVT.getVectorElementType();
5679   assert(VecSize <= 64);
5680 
5681   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5682 
5683   // Make sure we do any optimizations that will make it easier to fold
5684   // source modifiers before obscuring it with bit operations.
5685 
5686   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5687   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5688     return Combined;
5689 
5690   unsigned EltSize = EltVT.getSizeInBits();
5691   assert(isPowerOf2_32(EltSize));
5692 
5693   MVT IntVT = MVT::getIntegerVT(VecSize);
5694   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5695 
5696   // Convert vector index to bit-index (* EltSize)
5697   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5698 
5699   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5700   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5701 
5702   if (ResultVT == MVT::f16) {
5703     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5704     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5705   }
5706 
5707   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5708 }
5709 
5710 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5711   assert(Elt % 2 == 0);
5712   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5713 }
5714 
5715 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5716                                               SelectionDAG &DAG) const {
5717   SDLoc SL(Op);
5718   EVT ResultVT = Op.getValueType();
5719   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5720 
5721   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5722   EVT EltVT = PackVT.getVectorElementType();
5723   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5724 
5725   // vector_shuffle <0,1,6,7> lhs, rhs
5726   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5727   //
5728   // vector_shuffle <6,7,2,3> lhs, rhs
5729   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5730   //
5731   // vector_shuffle <6,7,0,1> lhs, rhs
5732   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5733 
5734   // Avoid scalarizing when both halves are reading from consecutive elements.
5735   SmallVector<SDValue, 4> Pieces;
5736   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5737     if (elementPairIsContiguous(SVN->getMask(), I)) {
5738       const int Idx = SVN->getMaskElt(I);
5739       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5740       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5741       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5742                                     PackVT, SVN->getOperand(VecIdx),
5743                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5744       Pieces.push_back(SubVec);
5745     } else {
5746       const int Idx0 = SVN->getMaskElt(I);
5747       const int Idx1 = SVN->getMaskElt(I + 1);
5748       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5749       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5750       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5751       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5752 
5753       SDValue Vec0 = SVN->getOperand(VecIdx0);
5754       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5755                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5756 
5757       SDValue Vec1 = SVN->getOperand(VecIdx1);
5758       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5759                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5760       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5761     }
5762   }
5763 
5764   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5765 }
5766 
5767 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5768                                             SelectionDAG &DAG) const {
5769   SDLoc SL(Op);
5770   EVT VT = Op.getValueType();
5771 
5772   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5773     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5774 
5775     // Turn into pair of packed build_vectors.
5776     // TODO: Special case for constants that can be materialized with s_mov_b64.
5777     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5778                                     { Op.getOperand(0), Op.getOperand(1) });
5779     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5780                                     { Op.getOperand(2), Op.getOperand(3) });
5781 
5782     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5783     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5784 
5785     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5786     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5787   }
5788 
5789   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5790   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5791 
5792   SDValue Lo = Op.getOperand(0);
5793   SDValue Hi = Op.getOperand(1);
5794 
5795   // Avoid adding defined bits with the zero_extend.
5796   if (Hi.isUndef()) {
5797     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5798     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5799     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5800   }
5801 
5802   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5803   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5804 
5805   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5806                               DAG.getConstant(16, SL, MVT::i32));
5807   if (Lo.isUndef())
5808     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5809 
5810   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5811   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5812 
5813   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5814   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5815 }
5816 
5817 bool
5818 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5819   // We can fold offsets for anything that doesn't require a GOT relocation.
5820   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5821           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5822           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5823          !shouldEmitGOTReloc(GA->getGlobal());
5824 }
5825 
5826 static SDValue
5827 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5828                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5829                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5830   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5831   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5832   // lowered to the following code sequence:
5833   //
5834   // For constant address space:
5835   //   s_getpc_b64 s[0:1]
5836   //   s_add_u32 s0, s0, $symbol
5837   //   s_addc_u32 s1, s1, 0
5838   //
5839   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5840   //   a fixup or relocation is emitted to replace $symbol with a literal
5841   //   constant, which is a pc-relative offset from the encoding of the $symbol
5842   //   operand to the global variable.
5843   //
5844   // For global address space:
5845   //   s_getpc_b64 s[0:1]
5846   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5847   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5848   //
5849   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5850   //   fixups or relocations are emitted to replace $symbol@*@lo and
5851   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5852   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5853   //   operand to the global variable.
5854   //
5855   // What we want here is an offset from the value returned by s_getpc
5856   // (which is the address of the s_add_u32 instruction) to the global
5857   // variable, but since the encoding of $symbol starts 4 bytes after the start
5858   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5859   // small. This requires us to add 4 to the global variable offset in order to
5860   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5861   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5862   // instruction.
5863   SDValue PtrLo =
5864       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5865   SDValue PtrHi;
5866   if (GAFlags == SIInstrInfo::MO_NONE) {
5867     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5868   } else {
5869     PtrHi =
5870         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5871   }
5872   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5873 }
5874 
5875 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5876                                              SDValue Op,
5877                                              SelectionDAG &DAG) const {
5878   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5879   SDLoc DL(GSD);
5880   EVT PtrVT = Op.getValueType();
5881 
5882   const GlobalValue *GV = GSD->getGlobal();
5883   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5884        shouldUseLDSConstAddress(GV)) ||
5885       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5886       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5887     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5888         GV->hasExternalLinkage()) {
5889       Type *Ty = GV->getValueType();
5890       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5891       // zero-sized type in other languages to declare the dynamic shared
5892       // memory which size is not known at the compile time. They will be
5893       // allocated by the runtime and placed directly after the static
5894       // allocated ones. They all share the same offset.
5895       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5896         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5897         // Adjust alignment for that dynamic shared memory array.
5898         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5899         return SDValue(
5900             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5901       }
5902     }
5903     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5904   }
5905 
5906   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5907     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5908                                             SIInstrInfo::MO_ABS32_LO);
5909     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5910   }
5911 
5912   if (shouldEmitFixup(GV))
5913     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5914   else if (shouldEmitPCReloc(GV))
5915     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5916                                    SIInstrInfo::MO_REL32);
5917 
5918   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5919                                             SIInstrInfo::MO_GOTPCREL32);
5920 
5921   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5922   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5923   const DataLayout &DataLayout = DAG.getDataLayout();
5924   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5925   MachinePointerInfo PtrInfo
5926     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5927 
5928   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5929                      MachineMemOperand::MODereferenceable |
5930                          MachineMemOperand::MOInvariant);
5931 }
5932 
5933 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5934                                    const SDLoc &DL, SDValue V) const {
5935   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5936   // the destination register.
5937   //
5938   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5939   // so we will end up with redundant moves to m0.
5940   //
5941   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5942 
5943   // A Null SDValue creates a glue result.
5944   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5945                                   V, Chain);
5946   return SDValue(M0, 0);
5947 }
5948 
5949 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5950                                                  SDValue Op,
5951                                                  MVT VT,
5952                                                  unsigned Offset) const {
5953   SDLoc SL(Op);
5954   SDValue Param = lowerKernargMemParameter(
5955       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5956   // The local size values will have the hi 16-bits as zero.
5957   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5958                      DAG.getValueType(VT));
5959 }
5960 
5961 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5962                                         EVT VT) {
5963   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5964                                       "non-hsa intrinsic with hsa target",
5965                                       DL.getDebugLoc());
5966   DAG.getContext()->diagnose(BadIntrin);
5967   return DAG.getUNDEF(VT);
5968 }
5969 
5970 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5971                                          EVT VT) {
5972   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5973                                       "intrinsic not supported on subtarget",
5974                                       DL.getDebugLoc());
5975   DAG.getContext()->diagnose(BadIntrin);
5976   return DAG.getUNDEF(VT);
5977 }
5978 
5979 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5980                                     ArrayRef<SDValue> Elts) {
5981   assert(!Elts.empty());
5982   MVT Type;
5983   unsigned NumElts = Elts.size();
5984 
5985   if (NumElts <= 8) {
5986     Type = MVT::getVectorVT(MVT::f32, NumElts);
5987   } else {
5988     assert(Elts.size() <= 16);
5989     Type = MVT::v16f32;
5990     NumElts = 16;
5991   }
5992 
5993   SmallVector<SDValue, 16> VecElts(NumElts);
5994   for (unsigned i = 0; i < Elts.size(); ++i) {
5995     SDValue Elt = Elts[i];
5996     if (Elt.getValueType() != MVT::f32)
5997       Elt = DAG.getBitcast(MVT::f32, Elt);
5998     VecElts[i] = Elt;
5999   }
6000   for (unsigned i = Elts.size(); i < NumElts; ++i)
6001     VecElts[i] = DAG.getUNDEF(MVT::f32);
6002 
6003   if (NumElts == 1)
6004     return VecElts[0];
6005   return DAG.getBuildVector(Type, DL, VecElts);
6006 }
6007 
6008 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6009                               SDValue Src, int ExtraElts) {
6010   EVT SrcVT = Src.getValueType();
6011 
6012   SmallVector<SDValue, 8> Elts;
6013 
6014   if (SrcVT.isVector())
6015     DAG.ExtractVectorElements(Src, Elts);
6016   else
6017     Elts.push_back(Src);
6018 
6019   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6020   while (ExtraElts--)
6021     Elts.push_back(Undef);
6022 
6023   return DAG.getBuildVector(CastVT, DL, Elts);
6024 }
6025 
6026 // Re-construct the required return value for a image load intrinsic.
6027 // This is more complicated due to the optional use TexFailCtrl which means the required
6028 // return type is an aggregate
6029 static SDValue constructRetValue(SelectionDAG &DAG,
6030                                  MachineSDNode *Result,
6031                                  ArrayRef<EVT> ResultTypes,
6032                                  bool IsTexFail, bool Unpacked, bool IsD16,
6033                                  int DMaskPop, int NumVDataDwords,
6034                                  const SDLoc &DL) {
6035   // Determine the required return type. This is the same regardless of IsTexFail flag
6036   EVT ReqRetVT = ResultTypes[0];
6037   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6038   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6039     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6040 
6041   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6042     DMaskPop : (DMaskPop + 1) / 2;
6043 
6044   MVT DataDwordVT = NumDataDwords == 1 ?
6045     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6046 
6047   MVT MaskPopVT = MaskPopDwords == 1 ?
6048     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6049 
6050   SDValue Data(Result, 0);
6051   SDValue TexFail;
6052 
6053   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6054     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6055     if (MaskPopVT.isVector()) {
6056       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6057                          SDValue(Result, 0), ZeroIdx);
6058     } else {
6059       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6060                          SDValue(Result, 0), ZeroIdx);
6061     }
6062   }
6063 
6064   if (DataDwordVT.isVector())
6065     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6066                           NumDataDwords - MaskPopDwords);
6067 
6068   if (IsD16)
6069     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6070 
6071   EVT LegalReqRetVT = ReqRetVT;
6072   if (!ReqRetVT.isVector()) {
6073     if (!Data.getValueType().isInteger())
6074       Data = DAG.getNode(ISD::BITCAST, DL,
6075                          Data.getValueType().changeTypeToInteger(), Data);
6076     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6077   } else {
6078     // We need to widen the return vector to a legal type
6079     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6080         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6081       LegalReqRetVT =
6082           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6083                            ReqRetVT.getVectorNumElements() + 1);
6084     }
6085   }
6086   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6087 
6088   if (IsTexFail) {
6089     TexFail =
6090         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6091                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6092 
6093     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6094   }
6095 
6096   if (Result->getNumValues() == 1)
6097     return Data;
6098 
6099   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6100 }
6101 
6102 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6103                          SDValue *LWE, bool &IsTexFail) {
6104   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6105 
6106   uint64_t Value = TexFailCtrlConst->getZExtValue();
6107   if (Value) {
6108     IsTexFail = true;
6109   }
6110 
6111   SDLoc DL(TexFailCtrlConst);
6112   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6113   Value &= ~(uint64_t)0x1;
6114   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6115   Value &= ~(uint64_t)0x2;
6116 
6117   return Value == 0;
6118 }
6119 
6120 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6121                                       MVT PackVectorVT,
6122                                       SmallVectorImpl<SDValue> &PackedAddrs,
6123                                       unsigned DimIdx, unsigned EndIdx,
6124                                       unsigned NumGradients) {
6125   SDLoc DL(Op);
6126   for (unsigned I = DimIdx; I < EndIdx; I++) {
6127     SDValue Addr = Op.getOperand(I);
6128 
6129     // Gradients are packed with undef for each coordinate.
6130     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6131     // 1D: undef,dx/dh; undef,dx/dv
6132     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6133     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6134     if (((I + 1) >= EndIdx) ||
6135         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6136                                          I == DimIdx + NumGradients - 1))) {
6137       if (Addr.getValueType() != MVT::i16)
6138         Addr = DAG.getBitcast(MVT::i16, Addr);
6139       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6140     } else {
6141       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6142       I++;
6143     }
6144     Addr = DAG.getBitcast(MVT::f32, Addr);
6145     PackedAddrs.push_back(Addr);
6146   }
6147 }
6148 
6149 SDValue SITargetLowering::lowerImage(SDValue Op,
6150                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6151                                      SelectionDAG &DAG, bool WithChain) const {
6152   SDLoc DL(Op);
6153   MachineFunction &MF = DAG.getMachineFunction();
6154   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6155   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6156       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6157   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6158   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6159       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6160   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6161       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6162   unsigned IntrOpcode = Intr->BaseOpcode;
6163   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6164 
6165   SmallVector<EVT, 3> ResultTypes(Op->values());
6166   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6167   bool IsD16 = false;
6168   bool IsG16 = false;
6169   bool IsA16 = false;
6170   SDValue VData;
6171   int NumVDataDwords;
6172   bool AdjustRetType = false;
6173 
6174   // Offset of intrinsic arguments
6175   const unsigned ArgOffset = WithChain ? 2 : 1;
6176 
6177   unsigned DMask;
6178   unsigned DMaskLanes = 0;
6179 
6180   if (BaseOpcode->Atomic) {
6181     VData = Op.getOperand(2);
6182 
6183     bool Is64Bit = VData.getValueType() == MVT::i64;
6184     if (BaseOpcode->AtomicX2) {
6185       SDValue VData2 = Op.getOperand(3);
6186       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6187                                  {VData, VData2});
6188       if (Is64Bit)
6189         VData = DAG.getBitcast(MVT::v4i32, VData);
6190 
6191       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6192       DMask = Is64Bit ? 0xf : 0x3;
6193       NumVDataDwords = Is64Bit ? 4 : 2;
6194     } else {
6195       DMask = Is64Bit ? 0x3 : 0x1;
6196       NumVDataDwords = Is64Bit ? 2 : 1;
6197     }
6198   } else {
6199     auto *DMaskConst =
6200         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6201     DMask = DMaskConst->getZExtValue();
6202     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6203 
6204     if (BaseOpcode->Store) {
6205       VData = Op.getOperand(2);
6206 
6207       MVT StoreVT = VData.getSimpleValueType();
6208       if (StoreVT.getScalarType() == MVT::f16) {
6209         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6210           return Op; // D16 is unsupported for this instruction
6211 
6212         IsD16 = true;
6213         VData = handleD16VData(VData, DAG, true);
6214       }
6215 
6216       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6217     } else {
6218       // Work out the num dwords based on the dmask popcount and underlying type
6219       // and whether packing is supported.
6220       MVT LoadVT = ResultTypes[0].getSimpleVT();
6221       if (LoadVT.getScalarType() == MVT::f16) {
6222         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6223           return Op; // D16 is unsupported for this instruction
6224 
6225         IsD16 = true;
6226       }
6227 
6228       // Confirm that the return type is large enough for the dmask specified
6229       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6230           (!LoadVT.isVector() && DMaskLanes > 1))
6231           return Op;
6232 
6233       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6234       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6235       // instructions.
6236       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6237           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6238         NumVDataDwords = (DMaskLanes + 1) / 2;
6239       else
6240         NumVDataDwords = DMaskLanes;
6241 
6242       AdjustRetType = true;
6243     }
6244   }
6245 
6246   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6247   SmallVector<SDValue, 4> VAddrs;
6248 
6249   // Optimize _L to _LZ when _L is zero
6250   if (LZMappingInfo) {
6251     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6252             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6253       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6254         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6255         VAddrEnd--;                      // remove 'lod'
6256       }
6257     }
6258   }
6259 
6260   // Optimize _mip away, when 'lod' is zero
6261   if (MIPMappingInfo) {
6262     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6263             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6264       if (ConstantLod->isZero()) {
6265         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6266         VAddrEnd--;                           // remove 'mip'
6267       }
6268     }
6269   }
6270 
6271   // Check for 16 bit addresses or derivatives and pack if true.
6272   MVT VAddrVT =
6273       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6274   MVT VAddrScalarVT = VAddrVT.getScalarType();
6275   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6276   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6277 
6278   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6279   VAddrScalarVT = VAddrVT.getScalarType();
6280   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6281   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6282 
6283   // Push back extra arguments.
6284   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6285     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6286       // Special handling of bias when A16 is on. Bias is of type half but
6287       // occupies full 32-bit.
6288       SDValue bias = DAG.getBuildVector( MVT::v2f16, DL, {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6289       VAddrs.push_back(bias);
6290     } else
6291       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6292   }
6293 
6294   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6295     // 16 bit gradients are supported, but are tied to the A16 control
6296     // so both gradients and addresses must be 16 bit
6297     LLVM_DEBUG(
6298         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6299                   "require 16 bit args for both gradients and addresses");
6300     return Op;
6301   }
6302 
6303   if (IsA16) {
6304     if (!ST->hasA16()) {
6305       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6306                            "support 16 bit addresses\n");
6307       return Op;
6308     }
6309   }
6310 
6311   // We've dealt with incorrect input so we know that if IsA16, IsG16
6312   // are set then we have to compress/pack operands (either address,
6313   // gradient or both)
6314   // In the case where a16 and gradients are tied (no G16 support) then we
6315   // have already verified that both IsA16 and IsG16 are true
6316   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6317     // Activate g16
6318     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6319         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6320     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6321   }
6322 
6323   // Add gradients (packed or unpacked)
6324   if (IsG16) {
6325     // Pack the gradients
6326     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6327     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6328                               ArgOffset + Intr->GradientStart,
6329                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6330   } else {
6331     for (unsigned I = ArgOffset + Intr->GradientStart;
6332          I < ArgOffset + Intr->CoordStart; I++)
6333       VAddrs.push_back(Op.getOperand(I));
6334   }
6335 
6336   // Add addresses (packed or unpacked)
6337   if (IsA16) {
6338     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6339                               ArgOffset + Intr->CoordStart, VAddrEnd,
6340                               0 /* No gradients */);
6341   } else {
6342     // Add uncompressed address
6343     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6344       VAddrs.push_back(Op.getOperand(I));
6345   }
6346 
6347   // If the register allocator cannot place the address registers contiguously
6348   // without introducing moves, then using the non-sequential address encoding
6349   // is always preferable, since it saves VALU instructions and is usually a
6350   // wash in terms of code size or even better.
6351   //
6352   // However, we currently have no way of hinting to the register allocator that
6353   // MIMG addresses should be placed contiguously when it is possible to do so,
6354   // so force non-NSA for the common 2-address case as a heuristic.
6355   //
6356   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6357   // allocation when possible.
6358   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6359                 VAddrs.size() >= 3 &&
6360                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6361   SDValue VAddr;
6362   if (!UseNSA)
6363     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6364 
6365   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6366   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6367   SDValue Unorm;
6368   if (!BaseOpcode->Sampler) {
6369     Unorm = True;
6370   } else {
6371     auto UnormConst =
6372         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6373 
6374     Unorm = UnormConst->getZExtValue() ? True : False;
6375   }
6376 
6377   SDValue TFE;
6378   SDValue LWE;
6379   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6380   bool IsTexFail = false;
6381   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6382     return Op;
6383 
6384   if (IsTexFail) {
6385     if (!DMaskLanes) {
6386       // Expecting to get an error flag since TFC is on - and dmask is 0
6387       // Force dmask to be at least 1 otherwise the instruction will fail
6388       DMask = 0x1;
6389       DMaskLanes = 1;
6390       NumVDataDwords = 1;
6391     }
6392     NumVDataDwords += 1;
6393     AdjustRetType = true;
6394   }
6395 
6396   // Has something earlier tagged that the return type needs adjusting
6397   // This happens if the instruction is a load or has set TexFailCtrl flags
6398   if (AdjustRetType) {
6399     // NumVDataDwords reflects the true number of dwords required in the return type
6400     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6401       // This is a no-op load. This can be eliminated
6402       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6403       if (isa<MemSDNode>(Op))
6404         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6405       return Undef;
6406     }
6407 
6408     EVT NewVT = NumVDataDwords > 1 ?
6409                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6410                 : MVT::i32;
6411 
6412     ResultTypes[0] = NewVT;
6413     if (ResultTypes.size() == 3) {
6414       // Original result was aggregate type used for TexFailCtrl results
6415       // The actual instruction returns as a vector type which has now been
6416       // created. Remove the aggregate result.
6417       ResultTypes.erase(&ResultTypes[1]);
6418     }
6419   }
6420 
6421   unsigned CPol = cast<ConstantSDNode>(
6422       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6423   if (BaseOpcode->Atomic)
6424     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6425   if (CPol & ~AMDGPU::CPol::ALL)
6426     return Op;
6427 
6428   SmallVector<SDValue, 26> Ops;
6429   if (BaseOpcode->Store || BaseOpcode->Atomic)
6430     Ops.push_back(VData); // vdata
6431   if (UseNSA)
6432     append_range(Ops, VAddrs);
6433   else
6434     Ops.push_back(VAddr);
6435   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6436   if (BaseOpcode->Sampler)
6437     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6438   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6439   if (IsGFX10Plus)
6440     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6441   Ops.push_back(Unorm);
6442   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6443   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6444                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6445   if (IsGFX10Plus)
6446     Ops.push_back(IsA16 ? True : False);
6447   if (!Subtarget->hasGFX90AInsts()) {
6448     Ops.push_back(TFE); //tfe
6449   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6450     report_fatal_error("TFE is not supported on this GPU");
6451   }
6452   Ops.push_back(LWE); // lwe
6453   if (!IsGFX10Plus)
6454     Ops.push_back(DimInfo->DA ? True : False);
6455   if (BaseOpcode->HasD16)
6456     Ops.push_back(IsD16 ? True : False);
6457   if (isa<MemSDNode>(Op))
6458     Ops.push_back(Op.getOperand(0)); // chain
6459 
6460   int NumVAddrDwords =
6461       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6462   int Opcode = -1;
6463 
6464   if (IsGFX10Plus) {
6465     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6466                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6467                                           : AMDGPU::MIMGEncGfx10Default,
6468                                    NumVDataDwords, NumVAddrDwords);
6469   } else {
6470     if (Subtarget->hasGFX90AInsts()) {
6471       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6472                                      NumVDataDwords, NumVAddrDwords);
6473       if (Opcode == -1)
6474         report_fatal_error(
6475             "requested image instruction is not supported on this GPU");
6476     }
6477     if (Opcode == -1 &&
6478         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6479       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6480                                      NumVDataDwords, NumVAddrDwords);
6481     if (Opcode == -1)
6482       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6483                                      NumVDataDwords, NumVAddrDwords);
6484   }
6485   assert(Opcode != -1);
6486 
6487   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6488   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6489     MachineMemOperand *MemRef = MemOp->getMemOperand();
6490     DAG.setNodeMemRefs(NewNode, {MemRef});
6491   }
6492 
6493   if (BaseOpcode->AtomicX2) {
6494     SmallVector<SDValue, 1> Elt;
6495     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6496     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6497   }
6498   if (BaseOpcode->Store)
6499     return SDValue(NewNode, 0);
6500   return constructRetValue(DAG, NewNode,
6501                            OrigResultTypes, IsTexFail,
6502                            Subtarget->hasUnpackedD16VMem(), IsD16,
6503                            DMaskLanes, NumVDataDwords, DL);
6504 }
6505 
6506 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6507                                        SDValue Offset, SDValue CachePolicy,
6508                                        SelectionDAG &DAG) const {
6509   MachineFunction &MF = DAG.getMachineFunction();
6510 
6511   const DataLayout &DataLayout = DAG.getDataLayout();
6512   Align Alignment =
6513       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6514 
6515   MachineMemOperand *MMO = MF.getMachineMemOperand(
6516       MachinePointerInfo(),
6517       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6518           MachineMemOperand::MOInvariant,
6519       VT.getStoreSize(), Alignment);
6520 
6521   if (!Offset->isDivergent()) {
6522     SDValue Ops[] = {
6523         Rsrc,
6524         Offset, // Offset
6525         CachePolicy
6526     };
6527 
6528     // Widen vec3 load to vec4.
6529     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6530       EVT WidenedVT =
6531           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6532       auto WidenedOp = DAG.getMemIntrinsicNode(
6533           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6534           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6535       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6536                                    DAG.getVectorIdxConstant(0, DL));
6537       return Subvector;
6538     }
6539 
6540     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6541                                    DAG.getVTList(VT), Ops, VT, MMO);
6542   }
6543 
6544   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6545   // assume that the buffer is unswizzled.
6546   SmallVector<SDValue, 4> Loads;
6547   unsigned NumLoads = 1;
6548   MVT LoadVT = VT.getSimpleVT();
6549   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6550   assert((LoadVT.getScalarType() == MVT::i32 ||
6551           LoadVT.getScalarType() == MVT::f32));
6552 
6553   if (NumElts == 8 || NumElts == 16) {
6554     NumLoads = NumElts / 4;
6555     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6556   }
6557 
6558   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6559   SDValue Ops[] = {
6560       DAG.getEntryNode(),                               // Chain
6561       Rsrc,                                             // rsrc
6562       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6563       {},                                               // voffset
6564       {},                                               // soffset
6565       {},                                               // offset
6566       CachePolicy,                                      // cachepolicy
6567       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6568   };
6569 
6570   // Use the alignment to ensure that the required offsets will fit into the
6571   // immediate offsets.
6572   setBufferOffsets(Offset, DAG, &Ops[3],
6573                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6574 
6575   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6576   for (unsigned i = 0; i < NumLoads; ++i) {
6577     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6578     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6579                                         LoadVT, MMO, DAG));
6580   }
6581 
6582   if (NumElts == 8 || NumElts == 16)
6583     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6584 
6585   return Loads[0];
6586 }
6587 
6588 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6589                                                   SelectionDAG &DAG) const {
6590   MachineFunction &MF = DAG.getMachineFunction();
6591   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6592 
6593   EVT VT = Op.getValueType();
6594   SDLoc DL(Op);
6595   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6596 
6597   // TODO: Should this propagate fast-math-flags?
6598 
6599   switch (IntrinsicID) {
6600   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6601     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6602       return emitNonHSAIntrinsicError(DAG, DL, VT);
6603     return getPreloadedValue(DAG, *MFI, VT,
6604                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6605   }
6606   case Intrinsic::amdgcn_dispatch_ptr:
6607   case Intrinsic::amdgcn_queue_ptr: {
6608     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6609       DiagnosticInfoUnsupported BadIntrin(
6610           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6611           DL.getDebugLoc());
6612       DAG.getContext()->diagnose(BadIntrin);
6613       return DAG.getUNDEF(VT);
6614     }
6615 
6616     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6617       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6618     return getPreloadedValue(DAG, *MFI, VT, RegID);
6619   }
6620   case Intrinsic::amdgcn_implicitarg_ptr: {
6621     if (MFI->isEntryFunction())
6622       return getImplicitArgPtr(DAG, DL);
6623     return getPreloadedValue(DAG, *MFI, VT,
6624                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6625   }
6626   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6627     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6628       // This only makes sense to call in a kernel, so just lower to null.
6629       return DAG.getConstant(0, DL, VT);
6630     }
6631 
6632     return getPreloadedValue(DAG, *MFI, VT,
6633                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6634   }
6635   case Intrinsic::amdgcn_dispatch_id: {
6636     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6637   }
6638   case Intrinsic::amdgcn_rcp:
6639     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6640   case Intrinsic::amdgcn_rsq:
6641     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6642   case Intrinsic::amdgcn_rsq_legacy:
6643     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6644       return emitRemovedIntrinsicError(DAG, DL, VT);
6645     return SDValue();
6646   case Intrinsic::amdgcn_rcp_legacy:
6647     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6648       return emitRemovedIntrinsicError(DAG, DL, VT);
6649     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6650   case Intrinsic::amdgcn_rsq_clamp: {
6651     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6652       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6653 
6654     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6655     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6656     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6657 
6658     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6659     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6660                               DAG.getConstantFP(Max, DL, VT));
6661     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6662                        DAG.getConstantFP(Min, DL, VT));
6663   }
6664   case Intrinsic::r600_read_ngroups_x:
6665     if (Subtarget->isAmdHsaOS())
6666       return emitNonHSAIntrinsicError(DAG, DL, VT);
6667 
6668     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6669                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6670                                     false);
6671   case Intrinsic::r600_read_ngroups_y:
6672     if (Subtarget->isAmdHsaOS())
6673       return emitNonHSAIntrinsicError(DAG, DL, VT);
6674 
6675     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6676                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6677                                     false);
6678   case Intrinsic::r600_read_ngroups_z:
6679     if (Subtarget->isAmdHsaOS())
6680       return emitNonHSAIntrinsicError(DAG, DL, VT);
6681 
6682     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6683                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6684                                     false);
6685   case Intrinsic::r600_read_global_size_x:
6686     if (Subtarget->isAmdHsaOS())
6687       return emitNonHSAIntrinsicError(DAG, DL, VT);
6688 
6689     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6690                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6691                                     Align(4), false);
6692   case Intrinsic::r600_read_global_size_y:
6693     if (Subtarget->isAmdHsaOS())
6694       return emitNonHSAIntrinsicError(DAG, DL, VT);
6695 
6696     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6697                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6698                                     Align(4), false);
6699   case Intrinsic::r600_read_global_size_z:
6700     if (Subtarget->isAmdHsaOS())
6701       return emitNonHSAIntrinsicError(DAG, DL, VT);
6702 
6703     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6704                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6705                                     Align(4), false);
6706   case Intrinsic::r600_read_local_size_x:
6707     if (Subtarget->isAmdHsaOS())
6708       return emitNonHSAIntrinsicError(DAG, DL, VT);
6709 
6710     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6711                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6712   case Intrinsic::r600_read_local_size_y:
6713     if (Subtarget->isAmdHsaOS())
6714       return emitNonHSAIntrinsicError(DAG, DL, VT);
6715 
6716     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6717                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6718   case Intrinsic::r600_read_local_size_z:
6719     if (Subtarget->isAmdHsaOS())
6720       return emitNonHSAIntrinsicError(DAG, DL, VT);
6721 
6722     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6723                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6724   case Intrinsic::amdgcn_workgroup_id_x:
6725     return getPreloadedValue(DAG, *MFI, VT,
6726                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6727   case Intrinsic::amdgcn_workgroup_id_y:
6728     return getPreloadedValue(DAG, *MFI, VT,
6729                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6730   case Intrinsic::amdgcn_workgroup_id_z:
6731     return getPreloadedValue(DAG, *MFI, VT,
6732                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6733   case Intrinsic::amdgcn_workitem_id_x:
6734     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6735                           SDLoc(DAG.getEntryNode()),
6736                           MFI->getArgInfo().WorkItemIDX);
6737   case Intrinsic::amdgcn_workitem_id_y:
6738     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6739                           SDLoc(DAG.getEntryNode()),
6740                           MFI->getArgInfo().WorkItemIDY);
6741   case Intrinsic::amdgcn_workitem_id_z:
6742     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6743                           SDLoc(DAG.getEntryNode()),
6744                           MFI->getArgInfo().WorkItemIDZ);
6745   case Intrinsic::amdgcn_wavefrontsize:
6746     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6747                            SDLoc(Op), MVT::i32);
6748   case Intrinsic::amdgcn_s_buffer_load: {
6749     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6750     if (CPol & ~AMDGPU::CPol::ALL)
6751       return Op;
6752     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6753                         DAG);
6754   }
6755   case Intrinsic::amdgcn_fdiv_fast:
6756     return lowerFDIV_FAST(Op, DAG);
6757   case Intrinsic::amdgcn_sin:
6758     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6759 
6760   case Intrinsic::amdgcn_cos:
6761     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6762 
6763   case Intrinsic::amdgcn_mul_u24:
6764     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6765   case Intrinsic::amdgcn_mul_i24:
6766     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6767 
6768   case Intrinsic::amdgcn_log_clamp: {
6769     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6770       return SDValue();
6771 
6772     return emitRemovedIntrinsicError(DAG, DL, VT);
6773   }
6774   case Intrinsic::amdgcn_ldexp:
6775     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6776                        Op.getOperand(1), Op.getOperand(2));
6777 
6778   case Intrinsic::amdgcn_fract:
6779     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6780 
6781   case Intrinsic::amdgcn_class:
6782     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6783                        Op.getOperand(1), Op.getOperand(2));
6784   case Intrinsic::amdgcn_div_fmas:
6785     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6786                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6787                        Op.getOperand(4));
6788 
6789   case Intrinsic::amdgcn_div_fixup:
6790     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6791                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6792 
6793   case Intrinsic::amdgcn_div_scale: {
6794     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6795 
6796     // Translate to the operands expected by the machine instruction. The
6797     // first parameter must be the same as the first instruction.
6798     SDValue Numerator = Op.getOperand(1);
6799     SDValue Denominator = Op.getOperand(2);
6800 
6801     // Note this order is opposite of the machine instruction's operations,
6802     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6803     // intrinsic has the numerator as the first operand to match a normal
6804     // division operation.
6805 
6806     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6807 
6808     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6809                        Denominator, Numerator);
6810   }
6811   case Intrinsic::amdgcn_icmp: {
6812     // There is a Pat that handles this variant, so return it as-is.
6813     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6814         Op.getConstantOperandVal(2) == 0 &&
6815         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6816       return Op;
6817     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6818   }
6819   case Intrinsic::amdgcn_fcmp: {
6820     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6821   }
6822   case Intrinsic::amdgcn_ballot:
6823     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6824   case Intrinsic::amdgcn_fmed3:
6825     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6826                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6827   case Intrinsic::amdgcn_fdot2:
6828     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6829                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6830                        Op.getOperand(4));
6831   case Intrinsic::amdgcn_fmul_legacy:
6832     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6833                        Op.getOperand(1), Op.getOperand(2));
6834   case Intrinsic::amdgcn_sffbh:
6835     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6836   case Intrinsic::amdgcn_sbfe:
6837     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6838                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6839   case Intrinsic::amdgcn_ubfe:
6840     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6841                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6842   case Intrinsic::amdgcn_cvt_pkrtz:
6843   case Intrinsic::amdgcn_cvt_pknorm_i16:
6844   case Intrinsic::amdgcn_cvt_pknorm_u16:
6845   case Intrinsic::amdgcn_cvt_pk_i16:
6846   case Intrinsic::amdgcn_cvt_pk_u16: {
6847     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6848     EVT VT = Op.getValueType();
6849     unsigned Opcode;
6850 
6851     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6852       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6853     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6854       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6855     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6856       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6857     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6858       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6859     else
6860       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6861 
6862     if (isTypeLegal(VT))
6863       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6864 
6865     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6866                                Op.getOperand(1), Op.getOperand(2));
6867     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6868   }
6869   case Intrinsic::amdgcn_fmad_ftz:
6870     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6871                        Op.getOperand(2), Op.getOperand(3));
6872 
6873   case Intrinsic::amdgcn_if_break:
6874     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6875                                       Op->getOperand(1), Op->getOperand(2)), 0);
6876 
6877   case Intrinsic::amdgcn_groupstaticsize: {
6878     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6879     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6880       return Op;
6881 
6882     const Module *M = MF.getFunction().getParent();
6883     const GlobalValue *GV =
6884         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6885     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6886                                             SIInstrInfo::MO_ABS32_LO);
6887     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6888   }
6889   case Intrinsic::amdgcn_is_shared:
6890   case Intrinsic::amdgcn_is_private: {
6891     SDLoc SL(Op);
6892     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6893       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6894     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6895     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6896                                  Op.getOperand(1));
6897 
6898     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6899                                 DAG.getConstant(1, SL, MVT::i32));
6900     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6901   }
6902   case Intrinsic::amdgcn_alignbit:
6903     return DAG.getNode(ISD::FSHR, DL, VT,
6904                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6905   case Intrinsic::amdgcn_perm:
6906     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6907                        Op.getOperand(2), Op.getOperand(3));
6908   case Intrinsic::amdgcn_reloc_constant: {
6909     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6910     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6911     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6912     auto RelocSymbol = cast<GlobalVariable>(
6913         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6914     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6915                                             SIInstrInfo::MO_ABS32_LO);
6916     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6917   }
6918   default:
6919     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6920             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6921       return lowerImage(Op, ImageDimIntr, DAG, false);
6922 
6923     return Op;
6924   }
6925 }
6926 
6927 /// Update \p MMO based on the offset inputs to an intrinsic.
6928 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6929                             SDValue SOffset, SDValue Offset,
6930                             SDValue VIndex = SDValue()) {
6931   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6932       !isa<ConstantSDNode>(Offset)) {
6933     // The combined offset is not known to be constant, so we cannot represent
6934     // it in the MMO. Give up.
6935     MMO->setValue((Value *)nullptr);
6936     return;
6937   }
6938 
6939   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6940                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6941     // The strided index component of the address is not known to be zero, so we
6942     // cannot represent it in the MMO. Give up.
6943     MMO->setValue((Value *)nullptr);
6944     return;
6945   }
6946 
6947   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6948                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6949                  cast<ConstantSDNode>(Offset)->getSExtValue());
6950 }
6951 
6952 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6953                                                      SelectionDAG &DAG,
6954                                                      unsigned NewOpcode) const {
6955   SDLoc DL(Op);
6956 
6957   SDValue VData = Op.getOperand(2);
6958   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6959   SDValue Ops[] = {
6960     Op.getOperand(0), // Chain
6961     VData,            // vdata
6962     Op.getOperand(3), // rsrc
6963     DAG.getConstant(0, DL, MVT::i32), // vindex
6964     Offsets.first,    // voffset
6965     Op.getOperand(5), // soffset
6966     Offsets.second,   // offset
6967     Op.getOperand(6), // cachepolicy
6968     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6969   };
6970 
6971   auto *M = cast<MemSDNode>(Op);
6972   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6973 
6974   EVT MemVT = VData.getValueType();
6975   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6976                                  M->getMemOperand());
6977 }
6978 
6979 // Return a value to use for the idxen operand by examining the vindex operand.
6980 static unsigned getIdxEn(SDValue VIndex) {
6981   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6982     // No need to set idxen if vindex is known to be zero.
6983     return VIndexC->getZExtValue() != 0;
6984   return 1;
6985 }
6986 
6987 SDValue
6988 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6989                                                 unsigned NewOpcode) const {
6990   SDLoc DL(Op);
6991 
6992   SDValue VData = Op.getOperand(2);
6993   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6994   SDValue Ops[] = {
6995     Op.getOperand(0), // Chain
6996     VData,            // vdata
6997     Op.getOperand(3), // rsrc
6998     Op.getOperand(4), // vindex
6999     Offsets.first,    // voffset
7000     Op.getOperand(6), // soffset
7001     Offsets.second,   // offset
7002     Op.getOperand(7), // cachepolicy
7003     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7004   };
7005 
7006   auto *M = cast<MemSDNode>(Op);
7007   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7008 
7009   EVT MemVT = VData.getValueType();
7010   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7011                                  M->getMemOperand());
7012 }
7013 
7014 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7015                                                  SelectionDAG &DAG) const {
7016   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7017   SDLoc DL(Op);
7018 
7019   switch (IntrID) {
7020   case Intrinsic::amdgcn_ds_ordered_add:
7021   case Intrinsic::amdgcn_ds_ordered_swap: {
7022     MemSDNode *M = cast<MemSDNode>(Op);
7023     SDValue Chain = M->getOperand(0);
7024     SDValue M0 = M->getOperand(2);
7025     SDValue Value = M->getOperand(3);
7026     unsigned IndexOperand = M->getConstantOperandVal(7);
7027     unsigned WaveRelease = M->getConstantOperandVal(8);
7028     unsigned WaveDone = M->getConstantOperandVal(9);
7029 
7030     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7031     IndexOperand &= ~0x3f;
7032     unsigned CountDw = 0;
7033 
7034     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7035       CountDw = (IndexOperand >> 24) & 0xf;
7036       IndexOperand &= ~(0xf << 24);
7037 
7038       if (CountDw < 1 || CountDw > 4) {
7039         report_fatal_error(
7040             "ds_ordered_count: dword count must be between 1 and 4");
7041       }
7042     }
7043 
7044     if (IndexOperand)
7045       report_fatal_error("ds_ordered_count: bad index operand");
7046 
7047     if (WaveDone && !WaveRelease)
7048       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7049 
7050     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7051     unsigned ShaderType =
7052         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7053     unsigned Offset0 = OrderedCountIndex << 2;
7054     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7055                        (Instruction << 4);
7056 
7057     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7058       Offset1 |= (CountDw - 1) << 6;
7059 
7060     unsigned Offset = Offset0 | (Offset1 << 8);
7061 
7062     SDValue Ops[] = {
7063       Chain,
7064       Value,
7065       DAG.getTargetConstant(Offset, DL, MVT::i16),
7066       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7067     };
7068     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7069                                    M->getVTList(), Ops, M->getMemoryVT(),
7070                                    M->getMemOperand());
7071   }
7072   case Intrinsic::amdgcn_ds_fadd: {
7073     MemSDNode *M = cast<MemSDNode>(Op);
7074     unsigned Opc;
7075     switch (IntrID) {
7076     case Intrinsic::amdgcn_ds_fadd:
7077       Opc = ISD::ATOMIC_LOAD_FADD;
7078       break;
7079     }
7080 
7081     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7082                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7083                          M->getMemOperand());
7084   }
7085   case Intrinsic::amdgcn_atomic_inc:
7086   case Intrinsic::amdgcn_atomic_dec:
7087   case Intrinsic::amdgcn_ds_fmin:
7088   case Intrinsic::amdgcn_ds_fmax: {
7089     MemSDNode *M = cast<MemSDNode>(Op);
7090     unsigned Opc;
7091     switch (IntrID) {
7092     case Intrinsic::amdgcn_atomic_inc:
7093       Opc = AMDGPUISD::ATOMIC_INC;
7094       break;
7095     case Intrinsic::amdgcn_atomic_dec:
7096       Opc = AMDGPUISD::ATOMIC_DEC;
7097       break;
7098     case Intrinsic::amdgcn_ds_fmin:
7099       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7100       break;
7101     case Intrinsic::amdgcn_ds_fmax:
7102       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7103       break;
7104     default:
7105       llvm_unreachable("Unknown intrinsic!");
7106     }
7107     SDValue Ops[] = {
7108       M->getOperand(0), // Chain
7109       M->getOperand(2), // Ptr
7110       M->getOperand(3)  // Value
7111     };
7112 
7113     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7114                                    M->getMemoryVT(), M->getMemOperand());
7115   }
7116   case Intrinsic::amdgcn_buffer_load:
7117   case Intrinsic::amdgcn_buffer_load_format: {
7118     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7119     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7120     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7121     SDValue Ops[] = {
7122       Op.getOperand(0), // Chain
7123       Op.getOperand(2), // rsrc
7124       Op.getOperand(3), // vindex
7125       SDValue(),        // voffset -- will be set by setBufferOffsets
7126       SDValue(),        // soffset -- will be set by setBufferOffsets
7127       SDValue(),        // offset -- will be set by setBufferOffsets
7128       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7129       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7130     };
7131     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7132 
7133     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7134         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7135 
7136     EVT VT = Op.getValueType();
7137     EVT IntVT = VT.changeTypeToInteger();
7138     auto *M = cast<MemSDNode>(Op);
7139     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7140     EVT LoadVT = Op.getValueType();
7141 
7142     if (LoadVT.getScalarType() == MVT::f16)
7143       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7144                                  M, DAG, Ops);
7145 
7146     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7147     if (LoadVT.getScalarType() == MVT::i8 ||
7148         LoadVT.getScalarType() == MVT::i16)
7149       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7150 
7151     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7152                                M->getMemOperand(), DAG);
7153   }
7154   case Intrinsic::amdgcn_raw_buffer_load:
7155   case Intrinsic::amdgcn_raw_buffer_load_format: {
7156     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7157 
7158     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7159     SDValue Ops[] = {
7160       Op.getOperand(0), // Chain
7161       Op.getOperand(2), // rsrc
7162       DAG.getConstant(0, DL, MVT::i32), // vindex
7163       Offsets.first,    // voffset
7164       Op.getOperand(4), // soffset
7165       Offsets.second,   // offset
7166       Op.getOperand(5), // cachepolicy, swizzled buffer
7167       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7168     };
7169 
7170     auto *M = cast<MemSDNode>(Op);
7171     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7172     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7173   }
7174   case Intrinsic::amdgcn_struct_buffer_load:
7175   case Intrinsic::amdgcn_struct_buffer_load_format: {
7176     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7177 
7178     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7179     SDValue Ops[] = {
7180       Op.getOperand(0), // Chain
7181       Op.getOperand(2), // rsrc
7182       Op.getOperand(3), // vindex
7183       Offsets.first,    // voffset
7184       Op.getOperand(5), // soffset
7185       Offsets.second,   // offset
7186       Op.getOperand(6), // cachepolicy, swizzled buffer
7187       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7188     };
7189 
7190     auto *M = cast<MemSDNode>(Op);
7191     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7192     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7193   }
7194   case Intrinsic::amdgcn_tbuffer_load: {
7195     MemSDNode *M = cast<MemSDNode>(Op);
7196     EVT LoadVT = Op.getValueType();
7197 
7198     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7199     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7200     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7201     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7202     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7203     SDValue Ops[] = {
7204       Op.getOperand(0),  // Chain
7205       Op.getOperand(2),  // rsrc
7206       Op.getOperand(3),  // vindex
7207       Op.getOperand(4),  // voffset
7208       Op.getOperand(5),  // soffset
7209       Op.getOperand(6),  // offset
7210       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7211       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7212       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7213     };
7214 
7215     if (LoadVT.getScalarType() == MVT::f16)
7216       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7217                                  M, DAG, Ops);
7218     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7219                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7220                                DAG);
7221   }
7222   case Intrinsic::amdgcn_raw_tbuffer_load: {
7223     MemSDNode *M = cast<MemSDNode>(Op);
7224     EVT LoadVT = Op.getValueType();
7225     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7226 
7227     SDValue Ops[] = {
7228       Op.getOperand(0),  // Chain
7229       Op.getOperand(2),  // rsrc
7230       DAG.getConstant(0, DL, MVT::i32), // vindex
7231       Offsets.first,     // voffset
7232       Op.getOperand(4),  // soffset
7233       Offsets.second,    // offset
7234       Op.getOperand(5),  // format
7235       Op.getOperand(6),  // cachepolicy, swizzled buffer
7236       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7237     };
7238 
7239     if (LoadVT.getScalarType() == MVT::f16)
7240       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7241                                  M, DAG, Ops);
7242     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7243                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7244                                DAG);
7245   }
7246   case Intrinsic::amdgcn_struct_tbuffer_load: {
7247     MemSDNode *M = cast<MemSDNode>(Op);
7248     EVT LoadVT = Op.getValueType();
7249     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7250 
7251     SDValue Ops[] = {
7252       Op.getOperand(0),  // Chain
7253       Op.getOperand(2),  // rsrc
7254       Op.getOperand(3),  // vindex
7255       Offsets.first,     // voffset
7256       Op.getOperand(5),  // soffset
7257       Offsets.second,    // offset
7258       Op.getOperand(6),  // format
7259       Op.getOperand(7),  // cachepolicy, swizzled buffer
7260       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7261     };
7262 
7263     if (LoadVT.getScalarType() == MVT::f16)
7264       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7265                                  M, DAG, Ops);
7266     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7267                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7268                                DAG);
7269   }
7270   case Intrinsic::amdgcn_buffer_atomic_swap:
7271   case Intrinsic::amdgcn_buffer_atomic_add:
7272   case Intrinsic::amdgcn_buffer_atomic_sub:
7273   case Intrinsic::amdgcn_buffer_atomic_csub:
7274   case Intrinsic::amdgcn_buffer_atomic_smin:
7275   case Intrinsic::amdgcn_buffer_atomic_umin:
7276   case Intrinsic::amdgcn_buffer_atomic_smax:
7277   case Intrinsic::amdgcn_buffer_atomic_umax:
7278   case Intrinsic::amdgcn_buffer_atomic_and:
7279   case Intrinsic::amdgcn_buffer_atomic_or:
7280   case Intrinsic::amdgcn_buffer_atomic_xor:
7281   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7282     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7283     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7284     SDValue Ops[] = {
7285       Op.getOperand(0), // Chain
7286       Op.getOperand(2), // vdata
7287       Op.getOperand(3), // rsrc
7288       Op.getOperand(4), // vindex
7289       SDValue(),        // voffset -- will be set by setBufferOffsets
7290       SDValue(),        // soffset -- will be set by setBufferOffsets
7291       SDValue(),        // offset -- will be set by setBufferOffsets
7292       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7293       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7294     };
7295     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7296 
7297     EVT VT = Op.getValueType();
7298 
7299     auto *M = cast<MemSDNode>(Op);
7300     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7301     unsigned Opcode = 0;
7302 
7303     switch (IntrID) {
7304     case Intrinsic::amdgcn_buffer_atomic_swap:
7305       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7306       break;
7307     case Intrinsic::amdgcn_buffer_atomic_add:
7308       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7309       break;
7310     case Intrinsic::amdgcn_buffer_atomic_sub:
7311       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7312       break;
7313     case Intrinsic::amdgcn_buffer_atomic_csub:
7314       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7315       break;
7316     case Intrinsic::amdgcn_buffer_atomic_smin:
7317       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7318       break;
7319     case Intrinsic::amdgcn_buffer_atomic_umin:
7320       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7321       break;
7322     case Intrinsic::amdgcn_buffer_atomic_smax:
7323       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7324       break;
7325     case Intrinsic::amdgcn_buffer_atomic_umax:
7326       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7327       break;
7328     case Intrinsic::amdgcn_buffer_atomic_and:
7329       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7330       break;
7331     case Intrinsic::amdgcn_buffer_atomic_or:
7332       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7333       break;
7334     case Intrinsic::amdgcn_buffer_atomic_xor:
7335       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7336       break;
7337     case Intrinsic::amdgcn_buffer_atomic_fadd:
7338       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7339         DiagnosticInfoUnsupported
7340           NoFpRet(DAG.getMachineFunction().getFunction(),
7341                   "return versions of fp atomics not supported",
7342                   DL.getDebugLoc(), DS_Error);
7343         DAG.getContext()->diagnose(NoFpRet);
7344         return SDValue();
7345       }
7346       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7347       break;
7348     default:
7349       llvm_unreachable("unhandled atomic opcode");
7350     }
7351 
7352     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7353                                    M->getMemOperand());
7354   }
7355   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7356     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7357   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7358     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7359   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7360     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7361   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7362     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7363   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7364     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7365   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7366     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7367   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7368     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7369   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7370     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7371   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7372     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7373   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7374     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7375   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7376     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7377   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7378     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7379   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7380     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7381   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7382     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7383   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7384     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7385   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7386     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7387   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7388     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7389   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7390     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7391   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7392     return lowerStructBufferAtomicIntrin(Op, DAG,
7393                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7394   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7395     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7396   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7397     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7398   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7399     return lowerStructBufferAtomicIntrin(Op, DAG,
7400                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7401   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7402     return lowerStructBufferAtomicIntrin(Op, DAG,
7403                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7404   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7405     return lowerStructBufferAtomicIntrin(Op, DAG,
7406                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7407   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7408     return lowerStructBufferAtomicIntrin(Op, DAG,
7409                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7410   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7411     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7412   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7413     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7414   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7415     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7416   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7417     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7418   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7419     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7420 
7421   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7422     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7423     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7424     SDValue Ops[] = {
7425       Op.getOperand(0), // Chain
7426       Op.getOperand(2), // src
7427       Op.getOperand(3), // cmp
7428       Op.getOperand(4), // rsrc
7429       Op.getOperand(5), // vindex
7430       SDValue(),        // voffset -- will be set by setBufferOffsets
7431       SDValue(),        // soffset -- will be set by setBufferOffsets
7432       SDValue(),        // offset -- will be set by setBufferOffsets
7433       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7434       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7435     };
7436     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7437 
7438     EVT VT = Op.getValueType();
7439     auto *M = cast<MemSDNode>(Op);
7440     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7441 
7442     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7443                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7444   }
7445   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7446     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7447     SDValue Ops[] = {
7448       Op.getOperand(0), // Chain
7449       Op.getOperand(2), // src
7450       Op.getOperand(3), // cmp
7451       Op.getOperand(4), // rsrc
7452       DAG.getConstant(0, DL, MVT::i32), // vindex
7453       Offsets.first,    // voffset
7454       Op.getOperand(6), // soffset
7455       Offsets.second,   // offset
7456       Op.getOperand(7), // cachepolicy
7457       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7458     };
7459     EVT VT = Op.getValueType();
7460     auto *M = cast<MemSDNode>(Op);
7461     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7462 
7463     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7464                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7465   }
7466   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7467     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7468     SDValue Ops[] = {
7469       Op.getOperand(0), // Chain
7470       Op.getOperand(2), // src
7471       Op.getOperand(3), // cmp
7472       Op.getOperand(4), // rsrc
7473       Op.getOperand(5), // vindex
7474       Offsets.first,    // voffset
7475       Op.getOperand(7), // soffset
7476       Offsets.second,   // offset
7477       Op.getOperand(8), // cachepolicy
7478       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7479     };
7480     EVT VT = Op.getValueType();
7481     auto *M = cast<MemSDNode>(Op);
7482     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7483 
7484     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7485                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7486   }
7487   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7488     MemSDNode *M = cast<MemSDNode>(Op);
7489     SDValue NodePtr = M->getOperand(2);
7490     SDValue RayExtent = M->getOperand(3);
7491     SDValue RayOrigin = M->getOperand(4);
7492     SDValue RayDir = M->getOperand(5);
7493     SDValue RayInvDir = M->getOperand(6);
7494     SDValue TDescr = M->getOperand(7);
7495 
7496     assert(NodePtr.getValueType() == MVT::i32 ||
7497            NodePtr.getValueType() == MVT::i64);
7498     assert(RayDir.getValueType() == MVT::v3f16 ||
7499            RayDir.getValueType() == MVT::v3f32);
7500 
7501     if (!Subtarget->hasGFX10_AEncoding()) {
7502       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7503       return SDValue();
7504     }
7505 
7506     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7507     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7508     const unsigned NumVDataDwords = 4;
7509     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7510     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7511                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7512     const unsigned BaseOpcodes[2][2] = {
7513         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7514         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7515          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7516     int Opcode;
7517     if (UseNSA) {
7518       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7519                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7520                                      NumVAddrDwords);
7521     } else {
7522       Opcode = AMDGPU::getMIMGOpcode(
7523           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7524           PowerOf2Ceil(NumVAddrDwords));
7525     }
7526     assert(Opcode != -1);
7527 
7528     SmallVector<SDValue, 16> Ops;
7529 
7530     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7531       SmallVector<SDValue, 3> Lanes;
7532       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7533       if (Lanes[0].getValueSizeInBits() == 32) {
7534         for (unsigned I = 0; I < 3; ++I)
7535           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7536       } else {
7537         if (IsAligned) {
7538           Ops.push_back(
7539             DAG.getBitcast(MVT::i32,
7540                            DAG.getBuildVector(MVT::v2f16, DL,
7541                                               { Lanes[0], Lanes[1] })));
7542           Ops.push_back(Lanes[2]);
7543         } else {
7544           SDValue Elt0 = Ops.pop_back_val();
7545           Ops.push_back(
7546             DAG.getBitcast(MVT::i32,
7547                            DAG.getBuildVector(MVT::v2f16, DL,
7548                                               { Elt0, Lanes[0] })));
7549           Ops.push_back(
7550             DAG.getBitcast(MVT::i32,
7551                            DAG.getBuildVector(MVT::v2f16, DL,
7552                                               { Lanes[1], Lanes[2] })));
7553         }
7554       }
7555     };
7556 
7557     if (Is64)
7558       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7559     else
7560       Ops.push_back(NodePtr);
7561 
7562     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7563     packLanes(RayOrigin, true);
7564     packLanes(RayDir, true);
7565     packLanes(RayInvDir, false);
7566 
7567     if (!UseNSA) {
7568       // Build a single vector containing all the operands so far prepared.
7569       if (NumVAddrDwords > 8) {
7570         SDValue Undef = DAG.getUNDEF(MVT::i32);
7571         Ops.append(16 - Ops.size(), Undef);
7572       }
7573       assert(Ops.size() == 8 || Ops.size() == 16);
7574       SDValue MergedOps = DAG.getBuildVector(
7575           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7576       Ops.clear();
7577       Ops.push_back(MergedOps);
7578     }
7579 
7580     Ops.push_back(TDescr);
7581     if (IsA16)
7582       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7583     Ops.push_back(M->getChain());
7584 
7585     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7586     MachineMemOperand *MemRef = M->getMemOperand();
7587     DAG.setNodeMemRefs(NewNode, {MemRef});
7588     return SDValue(NewNode, 0);
7589   }
7590   case Intrinsic::amdgcn_global_atomic_fadd:
7591     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7592       DiagnosticInfoUnsupported
7593         NoFpRet(DAG.getMachineFunction().getFunction(),
7594                 "return versions of fp atomics not supported",
7595                 DL.getDebugLoc(), DS_Error);
7596       DAG.getContext()->diagnose(NoFpRet);
7597       return SDValue();
7598     }
7599     LLVM_FALLTHROUGH;
7600   case Intrinsic::amdgcn_global_atomic_fmin:
7601   case Intrinsic::amdgcn_global_atomic_fmax:
7602   case Intrinsic::amdgcn_flat_atomic_fadd:
7603   case Intrinsic::amdgcn_flat_atomic_fmin:
7604   case Intrinsic::amdgcn_flat_atomic_fmax: {
7605     MemSDNode *M = cast<MemSDNode>(Op);
7606     SDValue Ops[] = {
7607       M->getOperand(0), // Chain
7608       M->getOperand(2), // Ptr
7609       M->getOperand(3)  // Value
7610     };
7611     unsigned Opcode = 0;
7612     switch (IntrID) {
7613     case Intrinsic::amdgcn_global_atomic_fadd:
7614     case Intrinsic::amdgcn_flat_atomic_fadd: {
7615       EVT VT = Op.getOperand(3).getValueType();
7616       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7617                            DAG.getVTList(VT, MVT::Other), Ops,
7618                            M->getMemOperand());
7619     }
7620     case Intrinsic::amdgcn_global_atomic_fmin:
7621     case Intrinsic::amdgcn_flat_atomic_fmin: {
7622       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7623       break;
7624     }
7625     case Intrinsic::amdgcn_global_atomic_fmax:
7626     case Intrinsic::amdgcn_flat_atomic_fmax: {
7627       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7628       break;
7629     }
7630     default:
7631       llvm_unreachable("unhandled atomic opcode");
7632     }
7633     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7634                                    M->getVTList(), Ops, M->getMemoryVT(),
7635                                    M->getMemOperand());
7636   }
7637   default:
7638 
7639     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7640             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7641       return lowerImage(Op, ImageDimIntr, DAG, true);
7642 
7643     return SDValue();
7644   }
7645 }
7646 
7647 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7648 // dwordx4 if on SI.
7649 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7650                                               SDVTList VTList,
7651                                               ArrayRef<SDValue> Ops, EVT MemVT,
7652                                               MachineMemOperand *MMO,
7653                                               SelectionDAG &DAG) const {
7654   EVT VT = VTList.VTs[0];
7655   EVT WidenedVT = VT;
7656   EVT WidenedMemVT = MemVT;
7657   if (!Subtarget->hasDwordx3LoadStores() &&
7658       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7659     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7660                                  WidenedVT.getVectorElementType(), 4);
7661     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7662                                     WidenedMemVT.getVectorElementType(), 4);
7663     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7664   }
7665 
7666   assert(VTList.NumVTs == 2);
7667   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7668 
7669   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7670                                        WidenedMemVT, MMO);
7671   if (WidenedVT != VT) {
7672     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7673                                DAG.getVectorIdxConstant(0, DL));
7674     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7675   }
7676   return NewOp;
7677 }
7678 
7679 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7680                                          bool ImageStore) const {
7681   EVT StoreVT = VData.getValueType();
7682 
7683   // No change for f16 and legal vector D16 types.
7684   if (!StoreVT.isVector())
7685     return VData;
7686 
7687   SDLoc DL(VData);
7688   unsigned NumElements = StoreVT.getVectorNumElements();
7689 
7690   if (Subtarget->hasUnpackedD16VMem()) {
7691     // We need to unpack the packed data to store.
7692     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7693     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7694 
7695     EVT EquivStoreVT =
7696         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7697     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7698     return DAG.UnrollVectorOp(ZExt.getNode());
7699   }
7700 
7701   // The sq block of gfx8.1 does not estimate register use correctly for d16
7702   // image store instructions. The data operand is computed as if it were not a
7703   // d16 image instruction.
7704   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7705     // Bitcast to i16
7706     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7707     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7708 
7709     // Decompose into scalars
7710     SmallVector<SDValue, 4> Elts;
7711     DAG.ExtractVectorElements(IntVData, Elts);
7712 
7713     // Group pairs of i16 into v2i16 and bitcast to i32
7714     SmallVector<SDValue, 4> PackedElts;
7715     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7716       SDValue Pair =
7717           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7718       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7719       PackedElts.push_back(IntPair);
7720     }
7721     if ((NumElements % 2) == 1) {
7722       // Handle v3i16
7723       unsigned I = Elts.size() / 2;
7724       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7725                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7726       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7727       PackedElts.push_back(IntPair);
7728     }
7729 
7730     // Pad using UNDEF
7731     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7732 
7733     // Build final vector
7734     EVT VecVT =
7735         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7736     return DAG.getBuildVector(VecVT, DL, PackedElts);
7737   }
7738 
7739   if (NumElements == 3) {
7740     EVT IntStoreVT =
7741         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7742     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7743 
7744     EVT WidenedStoreVT = EVT::getVectorVT(
7745         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7746     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7747                                          WidenedStoreVT.getStoreSizeInBits());
7748     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7749     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7750   }
7751 
7752   assert(isTypeLegal(StoreVT));
7753   return VData;
7754 }
7755 
7756 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7757                                               SelectionDAG &DAG) const {
7758   SDLoc DL(Op);
7759   SDValue Chain = Op.getOperand(0);
7760   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7761   MachineFunction &MF = DAG.getMachineFunction();
7762 
7763   switch (IntrinsicID) {
7764   case Intrinsic::amdgcn_exp_compr: {
7765     SDValue Src0 = Op.getOperand(4);
7766     SDValue Src1 = Op.getOperand(5);
7767     // Hack around illegal type on SI by directly selecting it.
7768     if (isTypeLegal(Src0.getValueType()))
7769       return SDValue();
7770 
7771     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7772     SDValue Undef = DAG.getUNDEF(MVT::f32);
7773     const SDValue Ops[] = {
7774       Op.getOperand(2), // tgt
7775       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7776       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7777       Undef, // src2
7778       Undef, // src3
7779       Op.getOperand(7), // vm
7780       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7781       Op.getOperand(3), // en
7782       Op.getOperand(0) // Chain
7783     };
7784 
7785     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7786     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7787   }
7788   case Intrinsic::amdgcn_s_barrier: {
7789     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7790       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7791       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7792       if (WGSize <= ST.getWavefrontSize())
7793         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7794                                           Op.getOperand(0)), 0);
7795     }
7796     return SDValue();
7797   };
7798   case Intrinsic::amdgcn_tbuffer_store: {
7799     SDValue VData = Op.getOperand(2);
7800     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7801     if (IsD16)
7802       VData = handleD16VData(VData, DAG);
7803     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7804     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7805     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7806     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7807     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7808     SDValue Ops[] = {
7809       Chain,
7810       VData,             // vdata
7811       Op.getOperand(3),  // rsrc
7812       Op.getOperand(4),  // vindex
7813       Op.getOperand(5),  // voffset
7814       Op.getOperand(6),  // soffset
7815       Op.getOperand(7),  // offset
7816       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7817       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7818       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7819     };
7820     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7821                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7822     MemSDNode *M = cast<MemSDNode>(Op);
7823     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7824                                    M->getMemoryVT(), M->getMemOperand());
7825   }
7826 
7827   case Intrinsic::amdgcn_struct_tbuffer_store: {
7828     SDValue VData = Op.getOperand(2);
7829     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7830     if (IsD16)
7831       VData = handleD16VData(VData, DAG);
7832     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7833     SDValue Ops[] = {
7834       Chain,
7835       VData,             // vdata
7836       Op.getOperand(3),  // rsrc
7837       Op.getOperand(4),  // vindex
7838       Offsets.first,     // voffset
7839       Op.getOperand(6),  // soffset
7840       Offsets.second,    // offset
7841       Op.getOperand(7),  // format
7842       Op.getOperand(8),  // cachepolicy, swizzled buffer
7843       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7844     };
7845     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7846                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7847     MemSDNode *M = cast<MemSDNode>(Op);
7848     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7849                                    M->getMemoryVT(), M->getMemOperand());
7850   }
7851 
7852   case Intrinsic::amdgcn_raw_tbuffer_store: {
7853     SDValue VData = Op.getOperand(2);
7854     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7855     if (IsD16)
7856       VData = handleD16VData(VData, DAG);
7857     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7858     SDValue Ops[] = {
7859       Chain,
7860       VData,             // vdata
7861       Op.getOperand(3),  // rsrc
7862       DAG.getConstant(0, DL, MVT::i32), // vindex
7863       Offsets.first,     // voffset
7864       Op.getOperand(5),  // soffset
7865       Offsets.second,    // offset
7866       Op.getOperand(6),  // format
7867       Op.getOperand(7),  // cachepolicy, swizzled buffer
7868       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7869     };
7870     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7871                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7872     MemSDNode *M = cast<MemSDNode>(Op);
7873     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7874                                    M->getMemoryVT(), M->getMemOperand());
7875   }
7876 
7877   case Intrinsic::amdgcn_buffer_store:
7878   case Intrinsic::amdgcn_buffer_store_format: {
7879     SDValue VData = Op.getOperand(2);
7880     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7881     if (IsD16)
7882       VData = handleD16VData(VData, DAG);
7883     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7884     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7885     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7886     SDValue Ops[] = {
7887       Chain,
7888       VData,
7889       Op.getOperand(3), // rsrc
7890       Op.getOperand(4), // vindex
7891       SDValue(), // voffset -- will be set by setBufferOffsets
7892       SDValue(), // soffset -- will be set by setBufferOffsets
7893       SDValue(), // offset -- will be set by setBufferOffsets
7894       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7895       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7896     };
7897     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7898 
7899     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7900                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7901     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7902     MemSDNode *M = cast<MemSDNode>(Op);
7903     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7904 
7905     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7906     EVT VDataType = VData.getValueType().getScalarType();
7907     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7908       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7909 
7910     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7911                                    M->getMemoryVT(), M->getMemOperand());
7912   }
7913 
7914   case Intrinsic::amdgcn_raw_buffer_store:
7915   case Intrinsic::amdgcn_raw_buffer_store_format: {
7916     const bool IsFormat =
7917         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7918 
7919     SDValue VData = Op.getOperand(2);
7920     EVT VDataVT = VData.getValueType();
7921     EVT EltType = VDataVT.getScalarType();
7922     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7923     if (IsD16) {
7924       VData = handleD16VData(VData, DAG);
7925       VDataVT = VData.getValueType();
7926     }
7927 
7928     if (!isTypeLegal(VDataVT)) {
7929       VData =
7930           DAG.getNode(ISD::BITCAST, DL,
7931                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7932     }
7933 
7934     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7935     SDValue Ops[] = {
7936       Chain,
7937       VData,
7938       Op.getOperand(3), // rsrc
7939       DAG.getConstant(0, DL, MVT::i32), // vindex
7940       Offsets.first,    // voffset
7941       Op.getOperand(5), // soffset
7942       Offsets.second,   // offset
7943       Op.getOperand(6), // cachepolicy, swizzled buffer
7944       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7945     };
7946     unsigned Opc =
7947         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7948     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7949     MemSDNode *M = cast<MemSDNode>(Op);
7950     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7951 
7952     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7953     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7954       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7955 
7956     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7957                                    M->getMemoryVT(), M->getMemOperand());
7958   }
7959 
7960   case Intrinsic::amdgcn_struct_buffer_store:
7961   case Intrinsic::amdgcn_struct_buffer_store_format: {
7962     const bool IsFormat =
7963         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7964 
7965     SDValue VData = Op.getOperand(2);
7966     EVT VDataVT = VData.getValueType();
7967     EVT EltType = VDataVT.getScalarType();
7968     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7969 
7970     if (IsD16) {
7971       VData = handleD16VData(VData, DAG);
7972       VDataVT = VData.getValueType();
7973     }
7974 
7975     if (!isTypeLegal(VDataVT)) {
7976       VData =
7977           DAG.getNode(ISD::BITCAST, DL,
7978                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7979     }
7980 
7981     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7982     SDValue Ops[] = {
7983       Chain,
7984       VData,
7985       Op.getOperand(3), // rsrc
7986       Op.getOperand(4), // vindex
7987       Offsets.first,    // voffset
7988       Op.getOperand(6), // soffset
7989       Offsets.second,   // offset
7990       Op.getOperand(7), // cachepolicy, swizzled buffer
7991       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7992     };
7993     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7994                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7995     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7996     MemSDNode *M = cast<MemSDNode>(Op);
7997     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7998 
7999     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8000     EVT VDataType = VData.getValueType().getScalarType();
8001     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8002       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8003 
8004     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8005                                    M->getMemoryVT(), M->getMemOperand());
8006   }
8007   case Intrinsic::amdgcn_end_cf:
8008     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8009                                       Op->getOperand(2), Chain), 0);
8010 
8011   default: {
8012     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8013             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8014       return lowerImage(Op, ImageDimIntr, DAG, true);
8015 
8016     return Op;
8017   }
8018   }
8019 }
8020 
8021 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8022 // offset (the offset that is included in bounds checking and swizzling, to be
8023 // split between the instruction's voffset and immoffset fields) and soffset
8024 // (the offset that is excluded from bounds checking and swizzling, to go in
8025 // the instruction's soffset field).  This function takes the first kind of
8026 // offset and figures out how to split it between voffset and immoffset.
8027 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8028     SDValue Offset, SelectionDAG &DAG) const {
8029   SDLoc DL(Offset);
8030   const unsigned MaxImm = 4095;
8031   SDValue N0 = Offset;
8032   ConstantSDNode *C1 = nullptr;
8033 
8034   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8035     N0 = SDValue();
8036   else if (DAG.isBaseWithConstantOffset(N0)) {
8037     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8038     N0 = N0.getOperand(0);
8039   }
8040 
8041   if (C1) {
8042     unsigned ImmOffset = C1->getZExtValue();
8043     // If the immediate value is too big for the immoffset field, put the value
8044     // and -4096 into the immoffset field so that the value that is copied/added
8045     // for the voffset field is a multiple of 4096, and it stands more chance
8046     // of being CSEd with the copy/add for another similar load/store.
8047     // However, do not do that rounding down to a multiple of 4096 if that is a
8048     // negative number, as it appears to be illegal to have a negative offset
8049     // in the vgpr, even if adding the immediate offset makes it positive.
8050     unsigned Overflow = ImmOffset & ~MaxImm;
8051     ImmOffset -= Overflow;
8052     if ((int32_t)Overflow < 0) {
8053       Overflow += ImmOffset;
8054       ImmOffset = 0;
8055     }
8056     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8057     if (Overflow) {
8058       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8059       if (!N0)
8060         N0 = OverflowVal;
8061       else {
8062         SDValue Ops[] = { N0, OverflowVal };
8063         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8064       }
8065     }
8066   }
8067   if (!N0)
8068     N0 = DAG.getConstant(0, DL, MVT::i32);
8069   if (!C1)
8070     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8071   return {N0, SDValue(C1, 0)};
8072 }
8073 
8074 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8075 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8076 // pointed to by Offsets.
8077 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8078                                         SelectionDAG &DAG, SDValue *Offsets,
8079                                         Align Alignment) const {
8080   SDLoc DL(CombinedOffset);
8081   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8082     uint32_t Imm = C->getZExtValue();
8083     uint32_t SOffset, ImmOffset;
8084     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8085                                  Alignment)) {
8086       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8087       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8088       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8089       return;
8090     }
8091   }
8092   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8093     SDValue N0 = CombinedOffset.getOperand(0);
8094     SDValue N1 = CombinedOffset.getOperand(1);
8095     uint32_t SOffset, ImmOffset;
8096     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8097     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8098                                                 Subtarget, Alignment)) {
8099       Offsets[0] = N0;
8100       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8101       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8102       return;
8103     }
8104   }
8105   Offsets[0] = CombinedOffset;
8106   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8107   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8108 }
8109 
8110 // Handle 8 bit and 16 bit buffer loads
8111 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8112                                                      EVT LoadVT, SDLoc DL,
8113                                                      ArrayRef<SDValue> Ops,
8114                                                      MemSDNode *M) const {
8115   EVT IntVT = LoadVT.changeTypeToInteger();
8116   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8117          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8118 
8119   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8120   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8121                                                Ops, IntVT,
8122                                                M->getMemOperand());
8123   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8124   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8125 
8126   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8127 }
8128 
8129 // Handle 8 bit and 16 bit buffer stores
8130 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8131                                                       EVT VDataType, SDLoc DL,
8132                                                       SDValue Ops[],
8133                                                       MemSDNode *M) const {
8134   if (VDataType == MVT::f16)
8135     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8136 
8137   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8138   Ops[1] = BufferStoreExt;
8139   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8140                                  AMDGPUISD::BUFFER_STORE_SHORT;
8141   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8142   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8143                                      M->getMemOperand());
8144 }
8145 
8146 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8147                                  ISD::LoadExtType ExtType, SDValue Op,
8148                                  const SDLoc &SL, EVT VT) {
8149   if (VT.bitsLT(Op.getValueType()))
8150     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8151 
8152   switch (ExtType) {
8153   case ISD::SEXTLOAD:
8154     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8155   case ISD::ZEXTLOAD:
8156     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8157   case ISD::EXTLOAD:
8158     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8159   case ISD::NON_EXTLOAD:
8160     return Op;
8161   }
8162 
8163   llvm_unreachable("invalid ext type");
8164 }
8165 
8166 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8167   SelectionDAG &DAG = DCI.DAG;
8168   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8169     return SDValue();
8170 
8171   // FIXME: Constant loads should all be marked invariant.
8172   unsigned AS = Ld->getAddressSpace();
8173   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8174       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8175       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8176     return SDValue();
8177 
8178   // Don't do this early, since it may interfere with adjacent load merging for
8179   // illegal types. We can avoid losing alignment information for exotic types
8180   // pre-legalize.
8181   EVT MemVT = Ld->getMemoryVT();
8182   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8183       MemVT.getSizeInBits() >= 32)
8184     return SDValue();
8185 
8186   SDLoc SL(Ld);
8187 
8188   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8189          "unexpected vector extload");
8190 
8191   // TODO: Drop only high part of range.
8192   SDValue Ptr = Ld->getBasePtr();
8193   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8194                                 MVT::i32, SL, Ld->getChain(), Ptr,
8195                                 Ld->getOffset(),
8196                                 Ld->getPointerInfo(), MVT::i32,
8197                                 Ld->getAlignment(),
8198                                 Ld->getMemOperand()->getFlags(),
8199                                 Ld->getAAInfo(),
8200                                 nullptr); // Drop ranges
8201 
8202   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8203   if (MemVT.isFloatingPoint()) {
8204     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8205            "unexpected fp extload");
8206     TruncVT = MemVT.changeTypeToInteger();
8207   }
8208 
8209   SDValue Cvt = NewLoad;
8210   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8211     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8212                       DAG.getValueType(TruncVT));
8213   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8214              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8215     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8216   } else {
8217     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8218   }
8219 
8220   EVT VT = Ld->getValueType(0);
8221   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8222 
8223   DCI.AddToWorklist(Cvt.getNode());
8224 
8225   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8226   // the appropriate extension from the 32-bit load.
8227   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8228   DCI.AddToWorklist(Cvt.getNode());
8229 
8230   // Handle conversion back to floating point if necessary.
8231   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8232 
8233   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8234 }
8235 
8236 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8237   SDLoc DL(Op);
8238   LoadSDNode *Load = cast<LoadSDNode>(Op);
8239   ISD::LoadExtType ExtType = Load->getExtensionType();
8240   EVT MemVT = Load->getMemoryVT();
8241 
8242   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8243     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8244       return SDValue();
8245 
8246     // FIXME: Copied from PPC
8247     // First, load into 32 bits, then truncate to 1 bit.
8248 
8249     SDValue Chain = Load->getChain();
8250     SDValue BasePtr = Load->getBasePtr();
8251     MachineMemOperand *MMO = Load->getMemOperand();
8252 
8253     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8254 
8255     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8256                                    BasePtr, RealMemVT, MMO);
8257 
8258     if (!MemVT.isVector()) {
8259       SDValue Ops[] = {
8260         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8261         NewLD.getValue(1)
8262       };
8263 
8264       return DAG.getMergeValues(Ops, DL);
8265     }
8266 
8267     SmallVector<SDValue, 3> Elts;
8268     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8269       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8270                                 DAG.getConstant(I, DL, MVT::i32));
8271 
8272       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8273     }
8274 
8275     SDValue Ops[] = {
8276       DAG.getBuildVector(MemVT, DL, Elts),
8277       NewLD.getValue(1)
8278     };
8279 
8280     return DAG.getMergeValues(Ops, DL);
8281   }
8282 
8283   if (!MemVT.isVector())
8284     return SDValue();
8285 
8286   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8287          "Custom lowering for non-i32 vectors hasn't been implemented.");
8288 
8289   unsigned Alignment = Load->getAlignment();
8290   unsigned AS = Load->getAddressSpace();
8291   if (Subtarget->hasLDSMisalignedBug() &&
8292       AS == AMDGPUAS::FLAT_ADDRESS &&
8293       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8294     return SplitVectorLoad(Op, DAG);
8295   }
8296 
8297   MachineFunction &MF = DAG.getMachineFunction();
8298   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8299   // If there is a possibilty that flat instruction access scratch memory
8300   // then we need to use the same legalization rules we use for private.
8301   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8302       !Subtarget->hasMultiDwordFlatScratchAddressing())
8303     AS = MFI->hasFlatScratchInit() ?
8304          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8305 
8306   unsigned NumElements = MemVT.getVectorNumElements();
8307 
8308   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8309       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8310     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8311       if (MemVT.isPow2VectorType())
8312         return SDValue();
8313       return WidenOrSplitVectorLoad(Op, DAG);
8314     }
8315     // Non-uniform loads will be selected to MUBUF instructions, so they
8316     // have the same legalization requirements as global and private
8317     // loads.
8318     //
8319   }
8320 
8321   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8322       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8323       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8324     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8325         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8326         Alignment >= 4 && NumElements < 32) {
8327       if (MemVT.isPow2VectorType())
8328         return SDValue();
8329       return WidenOrSplitVectorLoad(Op, DAG);
8330     }
8331     // Non-uniform loads will be selected to MUBUF instructions, so they
8332     // have the same legalization requirements as global and private
8333     // loads.
8334     //
8335   }
8336   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8337       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8338       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8339       AS == AMDGPUAS::FLAT_ADDRESS) {
8340     if (NumElements > 4)
8341       return SplitVectorLoad(Op, DAG);
8342     // v3 loads not supported on SI.
8343     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8344       return WidenOrSplitVectorLoad(Op, DAG);
8345 
8346     // v3 and v4 loads are supported for private and global memory.
8347     return SDValue();
8348   }
8349   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8350     // Depending on the setting of the private_element_size field in the
8351     // resource descriptor, we can only make private accesses up to a certain
8352     // size.
8353     switch (Subtarget->getMaxPrivateElementSize()) {
8354     case 4: {
8355       SDValue Ops[2];
8356       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8357       return DAG.getMergeValues(Ops, DL);
8358     }
8359     case 8:
8360       if (NumElements > 2)
8361         return SplitVectorLoad(Op, DAG);
8362       return SDValue();
8363     case 16:
8364       // Same as global/flat
8365       if (NumElements > 4)
8366         return SplitVectorLoad(Op, DAG);
8367       // v3 loads not supported on SI.
8368       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8369         return WidenOrSplitVectorLoad(Op, DAG);
8370 
8371       return SDValue();
8372     default:
8373       llvm_unreachable("unsupported private_element_size");
8374     }
8375   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8376     // Use ds_read_b128 or ds_read_b96 when possible.
8377     if (Subtarget->hasDS96AndDS128() &&
8378         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8379          MemVT.getStoreSize() == 12) &&
8380         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8381                                            Load->getAlign()))
8382       return SDValue();
8383 
8384     if (NumElements > 2)
8385       return SplitVectorLoad(Op, DAG);
8386 
8387     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8388     // address is negative, then the instruction is incorrectly treated as
8389     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8390     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8391     // load later in the SILoadStoreOptimizer.
8392     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8393         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8394         Load->getAlignment() < 8) {
8395       return SplitVectorLoad(Op, DAG);
8396     }
8397   }
8398 
8399   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8400                                       MemVT, *Load->getMemOperand())) {
8401     SDValue Ops[2];
8402     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8403     return DAG.getMergeValues(Ops, DL);
8404   }
8405 
8406   return SDValue();
8407 }
8408 
8409 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8410   EVT VT = Op.getValueType();
8411   assert(VT.getSizeInBits() == 64);
8412 
8413   SDLoc DL(Op);
8414   SDValue Cond = Op.getOperand(0);
8415 
8416   if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() &&
8417       !Op->isDivergent()) {
8418     if (VT == MVT::i64)
8419       return Op;
8420     SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1));
8421     SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2));
8422     return DAG.getNode(ISD::BITCAST, DL, VT,
8423                        DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS));
8424   }
8425 
8426   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8427   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8428 
8429   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8430   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8431 
8432   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8433   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8434 
8435   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8436 
8437   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8438   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8439 
8440   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8441 
8442   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8443   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8444 }
8445 
8446 // Catch division cases where we can use shortcuts with rcp and rsq
8447 // instructions.
8448 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8449                                               SelectionDAG &DAG) const {
8450   SDLoc SL(Op);
8451   SDValue LHS = Op.getOperand(0);
8452   SDValue RHS = Op.getOperand(1);
8453   EVT VT = Op.getValueType();
8454   const SDNodeFlags Flags = Op->getFlags();
8455 
8456   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8457 
8458   // Without !fpmath accuracy information, we can't do more because we don't
8459   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8460   if (!AllowInaccurateRcp)
8461     return SDValue();
8462 
8463   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8464     if (CLHS->isExactlyValue(1.0)) {
8465       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8466       // the CI documentation has a worst case error of 1 ulp.
8467       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8468       // use it as long as we aren't trying to use denormals.
8469       //
8470       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8471 
8472       // 1.0 / sqrt(x) -> rsq(x)
8473 
8474       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8475       // error seems really high at 2^29 ULP.
8476       if (RHS.getOpcode() == ISD::FSQRT)
8477         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8478 
8479       // 1.0 / x -> rcp(x)
8480       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8481     }
8482 
8483     // Same as for 1.0, but expand the sign out of the constant.
8484     if (CLHS->isExactlyValue(-1.0)) {
8485       // -1.0 / x -> rcp (fneg x)
8486       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8487       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8488     }
8489   }
8490 
8491   // Turn into multiply by the reciprocal.
8492   // x / y -> x * (1.0 / y)
8493   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8494   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8495 }
8496 
8497 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8498                                                 SelectionDAG &DAG) const {
8499   SDLoc SL(Op);
8500   SDValue X = Op.getOperand(0);
8501   SDValue Y = Op.getOperand(1);
8502   EVT VT = Op.getValueType();
8503   const SDNodeFlags Flags = Op->getFlags();
8504 
8505   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8506                             DAG.getTarget().Options.UnsafeFPMath;
8507   if (!AllowInaccurateDiv)
8508     return SDValue();
8509 
8510   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8511   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8512 
8513   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8514   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8515 
8516   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8517   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8518   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8519   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8520   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8521   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8522 }
8523 
8524 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8525                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8526                           SDNodeFlags Flags) {
8527   if (GlueChain->getNumValues() <= 1) {
8528     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8529   }
8530 
8531   assert(GlueChain->getNumValues() == 3);
8532 
8533   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8534   switch (Opcode) {
8535   default: llvm_unreachable("no chain equivalent for opcode");
8536   case ISD::FMUL:
8537     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8538     break;
8539   }
8540 
8541   return DAG.getNode(Opcode, SL, VTList,
8542                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8543                      Flags);
8544 }
8545 
8546 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8547                            EVT VT, SDValue A, SDValue B, SDValue C,
8548                            SDValue GlueChain, SDNodeFlags Flags) {
8549   if (GlueChain->getNumValues() <= 1) {
8550     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8551   }
8552 
8553   assert(GlueChain->getNumValues() == 3);
8554 
8555   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8556   switch (Opcode) {
8557   default: llvm_unreachable("no chain equivalent for opcode");
8558   case ISD::FMA:
8559     Opcode = AMDGPUISD::FMA_W_CHAIN;
8560     break;
8561   }
8562 
8563   return DAG.getNode(Opcode, SL, VTList,
8564                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8565                      Flags);
8566 }
8567 
8568 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8569   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8570     return FastLowered;
8571 
8572   SDLoc SL(Op);
8573   SDValue Src0 = Op.getOperand(0);
8574   SDValue Src1 = Op.getOperand(1);
8575 
8576   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8577   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8578 
8579   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8580   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8581 
8582   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8583   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8584 
8585   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8586 }
8587 
8588 // Faster 2.5 ULP division that does not support denormals.
8589 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8590   SDLoc SL(Op);
8591   SDValue LHS = Op.getOperand(1);
8592   SDValue RHS = Op.getOperand(2);
8593 
8594   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8595 
8596   const APFloat K0Val(BitsToFloat(0x6f800000));
8597   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8598 
8599   const APFloat K1Val(BitsToFloat(0x2f800000));
8600   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8601 
8602   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8603 
8604   EVT SetCCVT =
8605     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8606 
8607   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8608 
8609   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8610 
8611   // TODO: Should this propagate fast-math-flags?
8612   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8613 
8614   // rcp does not support denormals.
8615   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8616 
8617   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8618 
8619   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8620 }
8621 
8622 // Returns immediate value for setting the F32 denorm mode when using the
8623 // S_DENORM_MODE instruction.
8624 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8625                                     const SDLoc &SL, const GCNSubtarget *ST) {
8626   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8627   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8628                                 ? FP_DENORM_FLUSH_NONE
8629                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8630 
8631   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8632   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8633 }
8634 
8635 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8636   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8637     return FastLowered;
8638 
8639   // The selection matcher assumes anything with a chain selecting to a
8640   // mayRaiseFPException machine instruction. Since we're introducing a chain
8641   // here, we need to explicitly report nofpexcept for the regular fdiv
8642   // lowering.
8643   SDNodeFlags Flags = Op->getFlags();
8644   Flags.setNoFPExcept(true);
8645 
8646   SDLoc SL(Op);
8647   SDValue LHS = Op.getOperand(0);
8648   SDValue RHS = Op.getOperand(1);
8649 
8650   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8651 
8652   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8653 
8654   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8655                                           {RHS, RHS, LHS}, Flags);
8656   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8657                                         {LHS, RHS, LHS}, Flags);
8658 
8659   // Denominator is scaled to not be denormal, so using rcp is ok.
8660   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8661                                   DenominatorScaled, Flags);
8662   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8663                                      DenominatorScaled, Flags);
8664 
8665   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8666                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8667                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8668   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8669 
8670   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8671 
8672   if (!HasFP32Denormals) {
8673     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8674     // lowering. The chain dependence is insufficient, and we need glue. We do
8675     // not need the glue variants in a strictfp function.
8676 
8677     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8678 
8679     SDNode *EnableDenorm;
8680     if (Subtarget->hasDenormModeInst()) {
8681       const SDValue EnableDenormValue =
8682           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8683 
8684       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8685                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8686     } else {
8687       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8688                                                         SL, MVT::i32);
8689       EnableDenorm =
8690           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8691                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8692     }
8693 
8694     SDValue Ops[3] = {
8695       NegDivScale0,
8696       SDValue(EnableDenorm, 0),
8697       SDValue(EnableDenorm, 1)
8698     };
8699 
8700     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8701   }
8702 
8703   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8704                              ApproxRcp, One, NegDivScale0, Flags);
8705 
8706   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8707                              ApproxRcp, Fma0, Flags);
8708 
8709   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8710                            Fma1, Fma1, Flags);
8711 
8712   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8713                              NumeratorScaled, Mul, Flags);
8714 
8715   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8716                              Fma2, Fma1, Mul, Fma2, Flags);
8717 
8718   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8719                              NumeratorScaled, Fma3, Flags);
8720 
8721   if (!HasFP32Denormals) {
8722     SDNode *DisableDenorm;
8723     if (Subtarget->hasDenormModeInst()) {
8724       const SDValue DisableDenormValue =
8725           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8726 
8727       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8728                                   Fma4.getValue(1), DisableDenormValue,
8729                                   Fma4.getValue(2)).getNode();
8730     } else {
8731       const SDValue DisableDenormValue =
8732           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8733 
8734       DisableDenorm = DAG.getMachineNode(
8735           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8736           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8737     }
8738 
8739     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8740                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8741     DAG.setRoot(OutputChain);
8742   }
8743 
8744   SDValue Scale = NumeratorScaled.getValue(1);
8745   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8746                              {Fma4, Fma1, Fma3, Scale}, Flags);
8747 
8748   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8749 }
8750 
8751 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8752   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8753     return FastLowered;
8754 
8755   SDLoc SL(Op);
8756   SDValue X = Op.getOperand(0);
8757   SDValue Y = Op.getOperand(1);
8758 
8759   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8760 
8761   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8762 
8763   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8764 
8765   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8766 
8767   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8768 
8769   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8770 
8771   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8772 
8773   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8774 
8775   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8776 
8777   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8778   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8779 
8780   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8781                              NegDivScale0, Mul, DivScale1);
8782 
8783   SDValue Scale;
8784 
8785   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8786     // Workaround a hardware bug on SI where the condition output from div_scale
8787     // is not usable.
8788 
8789     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8790 
8791     // Figure out if the scale to use for div_fmas.
8792     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8793     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8794     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8795     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8796 
8797     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8798     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8799 
8800     SDValue Scale0Hi
8801       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8802     SDValue Scale1Hi
8803       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8804 
8805     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8806     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8807     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8808   } else {
8809     Scale = DivScale1.getValue(1);
8810   }
8811 
8812   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8813                              Fma4, Fma3, Mul, Scale);
8814 
8815   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8816 }
8817 
8818 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8819   EVT VT = Op.getValueType();
8820 
8821   if (VT == MVT::f32)
8822     return LowerFDIV32(Op, DAG);
8823 
8824   if (VT == MVT::f64)
8825     return LowerFDIV64(Op, DAG);
8826 
8827   if (VT == MVT::f16)
8828     return LowerFDIV16(Op, DAG);
8829 
8830   llvm_unreachable("Unexpected type for fdiv");
8831 }
8832 
8833 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8834   SDLoc DL(Op);
8835   StoreSDNode *Store = cast<StoreSDNode>(Op);
8836   EVT VT = Store->getMemoryVT();
8837 
8838   if (VT == MVT::i1) {
8839     return DAG.getTruncStore(Store->getChain(), DL,
8840        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8841        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8842   }
8843 
8844   assert(VT.isVector() &&
8845          Store->getValue().getValueType().getScalarType() == MVT::i32);
8846 
8847   unsigned AS = Store->getAddressSpace();
8848   if (Subtarget->hasLDSMisalignedBug() &&
8849       AS == AMDGPUAS::FLAT_ADDRESS &&
8850       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8851     return SplitVectorStore(Op, DAG);
8852   }
8853 
8854   MachineFunction &MF = DAG.getMachineFunction();
8855   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8856   // If there is a possibilty that flat instruction access scratch memory
8857   // then we need to use the same legalization rules we use for private.
8858   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8859       !Subtarget->hasMultiDwordFlatScratchAddressing())
8860     AS = MFI->hasFlatScratchInit() ?
8861          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8862 
8863   unsigned NumElements = VT.getVectorNumElements();
8864   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8865       AS == AMDGPUAS::FLAT_ADDRESS) {
8866     if (NumElements > 4)
8867       return SplitVectorStore(Op, DAG);
8868     // v3 stores not supported on SI.
8869     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8870       return SplitVectorStore(Op, DAG);
8871 
8872     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8873                                         VT, *Store->getMemOperand()))
8874       return expandUnalignedStore(Store, DAG);
8875 
8876     return SDValue();
8877   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8878     switch (Subtarget->getMaxPrivateElementSize()) {
8879     case 4:
8880       return scalarizeVectorStore(Store, DAG);
8881     case 8:
8882       if (NumElements > 2)
8883         return SplitVectorStore(Op, DAG);
8884       return SDValue();
8885     case 16:
8886       if (NumElements > 4 ||
8887           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8888         return SplitVectorStore(Op, DAG);
8889       return SDValue();
8890     default:
8891       llvm_unreachable("unsupported private_element_size");
8892     }
8893   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8894     // Use ds_write_b128 or ds_write_b96 when possible.
8895     if (Subtarget->hasDS96AndDS128() &&
8896         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8897          (VT.getStoreSize() == 12)) &&
8898         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8899                                            Store->getAlign()))
8900       return SDValue();
8901 
8902     if (NumElements > 2)
8903       return SplitVectorStore(Op, DAG);
8904 
8905     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8906     // address is negative, then the instruction is incorrectly treated as
8907     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8908     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8909     // store later in the SILoadStoreOptimizer.
8910     if (!Subtarget->hasUsableDSOffset() &&
8911         NumElements == 2 && VT.getStoreSize() == 8 &&
8912         Store->getAlignment() < 8) {
8913       return SplitVectorStore(Op, DAG);
8914     }
8915 
8916     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8917                                         VT, *Store->getMemOperand())) {
8918       if (VT.isVector())
8919         return SplitVectorStore(Op, DAG);
8920       return expandUnalignedStore(Store, DAG);
8921     }
8922 
8923     return SDValue();
8924   } else {
8925     llvm_unreachable("unhandled address space");
8926   }
8927 }
8928 
8929 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8930   SDLoc DL(Op);
8931   EVT VT = Op.getValueType();
8932   SDValue Arg = Op.getOperand(0);
8933   SDValue TrigVal;
8934 
8935   // Propagate fast-math flags so that the multiply we introduce can be folded
8936   // if Arg is already the result of a multiply by constant.
8937   auto Flags = Op->getFlags();
8938 
8939   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8940 
8941   if (Subtarget->hasTrigReducedRange()) {
8942     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8943     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8944   } else {
8945     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8946   }
8947 
8948   switch (Op.getOpcode()) {
8949   case ISD::FCOS:
8950     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8951   case ISD::FSIN:
8952     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8953   default:
8954     llvm_unreachable("Wrong trig opcode");
8955   }
8956 }
8957 
8958 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8959   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8960   assert(AtomicNode->isCompareAndSwap());
8961   unsigned AS = AtomicNode->getAddressSpace();
8962 
8963   // No custom lowering required for local address space
8964   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8965     return Op;
8966 
8967   // Non-local address space requires custom lowering for atomic compare
8968   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8969   SDLoc DL(Op);
8970   SDValue ChainIn = Op.getOperand(0);
8971   SDValue Addr = Op.getOperand(1);
8972   SDValue Old = Op.getOperand(2);
8973   SDValue New = Op.getOperand(3);
8974   EVT VT = Op.getValueType();
8975   MVT SimpleVT = VT.getSimpleVT();
8976   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8977 
8978   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8979   SDValue Ops[] = { ChainIn, Addr, NewOld };
8980 
8981   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8982                                  Ops, VT, AtomicNode->getMemOperand());
8983 }
8984 
8985 //===----------------------------------------------------------------------===//
8986 // Custom DAG optimizations
8987 //===----------------------------------------------------------------------===//
8988 
8989 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8990                                                      DAGCombinerInfo &DCI) const {
8991   EVT VT = N->getValueType(0);
8992   EVT ScalarVT = VT.getScalarType();
8993   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8994     return SDValue();
8995 
8996   SelectionDAG &DAG = DCI.DAG;
8997   SDLoc DL(N);
8998 
8999   SDValue Src = N->getOperand(0);
9000   EVT SrcVT = Src.getValueType();
9001 
9002   // TODO: We could try to match extracting the higher bytes, which would be
9003   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9004   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9005   // about in practice.
9006   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9007     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9008       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9009       DCI.AddToWorklist(Cvt.getNode());
9010 
9011       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9012       if (ScalarVT != MVT::f32) {
9013         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9014                           DAG.getTargetConstant(0, DL, MVT::i32));
9015       }
9016       return Cvt;
9017     }
9018   }
9019 
9020   return SDValue();
9021 }
9022 
9023 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9024 
9025 // This is a variant of
9026 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9027 //
9028 // The normal DAG combiner will do this, but only if the add has one use since
9029 // that would increase the number of instructions.
9030 //
9031 // This prevents us from seeing a constant offset that can be folded into a
9032 // memory instruction's addressing mode. If we know the resulting add offset of
9033 // a pointer can be folded into an addressing offset, we can replace the pointer
9034 // operand with the add of new constant offset. This eliminates one of the uses,
9035 // and may allow the remaining use to also be simplified.
9036 //
9037 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9038                                                unsigned AddrSpace,
9039                                                EVT MemVT,
9040                                                DAGCombinerInfo &DCI) const {
9041   SDValue N0 = N->getOperand(0);
9042   SDValue N1 = N->getOperand(1);
9043 
9044   // We only do this to handle cases where it's profitable when there are
9045   // multiple uses of the add, so defer to the standard combine.
9046   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9047       N0->hasOneUse())
9048     return SDValue();
9049 
9050   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9051   if (!CN1)
9052     return SDValue();
9053 
9054   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9055   if (!CAdd)
9056     return SDValue();
9057 
9058   // If the resulting offset is too large, we can't fold it into the addressing
9059   // mode offset.
9060   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9061   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9062 
9063   AddrMode AM;
9064   AM.HasBaseReg = true;
9065   AM.BaseOffs = Offset.getSExtValue();
9066   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9067     return SDValue();
9068 
9069   SelectionDAG &DAG = DCI.DAG;
9070   SDLoc SL(N);
9071   EVT VT = N->getValueType(0);
9072 
9073   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9074   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9075 
9076   SDNodeFlags Flags;
9077   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9078                           (N0.getOpcode() == ISD::OR ||
9079                            N0->getFlags().hasNoUnsignedWrap()));
9080 
9081   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9082 }
9083 
9084 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9085 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9086 /// specific intrinsic, but they all place the pointer operand first.
9087 static unsigned getBasePtrIndex(const MemSDNode *N) {
9088   switch (N->getOpcode()) {
9089   case ISD::STORE:
9090   case ISD::INTRINSIC_W_CHAIN:
9091   case ISD::INTRINSIC_VOID:
9092     return 2;
9093   default:
9094     return 1;
9095   }
9096 }
9097 
9098 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9099                                                   DAGCombinerInfo &DCI) const {
9100   SelectionDAG &DAG = DCI.DAG;
9101   SDLoc SL(N);
9102 
9103   unsigned PtrIdx = getBasePtrIndex(N);
9104   SDValue Ptr = N->getOperand(PtrIdx);
9105 
9106   // TODO: We could also do this for multiplies.
9107   if (Ptr.getOpcode() == ISD::SHL) {
9108     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9109                                           N->getMemoryVT(), DCI);
9110     if (NewPtr) {
9111       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9112 
9113       NewOps[PtrIdx] = NewPtr;
9114       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9115     }
9116   }
9117 
9118   return SDValue();
9119 }
9120 
9121 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9122   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9123          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9124          (Opc == ISD::XOR && Val == 0);
9125 }
9126 
9127 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9128 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9129 // integer combine opportunities since most 64-bit operations are decomposed
9130 // this way.  TODO: We won't want this for SALU especially if it is an inline
9131 // immediate.
9132 SDValue SITargetLowering::splitBinaryBitConstantOp(
9133   DAGCombinerInfo &DCI,
9134   const SDLoc &SL,
9135   unsigned Opc, SDValue LHS,
9136   const ConstantSDNode *CRHS) const {
9137   uint64_t Val = CRHS->getZExtValue();
9138   uint32_t ValLo = Lo_32(Val);
9139   uint32_t ValHi = Hi_32(Val);
9140   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9141 
9142     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9143          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9144         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9145     // If we need to materialize a 64-bit immediate, it will be split up later
9146     // anyway. Avoid creating the harder to understand 64-bit immediate
9147     // materialization.
9148     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9149   }
9150 
9151   return SDValue();
9152 }
9153 
9154 // Returns true if argument is a boolean value which is not serialized into
9155 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9156 static bool isBoolSGPR(SDValue V) {
9157   if (V.getValueType() != MVT::i1)
9158     return false;
9159   switch (V.getOpcode()) {
9160   default:
9161     break;
9162   case ISD::SETCC:
9163   case AMDGPUISD::FP_CLASS:
9164     return true;
9165   case ISD::AND:
9166   case ISD::OR:
9167   case ISD::XOR:
9168     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9169   }
9170   return false;
9171 }
9172 
9173 // If a constant has all zeroes or all ones within each byte return it.
9174 // Otherwise return 0.
9175 static uint32_t getConstantPermuteMask(uint32_t C) {
9176   // 0xff for any zero byte in the mask
9177   uint32_t ZeroByteMask = 0;
9178   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9179   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9180   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9181   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9182   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9183   if ((NonZeroByteMask & C) != NonZeroByteMask)
9184     return 0; // Partial bytes selected.
9185   return C;
9186 }
9187 
9188 // Check if a node selects whole bytes from its operand 0 starting at a byte
9189 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9190 // or -1 if not succeeded.
9191 // Note byte select encoding:
9192 // value 0-3 selects corresponding source byte;
9193 // value 0xc selects zero;
9194 // value 0xff selects 0xff.
9195 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9196   assert(V.getValueSizeInBits() == 32);
9197 
9198   if (V.getNumOperands() != 2)
9199     return ~0;
9200 
9201   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9202   if (!N1)
9203     return ~0;
9204 
9205   uint32_t C = N1->getZExtValue();
9206 
9207   switch (V.getOpcode()) {
9208   default:
9209     break;
9210   case ISD::AND:
9211     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9212       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9213     }
9214     break;
9215 
9216   case ISD::OR:
9217     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9218       return (0x03020100 & ~ConstMask) | ConstMask;
9219     }
9220     break;
9221 
9222   case ISD::SHL:
9223     if (C % 8)
9224       return ~0;
9225 
9226     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9227 
9228   case ISD::SRL:
9229     if (C % 8)
9230       return ~0;
9231 
9232     return uint32_t(0x0c0c0c0c03020100ull >> C);
9233   }
9234 
9235   return ~0;
9236 }
9237 
9238 SDValue SITargetLowering::performAndCombine(SDNode *N,
9239                                             DAGCombinerInfo &DCI) const {
9240   if (DCI.isBeforeLegalize())
9241     return SDValue();
9242 
9243   SelectionDAG &DAG = DCI.DAG;
9244   EVT VT = N->getValueType(0);
9245   SDValue LHS = N->getOperand(0);
9246   SDValue RHS = N->getOperand(1);
9247 
9248 
9249   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9250   if (VT == MVT::i64 && CRHS) {
9251     if (SDValue Split
9252         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9253       return Split;
9254   }
9255 
9256   if (CRHS && VT == MVT::i32) {
9257     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9258     // nb = number of trailing zeroes in mask
9259     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9260     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9261     uint64_t Mask = CRHS->getZExtValue();
9262     unsigned Bits = countPopulation(Mask);
9263     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9264         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9265       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9266         unsigned Shift = CShift->getZExtValue();
9267         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9268         unsigned Offset = NB + Shift;
9269         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9270           SDLoc SL(N);
9271           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9272                                     LHS->getOperand(0),
9273                                     DAG.getConstant(Offset, SL, MVT::i32),
9274                                     DAG.getConstant(Bits, SL, MVT::i32));
9275           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9276           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9277                                     DAG.getValueType(NarrowVT));
9278           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9279                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9280           return Shl;
9281         }
9282       }
9283     }
9284 
9285     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9286     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9287         isa<ConstantSDNode>(LHS.getOperand(2))) {
9288       uint32_t Sel = getConstantPermuteMask(Mask);
9289       if (!Sel)
9290         return SDValue();
9291 
9292       // Select 0xc for all zero bytes
9293       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9294       SDLoc DL(N);
9295       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9296                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9297     }
9298   }
9299 
9300   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9301   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9302   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9303     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9304     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9305 
9306     SDValue X = LHS.getOperand(0);
9307     SDValue Y = RHS.getOperand(0);
9308     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9309       return SDValue();
9310 
9311     if (LCC == ISD::SETO) {
9312       if (X != LHS.getOperand(1))
9313         return SDValue();
9314 
9315       if (RCC == ISD::SETUNE) {
9316         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9317         if (!C1 || !C1->isInfinity() || C1->isNegative())
9318           return SDValue();
9319 
9320         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9321                               SIInstrFlags::N_SUBNORMAL |
9322                               SIInstrFlags::N_ZERO |
9323                               SIInstrFlags::P_ZERO |
9324                               SIInstrFlags::P_SUBNORMAL |
9325                               SIInstrFlags::P_NORMAL;
9326 
9327         static_assert(((~(SIInstrFlags::S_NAN |
9328                           SIInstrFlags::Q_NAN |
9329                           SIInstrFlags::N_INFINITY |
9330                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9331                       "mask not equal");
9332 
9333         SDLoc DL(N);
9334         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9335                            X, DAG.getConstant(Mask, DL, MVT::i32));
9336       }
9337     }
9338   }
9339 
9340   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9341     std::swap(LHS, RHS);
9342 
9343   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9344       RHS.hasOneUse()) {
9345     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9346     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9347     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9348     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9349     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9350         (RHS.getOperand(0) == LHS.getOperand(0) &&
9351          LHS.getOperand(0) == LHS.getOperand(1))) {
9352       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9353       unsigned NewMask = LCC == ISD::SETO ?
9354         Mask->getZExtValue() & ~OrdMask :
9355         Mask->getZExtValue() & OrdMask;
9356 
9357       SDLoc DL(N);
9358       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9359                          DAG.getConstant(NewMask, DL, MVT::i32));
9360     }
9361   }
9362 
9363   if (VT == MVT::i32 &&
9364       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9365     // and x, (sext cc from i1) => select cc, x, 0
9366     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9367       std::swap(LHS, RHS);
9368     if (isBoolSGPR(RHS.getOperand(0)))
9369       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9370                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9371   }
9372 
9373   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9374   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9375   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9376       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9377     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9378     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9379     if (LHSMask != ~0u && RHSMask != ~0u) {
9380       // Canonicalize the expression in an attempt to have fewer unique masks
9381       // and therefore fewer registers used to hold the masks.
9382       if (LHSMask > RHSMask) {
9383         std::swap(LHSMask, RHSMask);
9384         std::swap(LHS, RHS);
9385       }
9386 
9387       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9388       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9389       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9390       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9391 
9392       // Check of we need to combine values from two sources within a byte.
9393       if (!(LHSUsedLanes & RHSUsedLanes) &&
9394           // If we select high and lower word keep it for SDWA.
9395           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9396           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9397         // Each byte in each mask is either selector mask 0-3, or has higher
9398         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9399         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9400         // mask which is not 0xff wins. By anding both masks we have a correct
9401         // result except that 0x0c shall be corrected to give 0x0c only.
9402         uint32_t Mask = LHSMask & RHSMask;
9403         for (unsigned I = 0; I < 32; I += 8) {
9404           uint32_t ByteSel = 0xff << I;
9405           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9406             Mask &= (0x0c << I) & 0xffffffff;
9407         }
9408 
9409         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9410         // or 0x0c.
9411         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9412         SDLoc DL(N);
9413 
9414         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9415                            LHS.getOperand(0), RHS.getOperand(0),
9416                            DAG.getConstant(Sel, DL, MVT::i32));
9417       }
9418     }
9419   }
9420 
9421   return SDValue();
9422 }
9423 
9424 SDValue SITargetLowering::performOrCombine(SDNode *N,
9425                                            DAGCombinerInfo &DCI) const {
9426   SelectionDAG &DAG = DCI.DAG;
9427   SDValue LHS = N->getOperand(0);
9428   SDValue RHS = N->getOperand(1);
9429 
9430   EVT VT = N->getValueType(0);
9431   if (VT == MVT::i1) {
9432     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9433     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9434         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9435       SDValue Src = LHS.getOperand(0);
9436       if (Src != RHS.getOperand(0))
9437         return SDValue();
9438 
9439       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9440       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9441       if (!CLHS || !CRHS)
9442         return SDValue();
9443 
9444       // Only 10 bits are used.
9445       static const uint32_t MaxMask = 0x3ff;
9446 
9447       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9448       SDLoc DL(N);
9449       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9450                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9451     }
9452 
9453     return SDValue();
9454   }
9455 
9456   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9457   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9458       LHS.getOpcode() == AMDGPUISD::PERM &&
9459       isa<ConstantSDNode>(LHS.getOperand(2))) {
9460     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9461     if (!Sel)
9462       return SDValue();
9463 
9464     Sel |= LHS.getConstantOperandVal(2);
9465     SDLoc DL(N);
9466     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9467                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9468   }
9469 
9470   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9471   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9472   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9473       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9474     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9475     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9476     if (LHSMask != ~0u && RHSMask != ~0u) {
9477       // Canonicalize the expression in an attempt to have fewer unique masks
9478       // and therefore fewer registers used to hold the masks.
9479       if (LHSMask > RHSMask) {
9480         std::swap(LHSMask, RHSMask);
9481         std::swap(LHS, RHS);
9482       }
9483 
9484       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9485       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9486       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9487       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9488 
9489       // Check of we need to combine values from two sources within a byte.
9490       if (!(LHSUsedLanes & RHSUsedLanes) &&
9491           // If we select high and lower word keep it for SDWA.
9492           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9493           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9494         // Kill zero bytes selected by other mask. Zero value is 0xc.
9495         LHSMask &= ~RHSUsedLanes;
9496         RHSMask &= ~LHSUsedLanes;
9497         // Add 4 to each active LHS lane
9498         LHSMask |= LHSUsedLanes & 0x04040404;
9499         // Combine masks
9500         uint32_t Sel = LHSMask | RHSMask;
9501         SDLoc DL(N);
9502 
9503         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9504                            LHS.getOperand(0), RHS.getOperand(0),
9505                            DAG.getConstant(Sel, DL, MVT::i32));
9506       }
9507     }
9508   }
9509 
9510   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9511     return SDValue();
9512 
9513   // TODO: This could be a generic combine with a predicate for extracting the
9514   // high half of an integer being free.
9515 
9516   // (or i64:x, (zero_extend i32:y)) ->
9517   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9518   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9519       RHS.getOpcode() != ISD::ZERO_EXTEND)
9520     std::swap(LHS, RHS);
9521 
9522   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9523     SDValue ExtSrc = RHS.getOperand(0);
9524     EVT SrcVT = ExtSrc.getValueType();
9525     if (SrcVT == MVT::i32) {
9526       SDLoc SL(N);
9527       SDValue LowLHS, HiBits;
9528       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9529       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9530 
9531       DCI.AddToWorklist(LowOr.getNode());
9532       DCI.AddToWorklist(HiBits.getNode());
9533 
9534       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9535                                 LowOr, HiBits);
9536       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9537     }
9538   }
9539 
9540   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9541   if (CRHS) {
9542     if (SDValue Split
9543           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9544                                      N->getOperand(0), CRHS))
9545       return Split;
9546   }
9547 
9548   return SDValue();
9549 }
9550 
9551 SDValue SITargetLowering::performXorCombine(SDNode *N,
9552                                             DAGCombinerInfo &DCI) const {
9553   EVT VT = N->getValueType(0);
9554   if (VT != MVT::i64)
9555     return SDValue();
9556 
9557   SDValue LHS = N->getOperand(0);
9558   SDValue RHS = N->getOperand(1);
9559 
9560   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9561   if (CRHS) {
9562     if (SDValue Split
9563           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9564       return Split;
9565   }
9566 
9567   return SDValue();
9568 }
9569 
9570 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9571                                                    DAGCombinerInfo &DCI) const {
9572   if (!Subtarget->has16BitInsts() ||
9573       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9574     return SDValue();
9575 
9576   EVT VT = N->getValueType(0);
9577   if (VT != MVT::i32)
9578     return SDValue();
9579 
9580   SDValue Src = N->getOperand(0);
9581   if (Src.getValueType() != MVT::i16)
9582     return SDValue();
9583 
9584   return SDValue();
9585 }
9586 
9587 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9588                                                         DAGCombinerInfo &DCI)
9589                                                         const {
9590   SDValue Src = N->getOperand(0);
9591   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9592 
9593   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9594       VTSign->getVT() == MVT::i8) ||
9595       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9596       VTSign->getVT() == MVT::i16)) &&
9597       Src.hasOneUse()) {
9598     auto *M = cast<MemSDNode>(Src);
9599     SDValue Ops[] = {
9600       Src.getOperand(0), // Chain
9601       Src.getOperand(1), // rsrc
9602       Src.getOperand(2), // vindex
9603       Src.getOperand(3), // voffset
9604       Src.getOperand(4), // soffset
9605       Src.getOperand(5), // offset
9606       Src.getOperand(6),
9607       Src.getOperand(7)
9608     };
9609     // replace with BUFFER_LOAD_BYTE/SHORT
9610     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9611                                          Src.getOperand(0).getValueType());
9612     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9613                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9614     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9615                                                           ResList,
9616                                                           Ops, M->getMemoryVT(),
9617                                                           M->getMemOperand());
9618     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9619                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9620   }
9621   return SDValue();
9622 }
9623 
9624 SDValue SITargetLowering::performClassCombine(SDNode *N,
9625                                               DAGCombinerInfo &DCI) const {
9626   SelectionDAG &DAG = DCI.DAG;
9627   SDValue Mask = N->getOperand(1);
9628 
9629   // fp_class x, 0 -> false
9630   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9631     if (CMask->isZero())
9632       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9633   }
9634 
9635   if (N->getOperand(0).isUndef())
9636     return DAG.getUNDEF(MVT::i1);
9637 
9638   return SDValue();
9639 }
9640 
9641 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9642                                             DAGCombinerInfo &DCI) const {
9643   EVT VT = N->getValueType(0);
9644   SDValue N0 = N->getOperand(0);
9645 
9646   if (N0.isUndef())
9647     return N0;
9648 
9649   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9650                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9651     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9652                            N->getFlags());
9653   }
9654 
9655   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9656     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9657                            N0.getOperand(0), N->getFlags());
9658   }
9659 
9660   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9661 }
9662 
9663 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9664                                        unsigned MaxDepth) const {
9665   unsigned Opcode = Op.getOpcode();
9666   if (Opcode == ISD::FCANONICALIZE)
9667     return true;
9668 
9669   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9670     auto F = CFP->getValueAPF();
9671     if (F.isNaN() && F.isSignaling())
9672       return false;
9673     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9674   }
9675 
9676   // If source is a result of another standard FP operation it is already in
9677   // canonical form.
9678   if (MaxDepth == 0)
9679     return false;
9680 
9681   switch (Opcode) {
9682   // These will flush denorms if required.
9683   case ISD::FADD:
9684   case ISD::FSUB:
9685   case ISD::FMUL:
9686   case ISD::FCEIL:
9687   case ISD::FFLOOR:
9688   case ISD::FMA:
9689   case ISD::FMAD:
9690   case ISD::FSQRT:
9691   case ISD::FDIV:
9692   case ISD::FREM:
9693   case ISD::FP_ROUND:
9694   case ISD::FP_EXTEND:
9695   case AMDGPUISD::FMUL_LEGACY:
9696   case AMDGPUISD::FMAD_FTZ:
9697   case AMDGPUISD::RCP:
9698   case AMDGPUISD::RSQ:
9699   case AMDGPUISD::RSQ_CLAMP:
9700   case AMDGPUISD::RCP_LEGACY:
9701   case AMDGPUISD::RCP_IFLAG:
9702   case AMDGPUISD::DIV_SCALE:
9703   case AMDGPUISD::DIV_FMAS:
9704   case AMDGPUISD::DIV_FIXUP:
9705   case AMDGPUISD::FRACT:
9706   case AMDGPUISD::LDEXP:
9707   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9708   case AMDGPUISD::CVT_F32_UBYTE0:
9709   case AMDGPUISD::CVT_F32_UBYTE1:
9710   case AMDGPUISD::CVT_F32_UBYTE2:
9711   case AMDGPUISD::CVT_F32_UBYTE3:
9712     return true;
9713 
9714   // It can/will be lowered or combined as a bit operation.
9715   // Need to check their input recursively to handle.
9716   case ISD::FNEG:
9717   case ISD::FABS:
9718   case ISD::FCOPYSIGN:
9719     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9720 
9721   case ISD::FSIN:
9722   case ISD::FCOS:
9723   case ISD::FSINCOS:
9724     return Op.getValueType().getScalarType() != MVT::f16;
9725 
9726   case ISD::FMINNUM:
9727   case ISD::FMAXNUM:
9728   case ISD::FMINNUM_IEEE:
9729   case ISD::FMAXNUM_IEEE:
9730   case AMDGPUISD::CLAMP:
9731   case AMDGPUISD::FMED3:
9732   case AMDGPUISD::FMAX3:
9733   case AMDGPUISD::FMIN3: {
9734     // FIXME: Shouldn't treat the generic operations different based these.
9735     // However, we aren't really required to flush the result from
9736     // minnum/maxnum..
9737 
9738     // snans will be quieted, so we only need to worry about denormals.
9739     if (Subtarget->supportsMinMaxDenormModes() ||
9740         denormalsEnabledForType(DAG, Op.getValueType()))
9741       return true;
9742 
9743     // Flushing may be required.
9744     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9745     // targets need to check their input recursively.
9746 
9747     // FIXME: Does this apply with clamp? It's implemented with max.
9748     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9749       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9750         return false;
9751     }
9752 
9753     return true;
9754   }
9755   case ISD::SELECT: {
9756     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9757            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9758   }
9759   case ISD::BUILD_VECTOR: {
9760     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9761       SDValue SrcOp = Op.getOperand(i);
9762       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9763         return false;
9764     }
9765 
9766     return true;
9767   }
9768   case ISD::EXTRACT_VECTOR_ELT:
9769   case ISD::EXTRACT_SUBVECTOR: {
9770     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9771   }
9772   case ISD::INSERT_VECTOR_ELT: {
9773     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9774            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9775   }
9776   case ISD::UNDEF:
9777     // Could be anything.
9778     return false;
9779 
9780   case ISD::BITCAST:
9781     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9782   case ISD::TRUNCATE: {
9783     // Hack round the mess we make when legalizing extract_vector_elt
9784     if (Op.getValueType() == MVT::i16) {
9785       SDValue TruncSrc = Op.getOperand(0);
9786       if (TruncSrc.getValueType() == MVT::i32 &&
9787           TruncSrc.getOpcode() == ISD::BITCAST &&
9788           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9789         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9790       }
9791     }
9792     return false;
9793   }
9794   case ISD::INTRINSIC_WO_CHAIN: {
9795     unsigned IntrinsicID
9796       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9797     // TODO: Handle more intrinsics
9798     switch (IntrinsicID) {
9799     case Intrinsic::amdgcn_cvt_pkrtz:
9800     case Intrinsic::amdgcn_cubeid:
9801     case Intrinsic::amdgcn_frexp_mant:
9802     case Intrinsic::amdgcn_fdot2:
9803     case Intrinsic::amdgcn_rcp:
9804     case Intrinsic::amdgcn_rsq:
9805     case Intrinsic::amdgcn_rsq_clamp:
9806     case Intrinsic::amdgcn_rcp_legacy:
9807     case Intrinsic::amdgcn_rsq_legacy:
9808     case Intrinsic::amdgcn_trig_preop:
9809       return true;
9810     default:
9811       break;
9812     }
9813 
9814     LLVM_FALLTHROUGH;
9815   }
9816   default:
9817     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9818            DAG.isKnownNeverSNaN(Op);
9819   }
9820 
9821   llvm_unreachable("invalid operation");
9822 }
9823 
9824 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9825                                        unsigned MaxDepth) const {
9826   MachineRegisterInfo &MRI = MF.getRegInfo();
9827   MachineInstr *MI = MRI.getVRegDef(Reg);
9828   unsigned Opcode = MI->getOpcode();
9829 
9830   if (Opcode == AMDGPU::G_FCANONICALIZE)
9831     return true;
9832 
9833   Optional<FPValueAndVReg> FCR;
9834   // Constant splat (can be padded with undef) or scalar constant.
9835   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9836     if (FCR->Value.isSignaling())
9837       return false;
9838     return !FCR->Value.isDenormal() ||
9839            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9840   }
9841 
9842   if (MaxDepth == 0)
9843     return false;
9844 
9845   switch (Opcode) {
9846   case AMDGPU::G_FMINNUM_IEEE:
9847   case AMDGPU::G_FMAXNUM_IEEE: {
9848     if (Subtarget->supportsMinMaxDenormModes() ||
9849         denormalsEnabledForType(MRI.getType(Reg), MF))
9850       return true;
9851     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9852       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9853         return false;
9854     return true;
9855   }
9856   default:
9857     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9858            isKnownNeverSNaN(Reg, MRI);
9859   }
9860 
9861   llvm_unreachable("invalid operation");
9862 }
9863 
9864 // Constant fold canonicalize.
9865 SDValue SITargetLowering::getCanonicalConstantFP(
9866   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9867   // Flush denormals to 0 if not enabled.
9868   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9869     return DAG.getConstantFP(0.0, SL, VT);
9870 
9871   if (C.isNaN()) {
9872     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9873     if (C.isSignaling()) {
9874       // Quiet a signaling NaN.
9875       // FIXME: Is this supposed to preserve payload bits?
9876       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9877     }
9878 
9879     // Make sure it is the canonical NaN bitpattern.
9880     //
9881     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9882     // immediate?
9883     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9884       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9885   }
9886 
9887   // Already canonical.
9888   return DAG.getConstantFP(C, SL, VT);
9889 }
9890 
9891 static bool vectorEltWillFoldAway(SDValue Op) {
9892   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9893 }
9894 
9895 SDValue SITargetLowering::performFCanonicalizeCombine(
9896   SDNode *N,
9897   DAGCombinerInfo &DCI) const {
9898   SelectionDAG &DAG = DCI.DAG;
9899   SDValue N0 = N->getOperand(0);
9900   EVT VT = N->getValueType(0);
9901 
9902   // fcanonicalize undef -> qnan
9903   if (N0.isUndef()) {
9904     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9905     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9906   }
9907 
9908   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9909     EVT VT = N->getValueType(0);
9910     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9911   }
9912 
9913   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9914   //                                                   (fcanonicalize k)
9915   //
9916   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9917 
9918   // TODO: This could be better with wider vectors that will be split to v2f16,
9919   // and to consider uses since there aren't that many packed operations.
9920   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9921       isTypeLegal(MVT::v2f16)) {
9922     SDLoc SL(N);
9923     SDValue NewElts[2];
9924     SDValue Lo = N0.getOperand(0);
9925     SDValue Hi = N0.getOperand(1);
9926     EVT EltVT = Lo.getValueType();
9927 
9928     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9929       for (unsigned I = 0; I != 2; ++I) {
9930         SDValue Op = N0.getOperand(I);
9931         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9932           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9933                                               CFP->getValueAPF());
9934         } else if (Op.isUndef()) {
9935           // Handled below based on what the other operand is.
9936           NewElts[I] = Op;
9937         } else {
9938           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9939         }
9940       }
9941 
9942       // If one half is undef, and one is constant, perfer a splat vector rather
9943       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9944       // cheaper to use and may be free with a packed operation.
9945       if (NewElts[0].isUndef()) {
9946         if (isa<ConstantFPSDNode>(NewElts[1]))
9947           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9948             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9949       }
9950 
9951       if (NewElts[1].isUndef()) {
9952         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9953           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9954       }
9955 
9956       return DAG.getBuildVector(VT, SL, NewElts);
9957     }
9958   }
9959 
9960   unsigned SrcOpc = N0.getOpcode();
9961 
9962   // If it's free to do so, push canonicalizes further up the source, which may
9963   // find a canonical source.
9964   //
9965   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9966   // sNaNs.
9967   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9968     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9969     if (CRHS && N0.hasOneUse()) {
9970       SDLoc SL(N);
9971       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9972                                    N0.getOperand(0));
9973       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9974       DCI.AddToWorklist(Canon0.getNode());
9975 
9976       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9977     }
9978   }
9979 
9980   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9981 }
9982 
9983 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9984   switch (Opc) {
9985   case ISD::FMAXNUM:
9986   case ISD::FMAXNUM_IEEE:
9987     return AMDGPUISD::FMAX3;
9988   case ISD::SMAX:
9989     return AMDGPUISD::SMAX3;
9990   case ISD::UMAX:
9991     return AMDGPUISD::UMAX3;
9992   case ISD::FMINNUM:
9993   case ISD::FMINNUM_IEEE:
9994     return AMDGPUISD::FMIN3;
9995   case ISD::SMIN:
9996     return AMDGPUISD::SMIN3;
9997   case ISD::UMIN:
9998     return AMDGPUISD::UMIN3;
9999   default:
10000     llvm_unreachable("Not a min/max opcode");
10001   }
10002 }
10003 
10004 SDValue SITargetLowering::performIntMed3ImmCombine(
10005   SelectionDAG &DAG, const SDLoc &SL,
10006   SDValue Op0, SDValue Op1, bool Signed) const {
10007   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10008   if (!K1)
10009     return SDValue();
10010 
10011   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10012   if (!K0)
10013     return SDValue();
10014 
10015   if (Signed) {
10016     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10017       return SDValue();
10018   } else {
10019     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10020       return SDValue();
10021   }
10022 
10023   EVT VT = K0->getValueType(0);
10024   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10025   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10026     return DAG.getNode(Med3Opc, SL, VT,
10027                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10028   }
10029 
10030   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10031   if (VT == MVT::i16) {
10032     MVT NVT = MVT::i32;
10033     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10034 
10035     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10036     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10037     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10038 
10039     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10040     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10041   }
10042 
10043   return SDValue();
10044 }
10045 
10046 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10047   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10048     return C;
10049 
10050   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10051     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10052       return C;
10053   }
10054 
10055   return nullptr;
10056 }
10057 
10058 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10059                                                   const SDLoc &SL,
10060                                                   SDValue Op0,
10061                                                   SDValue Op1) const {
10062   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10063   if (!K1)
10064     return SDValue();
10065 
10066   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10067   if (!K0)
10068     return SDValue();
10069 
10070   // Ordered >= (although NaN inputs should have folded away by now).
10071   if (K0->getValueAPF() > K1->getValueAPF())
10072     return SDValue();
10073 
10074   const MachineFunction &MF = DAG.getMachineFunction();
10075   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10076 
10077   // TODO: Check IEEE bit enabled?
10078   EVT VT = Op0.getValueType();
10079   if (Info->getMode().DX10Clamp) {
10080     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10081     // hardware fmed3 behavior converting to a min.
10082     // FIXME: Should this be allowing -0.0?
10083     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10084       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10085   }
10086 
10087   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10088   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10089     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10090     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10091     // then give the other result, which is different from med3 with a NaN
10092     // input.
10093     SDValue Var = Op0.getOperand(0);
10094     if (!DAG.isKnownNeverSNaN(Var))
10095       return SDValue();
10096 
10097     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10098 
10099     if ((!K0->hasOneUse() ||
10100          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10101         (!K1->hasOneUse() ||
10102          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10103       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10104                          Var, SDValue(K0, 0), SDValue(K1, 0));
10105     }
10106   }
10107 
10108   return SDValue();
10109 }
10110 
10111 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10112                                                DAGCombinerInfo &DCI) const {
10113   SelectionDAG &DAG = DCI.DAG;
10114 
10115   EVT VT = N->getValueType(0);
10116   unsigned Opc = N->getOpcode();
10117   SDValue Op0 = N->getOperand(0);
10118   SDValue Op1 = N->getOperand(1);
10119 
10120   // Only do this if the inner op has one use since this will just increases
10121   // register pressure for no benefit.
10122 
10123   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10124       !VT.isVector() &&
10125       (VT == MVT::i32 || VT == MVT::f32 ||
10126        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10127     // max(max(a, b), c) -> max3(a, b, c)
10128     // min(min(a, b), c) -> min3(a, b, c)
10129     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10130       SDLoc DL(N);
10131       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10132                          DL,
10133                          N->getValueType(0),
10134                          Op0.getOperand(0),
10135                          Op0.getOperand(1),
10136                          Op1);
10137     }
10138 
10139     // Try commuted.
10140     // max(a, max(b, c)) -> max3(a, b, c)
10141     // min(a, min(b, c)) -> min3(a, b, c)
10142     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10143       SDLoc DL(N);
10144       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10145                          DL,
10146                          N->getValueType(0),
10147                          Op0,
10148                          Op1.getOperand(0),
10149                          Op1.getOperand(1));
10150     }
10151   }
10152 
10153   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10154   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10155     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10156       return Med3;
10157   }
10158 
10159   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10160     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10161       return Med3;
10162   }
10163 
10164   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10165   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10166        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10167        (Opc == AMDGPUISD::FMIN_LEGACY &&
10168         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10169       (VT == MVT::f32 || VT == MVT::f64 ||
10170        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10171        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10172       Op0.hasOneUse()) {
10173     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10174       return Res;
10175   }
10176 
10177   return SDValue();
10178 }
10179 
10180 static bool isClampZeroToOne(SDValue A, SDValue B) {
10181   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10182     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10183       // FIXME: Should this be allowing -0.0?
10184       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10185              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10186     }
10187   }
10188 
10189   return false;
10190 }
10191 
10192 // FIXME: Should only worry about snans for version with chain.
10193 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10194                                               DAGCombinerInfo &DCI) const {
10195   EVT VT = N->getValueType(0);
10196   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10197   // NaNs. With a NaN input, the order of the operands may change the result.
10198 
10199   SelectionDAG &DAG = DCI.DAG;
10200   SDLoc SL(N);
10201 
10202   SDValue Src0 = N->getOperand(0);
10203   SDValue Src1 = N->getOperand(1);
10204   SDValue Src2 = N->getOperand(2);
10205 
10206   if (isClampZeroToOne(Src0, Src1)) {
10207     // const_a, const_b, x -> clamp is safe in all cases including signaling
10208     // nans.
10209     // FIXME: Should this be allowing -0.0?
10210     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10211   }
10212 
10213   const MachineFunction &MF = DAG.getMachineFunction();
10214   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10215 
10216   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10217   // handling no dx10-clamp?
10218   if (Info->getMode().DX10Clamp) {
10219     // If NaNs is clamped to 0, we are free to reorder the inputs.
10220 
10221     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10222       std::swap(Src0, Src1);
10223 
10224     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10225       std::swap(Src1, Src2);
10226 
10227     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10228       std::swap(Src0, Src1);
10229 
10230     if (isClampZeroToOne(Src1, Src2))
10231       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10232   }
10233 
10234   return SDValue();
10235 }
10236 
10237 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10238                                                  DAGCombinerInfo &DCI) const {
10239   SDValue Src0 = N->getOperand(0);
10240   SDValue Src1 = N->getOperand(1);
10241   if (Src0.isUndef() && Src1.isUndef())
10242     return DCI.DAG.getUNDEF(N->getValueType(0));
10243   return SDValue();
10244 }
10245 
10246 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10247 // expanded into a set of cmp/select instructions.
10248 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10249                                                 unsigned NumElem,
10250                                                 bool IsDivergentIdx) {
10251   if (UseDivergentRegisterIndexing)
10252     return false;
10253 
10254   unsigned VecSize = EltSize * NumElem;
10255 
10256   // Sub-dword vectors of size 2 dword or less have better implementation.
10257   if (VecSize <= 64 && EltSize < 32)
10258     return false;
10259 
10260   // Always expand the rest of sub-dword instructions, otherwise it will be
10261   // lowered via memory.
10262   if (EltSize < 32)
10263     return true;
10264 
10265   // Always do this if var-idx is divergent, otherwise it will become a loop.
10266   if (IsDivergentIdx)
10267     return true;
10268 
10269   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10270   unsigned NumInsts = NumElem /* Number of compares */ +
10271                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10272   return NumInsts <= 16;
10273 }
10274 
10275 static bool shouldExpandVectorDynExt(SDNode *N) {
10276   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10277   if (isa<ConstantSDNode>(Idx))
10278     return false;
10279 
10280   SDValue Vec = N->getOperand(0);
10281   EVT VecVT = Vec.getValueType();
10282   EVT EltVT = VecVT.getVectorElementType();
10283   unsigned EltSize = EltVT.getSizeInBits();
10284   unsigned NumElem = VecVT.getVectorNumElements();
10285 
10286   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10287                                                     Idx->isDivergent());
10288 }
10289 
10290 SDValue SITargetLowering::performExtractVectorEltCombine(
10291   SDNode *N, DAGCombinerInfo &DCI) const {
10292   SDValue Vec = N->getOperand(0);
10293   SelectionDAG &DAG = DCI.DAG;
10294 
10295   EVT VecVT = Vec.getValueType();
10296   EVT EltVT = VecVT.getVectorElementType();
10297 
10298   if ((Vec.getOpcode() == ISD::FNEG ||
10299        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10300     SDLoc SL(N);
10301     EVT EltVT = N->getValueType(0);
10302     SDValue Idx = N->getOperand(1);
10303     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10304                               Vec.getOperand(0), Idx);
10305     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10306   }
10307 
10308   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10309   //    =>
10310   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10311   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10312   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10313   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10314     SDLoc SL(N);
10315     EVT EltVT = N->getValueType(0);
10316     SDValue Idx = N->getOperand(1);
10317     unsigned Opc = Vec.getOpcode();
10318 
10319     switch(Opc) {
10320     default:
10321       break;
10322       // TODO: Support other binary operations.
10323     case ISD::FADD:
10324     case ISD::FSUB:
10325     case ISD::FMUL:
10326     case ISD::ADD:
10327     case ISD::UMIN:
10328     case ISD::UMAX:
10329     case ISD::SMIN:
10330     case ISD::SMAX:
10331     case ISD::FMAXNUM:
10332     case ISD::FMINNUM:
10333     case ISD::FMAXNUM_IEEE:
10334     case ISD::FMINNUM_IEEE: {
10335       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10336                                  Vec.getOperand(0), Idx);
10337       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10338                                  Vec.getOperand(1), Idx);
10339 
10340       DCI.AddToWorklist(Elt0.getNode());
10341       DCI.AddToWorklist(Elt1.getNode());
10342       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10343     }
10344     }
10345   }
10346 
10347   unsigned VecSize = VecVT.getSizeInBits();
10348   unsigned EltSize = EltVT.getSizeInBits();
10349 
10350   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10351   if (::shouldExpandVectorDynExt(N)) {
10352     SDLoc SL(N);
10353     SDValue Idx = N->getOperand(1);
10354     SDValue V;
10355     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10356       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10357       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10358       if (I == 0)
10359         V = Elt;
10360       else
10361         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10362     }
10363     return V;
10364   }
10365 
10366   if (!DCI.isBeforeLegalize())
10367     return SDValue();
10368 
10369   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10370   // elements. This exposes more load reduction opportunities by replacing
10371   // multiple small extract_vector_elements with a single 32-bit extract.
10372   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10373   if (isa<MemSDNode>(Vec) &&
10374       EltSize <= 16 &&
10375       EltVT.isByteSized() &&
10376       VecSize > 32 &&
10377       VecSize % 32 == 0 &&
10378       Idx) {
10379     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10380 
10381     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10382     unsigned EltIdx = BitIndex / 32;
10383     unsigned LeftoverBitIdx = BitIndex % 32;
10384     SDLoc SL(N);
10385 
10386     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10387     DCI.AddToWorklist(Cast.getNode());
10388 
10389     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10390                               DAG.getConstant(EltIdx, SL, MVT::i32));
10391     DCI.AddToWorklist(Elt.getNode());
10392     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10393                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10394     DCI.AddToWorklist(Srl.getNode());
10395 
10396     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10397     DCI.AddToWorklist(Trunc.getNode());
10398     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10399   }
10400 
10401   return SDValue();
10402 }
10403 
10404 SDValue
10405 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10406                                                 DAGCombinerInfo &DCI) const {
10407   SDValue Vec = N->getOperand(0);
10408   SDValue Idx = N->getOperand(2);
10409   EVT VecVT = Vec.getValueType();
10410   EVT EltVT = VecVT.getVectorElementType();
10411 
10412   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10413   // => BUILD_VECTOR n x select (e, const-idx)
10414   if (!::shouldExpandVectorDynExt(N))
10415     return SDValue();
10416 
10417   SelectionDAG &DAG = DCI.DAG;
10418   SDLoc SL(N);
10419   SDValue Ins = N->getOperand(1);
10420   EVT IdxVT = Idx.getValueType();
10421 
10422   SmallVector<SDValue, 16> Ops;
10423   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10424     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10425     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10426     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10427     Ops.push_back(V);
10428   }
10429 
10430   return DAG.getBuildVector(VecVT, SL, Ops);
10431 }
10432 
10433 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10434                                           const SDNode *N0,
10435                                           const SDNode *N1) const {
10436   EVT VT = N0->getValueType(0);
10437 
10438   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10439   // support denormals ever.
10440   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10441        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10442         getSubtarget()->hasMadF16())) &&
10443        isOperationLegal(ISD::FMAD, VT))
10444     return ISD::FMAD;
10445 
10446   const TargetOptions &Options = DAG.getTarget().Options;
10447   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10448        (N0->getFlags().hasAllowContract() &&
10449         N1->getFlags().hasAllowContract())) &&
10450       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10451     return ISD::FMA;
10452   }
10453 
10454   return 0;
10455 }
10456 
10457 // For a reassociatable opcode perform:
10458 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10459 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10460                                                SelectionDAG &DAG) const {
10461   EVT VT = N->getValueType(0);
10462   if (VT != MVT::i32 && VT != MVT::i64)
10463     return SDValue();
10464 
10465   unsigned Opc = N->getOpcode();
10466   SDValue Op0 = N->getOperand(0);
10467   SDValue Op1 = N->getOperand(1);
10468 
10469   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10470     return SDValue();
10471 
10472   if (Op0->isDivergent())
10473     std::swap(Op0, Op1);
10474 
10475   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10476     return SDValue();
10477 
10478   SDValue Op2 = Op1.getOperand(1);
10479   Op1 = Op1.getOperand(0);
10480   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10481     return SDValue();
10482 
10483   if (Op1->isDivergent())
10484     std::swap(Op1, Op2);
10485 
10486   // If either operand is constant this will conflict with
10487   // DAGCombiner::ReassociateOps().
10488   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10489       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10490     return SDValue();
10491 
10492   SDLoc SL(N);
10493   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10494   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10495 }
10496 
10497 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10498                            EVT VT,
10499                            SDValue N0, SDValue N1, SDValue N2,
10500                            bool Signed) {
10501   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10502   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10503   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10504   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10505 }
10506 
10507 SDValue SITargetLowering::performAddCombine(SDNode *N,
10508                                             DAGCombinerInfo &DCI) const {
10509   SelectionDAG &DAG = DCI.DAG;
10510   EVT VT = N->getValueType(0);
10511   SDLoc SL(N);
10512   SDValue LHS = N->getOperand(0);
10513   SDValue RHS = N->getOperand(1);
10514 
10515   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10516       && Subtarget->hasMad64_32() &&
10517       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10518       VT.getScalarSizeInBits() <= 64) {
10519     if (LHS.getOpcode() != ISD::MUL)
10520       std::swap(LHS, RHS);
10521 
10522     SDValue MulLHS = LHS.getOperand(0);
10523     SDValue MulRHS = LHS.getOperand(1);
10524     SDValue AddRHS = RHS;
10525 
10526     // TODO: Maybe restrict if SGPR inputs.
10527     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10528         numBitsUnsigned(MulRHS, DAG) <= 32) {
10529       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10530       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10531       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10532       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10533     }
10534 
10535     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10536       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10537       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10538       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10539       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10540     }
10541 
10542     return SDValue();
10543   }
10544 
10545   if (SDValue V = reassociateScalarOps(N, DAG)) {
10546     return V;
10547   }
10548 
10549   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10550     return SDValue();
10551 
10552   // add x, zext (setcc) => addcarry x, 0, setcc
10553   // add x, sext (setcc) => subcarry x, 0, setcc
10554   unsigned Opc = LHS.getOpcode();
10555   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10556       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10557     std::swap(RHS, LHS);
10558 
10559   Opc = RHS.getOpcode();
10560   switch (Opc) {
10561   default: break;
10562   case ISD::ZERO_EXTEND:
10563   case ISD::SIGN_EXTEND:
10564   case ISD::ANY_EXTEND: {
10565     auto Cond = RHS.getOperand(0);
10566     // If this won't be a real VOPC output, we would still need to insert an
10567     // extra instruction anyway.
10568     if (!isBoolSGPR(Cond))
10569       break;
10570     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10571     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10572     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10573     return DAG.getNode(Opc, SL, VTList, Args);
10574   }
10575   case ISD::ADDCARRY: {
10576     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10577     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10578     if (!C || C->getZExtValue() != 0) break;
10579     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10580     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10581   }
10582   }
10583   return SDValue();
10584 }
10585 
10586 SDValue SITargetLowering::performSubCombine(SDNode *N,
10587                                             DAGCombinerInfo &DCI) const {
10588   SelectionDAG &DAG = DCI.DAG;
10589   EVT VT = N->getValueType(0);
10590 
10591   if (VT != MVT::i32)
10592     return SDValue();
10593 
10594   SDLoc SL(N);
10595   SDValue LHS = N->getOperand(0);
10596   SDValue RHS = N->getOperand(1);
10597 
10598   // sub x, zext (setcc) => subcarry x, 0, setcc
10599   // sub x, sext (setcc) => addcarry x, 0, setcc
10600   unsigned Opc = RHS.getOpcode();
10601   switch (Opc) {
10602   default: break;
10603   case ISD::ZERO_EXTEND:
10604   case ISD::SIGN_EXTEND:
10605   case ISD::ANY_EXTEND: {
10606     auto Cond = RHS.getOperand(0);
10607     // If this won't be a real VOPC output, we would still need to insert an
10608     // extra instruction anyway.
10609     if (!isBoolSGPR(Cond))
10610       break;
10611     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10612     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10613     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10614     return DAG.getNode(Opc, SL, VTList, Args);
10615   }
10616   }
10617 
10618   if (LHS.getOpcode() == ISD::SUBCARRY) {
10619     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10620     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10621     if (!C || !C->isZero())
10622       return SDValue();
10623     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10624     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10625   }
10626   return SDValue();
10627 }
10628 
10629 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10630   DAGCombinerInfo &DCI) const {
10631 
10632   if (N->getValueType(0) != MVT::i32)
10633     return SDValue();
10634 
10635   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10636   if (!C || C->getZExtValue() != 0)
10637     return SDValue();
10638 
10639   SelectionDAG &DAG = DCI.DAG;
10640   SDValue LHS = N->getOperand(0);
10641 
10642   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10643   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10644   unsigned LHSOpc = LHS.getOpcode();
10645   unsigned Opc = N->getOpcode();
10646   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10647       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10648     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10649     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10650   }
10651   return SDValue();
10652 }
10653 
10654 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10655                                              DAGCombinerInfo &DCI) const {
10656   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10657     return SDValue();
10658 
10659   SelectionDAG &DAG = DCI.DAG;
10660   EVT VT = N->getValueType(0);
10661 
10662   SDLoc SL(N);
10663   SDValue LHS = N->getOperand(0);
10664   SDValue RHS = N->getOperand(1);
10665 
10666   // These should really be instruction patterns, but writing patterns with
10667   // source modiifiers is a pain.
10668 
10669   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10670   if (LHS.getOpcode() == ISD::FADD) {
10671     SDValue A = LHS.getOperand(0);
10672     if (A == LHS.getOperand(1)) {
10673       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10674       if (FusedOp != 0) {
10675         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10676         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10677       }
10678     }
10679   }
10680 
10681   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10682   if (RHS.getOpcode() == ISD::FADD) {
10683     SDValue A = RHS.getOperand(0);
10684     if (A == RHS.getOperand(1)) {
10685       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10686       if (FusedOp != 0) {
10687         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10688         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10689       }
10690     }
10691   }
10692 
10693   return SDValue();
10694 }
10695 
10696 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10697                                              DAGCombinerInfo &DCI) const {
10698   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10699     return SDValue();
10700 
10701   SelectionDAG &DAG = DCI.DAG;
10702   SDLoc SL(N);
10703   EVT VT = N->getValueType(0);
10704   assert(!VT.isVector());
10705 
10706   // Try to get the fneg to fold into the source modifier. This undoes generic
10707   // DAG combines and folds them into the mad.
10708   //
10709   // Only do this if we are not trying to support denormals. v_mad_f32 does
10710   // not support denormals ever.
10711   SDValue LHS = N->getOperand(0);
10712   SDValue RHS = N->getOperand(1);
10713   if (LHS.getOpcode() == ISD::FADD) {
10714     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10715     SDValue A = LHS.getOperand(0);
10716     if (A == LHS.getOperand(1)) {
10717       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10718       if (FusedOp != 0){
10719         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10720         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10721 
10722         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10723       }
10724     }
10725   }
10726 
10727   if (RHS.getOpcode() == ISD::FADD) {
10728     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10729 
10730     SDValue A = RHS.getOperand(0);
10731     if (A == RHS.getOperand(1)) {
10732       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10733       if (FusedOp != 0){
10734         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10735         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10736       }
10737     }
10738   }
10739 
10740   return SDValue();
10741 }
10742 
10743 SDValue SITargetLowering::performFMACombine(SDNode *N,
10744                                             DAGCombinerInfo &DCI) const {
10745   SelectionDAG &DAG = DCI.DAG;
10746   EVT VT = N->getValueType(0);
10747   SDLoc SL(N);
10748 
10749   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10750     return SDValue();
10751 
10752   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10753   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10754   SDValue Op1 = N->getOperand(0);
10755   SDValue Op2 = N->getOperand(1);
10756   SDValue FMA = N->getOperand(2);
10757 
10758   if (FMA.getOpcode() != ISD::FMA ||
10759       Op1.getOpcode() != ISD::FP_EXTEND ||
10760       Op2.getOpcode() != ISD::FP_EXTEND)
10761     return SDValue();
10762 
10763   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10764   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10765   // is sufficient to allow generaing fdot2.
10766   const TargetOptions &Options = DAG.getTarget().Options;
10767   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10768       (N->getFlags().hasAllowContract() &&
10769        FMA->getFlags().hasAllowContract())) {
10770     Op1 = Op1.getOperand(0);
10771     Op2 = Op2.getOperand(0);
10772     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10773         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10774       return SDValue();
10775 
10776     SDValue Vec1 = Op1.getOperand(0);
10777     SDValue Idx1 = Op1.getOperand(1);
10778     SDValue Vec2 = Op2.getOperand(0);
10779 
10780     SDValue FMAOp1 = FMA.getOperand(0);
10781     SDValue FMAOp2 = FMA.getOperand(1);
10782     SDValue FMAAcc = FMA.getOperand(2);
10783 
10784     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10785         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10786       return SDValue();
10787 
10788     FMAOp1 = FMAOp1.getOperand(0);
10789     FMAOp2 = FMAOp2.getOperand(0);
10790     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10791         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10792       return SDValue();
10793 
10794     SDValue Vec3 = FMAOp1.getOperand(0);
10795     SDValue Vec4 = FMAOp2.getOperand(0);
10796     SDValue Idx2 = FMAOp1.getOperand(1);
10797 
10798     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10799         // Idx1 and Idx2 cannot be the same.
10800         Idx1 == Idx2)
10801       return SDValue();
10802 
10803     if (Vec1 == Vec2 || Vec3 == Vec4)
10804       return SDValue();
10805 
10806     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10807       return SDValue();
10808 
10809     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10810         (Vec1 == Vec4 && Vec2 == Vec3)) {
10811       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10812                          DAG.getTargetConstant(0, SL, MVT::i1));
10813     }
10814   }
10815   return SDValue();
10816 }
10817 
10818 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10819                                               DAGCombinerInfo &DCI) const {
10820   SelectionDAG &DAG = DCI.DAG;
10821   SDLoc SL(N);
10822 
10823   SDValue LHS = N->getOperand(0);
10824   SDValue RHS = N->getOperand(1);
10825   EVT VT = LHS.getValueType();
10826   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10827 
10828   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10829   if (!CRHS) {
10830     CRHS = dyn_cast<ConstantSDNode>(LHS);
10831     if (CRHS) {
10832       std::swap(LHS, RHS);
10833       CC = getSetCCSwappedOperands(CC);
10834     }
10835   }
10836 
10837   if (CRHS) {
10838     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10839         isBoolSGPR(LHS.getOperand(0))) {
10840       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10841       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10842       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10843       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10844       if ((CRHS->isAllOnes() &&
10845            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10846           (CRHS->isZero() &&
10847            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10848         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10849                            DAG.getConstant(-1, SL, MVT::i1));
10850       if ((CRHS->isAllOnes() &&
10851            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10852           (CRHS->isZero() &&
10853            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10854         return LHS.getOperand(0);
10855     }
10856 
10857     const APInt &CRHSVal = CRHS->getAPIntValue();
10858     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10859         LHS.getOpcode() == ISD::SELECT &&
10860         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10861         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10862         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10863         isBoolSGPR(LHS.getOperand(0))) {
10864       // Given CT != FT:
10865       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10866       // setcc (select cc, CT, CF), CF, ne => cc
10867       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10868       // setcc (select cc, CT, CF), CT, eq => cc
10869       const APInt &CT = LHS.getConstantOperandAPInt(1);
10870       const APInt &CF = LHS.getConstantOperandAPInt(2);
10871 
10872       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10873           (CT == CRHSVal && CC == ISD::SETNE))
10874         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10875                            DAG.getConstant(-1, SL, MVT::i1));
10876       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10877           (CT == CRHSVal && CC == ISD::SETEQ))
10878         return LHS.getOperand(0);
10879     }
10880   }
10881 
10882   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10883                                            VT != MVT::f16))
10884     return SDValue();
10885 
10886   // Match isinf/isfinite pattern
10887   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10888   // (fcmp one (fabs x), inf) -> (fp_class x,
10889   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10890   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10891     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10892     if (!CRHS)
10893       return SDValue();
10894 
10895     const APFloat &APF = CRHS->getValueAPF();
10896     if (APF.isInfinity() && !APF.isNegative()) {
10897       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10898                                  SIInstrFlags::N_INFINITY;
10899       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10900                                     SIInstrFlags::P_ZERO |
10901                                     SIInstrFlags::N_NORMAL |
10902                                     SIInstrFlags::P_NORMAL |
10903                                     SIInstrFlags::N_SUBNORMAL |
10904                                     SIInstrFlags::P_SUBNORMAL;
10905       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10906       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10907                          DAG.getConstant(Mask, SL, MVT::i32));
10908     }
10909   }
10910 
10911   return SDValue();
10912 }
10913 
10914 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10915                                                      DAGCombinerInfo &DCI) const {
10916   SelectionDAG &DAG = DCI.DAG;
10917   SDLoc SL(N);
10918   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10919 
10920   SDValue Src = N->getOperand(0);
10921   SDValue Shift = N->getOperand(0);
10922 
10923   // TODO: Extend type shouldn't matter (assuming legal types).
10924   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10925     Shift = Shift.getOperand(0);
10926 
10927   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10928     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10929     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10930     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10931     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10932     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10933     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10934       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
10935                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10936 
10937       unsigned ShiftOffset = 8 * Offset;
10938       if (Shift.getOpcode() == ISD::SHL)
10939         ShiftOffset -= C->getZExtValue();
10940       else
10941         ShiftOffset += C->getZExtValue();
10942 
10943       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10944         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10945                            MVT::f32, Shifted);
10946       }
10947     }
10948   }
10949 
10950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10951   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10952   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10953     // We simplified Src. If this node is not dead, visit it again so it is
10954     // folded properly.
10955     if (N->getOpcode() != ISD::DELETED_NODE)
10956       DCI.AddToWorklist(N);
10957     return SDValue(N, 0);
10958   }
10959 
10960   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10961   if (SDValue DemandedSrc =
10962           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10963     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10964 
10965   return SDValue();
10966 }
10967 
10968 SDValue SITargetLowering::performClampCombine(SDNode *N,
10969                                               DAGCombinerInfo &DCI) const {
10970   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10971   if (!CSrc)
10972     return SDValue();
10973 
10974   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10975   const APFloat &F = CSrc->getValueAPF();
10976   APFloat Zero = APFloat::getZero(F.getSemantics());
10977   if (F < Zero ||
10978       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10979     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10980   }
10981 
10982   APFloat One(F.getSemantics(), "1.0");
10983   if (F > One)
10984     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10985 
10986   return SDValue(CSrc, 0);
10987 }
10988 
10989 
10990 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10991                                             DAGCombinerInfo &DCI) const {
10992   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10993     return SDValue();
10994   switch (N->getOpcode()) {
10995   case ISD::ADD:
10996     return performAddCombine(N, DCI);
10997   case ISD::SUB:
10998     return performSubCombine(N, DCI);
10999   case ISD::ADDCARRY:
11000   case ISD::SUBCARRY:
11001     return performAddCarrySubCarryCombine(N, DCI);
11002   case ISD::FADD:
11003     return performFAddCombine(N, DCI);
11004   case ISD::FSUB:
11005     return performFSubCombine(N, DCI);
11006   case ISD::SETCC:
11007     return performSetCCCombine(N, DCI);
11008   case ISD::FMAXNUM:
11009   case ISD::FMINNUM:
11010   case ISD::FMAXNUM_IEEE:
11011   case ISD::FMINNUM_IEEE:
11012   case ISD::SMAX:
11013   case ISD::SMIN:
11014   case ISD::UMAX:
11015   case ISD::UMIN:
11016   case AMDGPUISD::FMIN_LEGACY:
11017   case AMDGPUISD::FMAX_LEGACY:
11018     return performMinMaxCombine(N, DCI);
11019   case ISD::FMA:
11020     return performFMACombine(N, DCI);
11021   case ISD::AND:
11022     return performAndCombine(N, DCI);
11023   case ISD::OR:
11024     return performOrCombine(N, DCI);
11025   case ISD::XOR:
11026     return performXorCombine(N, DCI);
11027   case ISD::ZERO_EXTEND:
11028     return performZeroExtendCombine(N, DCI);
11029   case ISD::SIGN_EXTEND_INREG:
11030     return performSignExtendInRegCombine(N , DCI);
11031   case AMDGPUISD::FP_CLASS:
11032     return performClassCombine(N, DCI);
11033   case ISD::FCANONICALIZE:
11034     return performFCanonicalizeCombine(N, DCI);
11035   case AMDGPUISD::RCP:
11036     return performRcpCombine(N, DCI);
11037   case AMDGPUISD::FRACT:
11038   case AMDGPUISD::RSQ:
11039   case AMDGPUISD::RCP_LEGACY:
11040   case AMDGPUISD::RCP_IFLAG:
11041   case AMDGPUISD::RSQ_CLAMP:
11042   case AMDGPUISD::LDEXP: {
11043     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11044     SDValue Src = N->getOperand(0);
11045     if (Src.isUndef())
11046       return Src;
11047     break;
11048   }
11049   case ISD::SINT_TO_FP:
11050   case ISD::UINT_TO_FP:
11051     return performUCharToFloatCombine(N, DCI);
11052   case AMDGPUISD::CVT_F32_UBYTE0:
11053   case AMDGPUISD::CVT_F32_UBYTE1:
11054   case AMDGPUISD::CVT_F32_UBYTE2:
11055   case AMDGPUISD::CVT_F32_UBYTE3:
11056     return performCvtF32UByteNCombine(N, DCI);
11057   case AMDGPUISD::FMED3:
11058     return performFMed3Combine(N, DCI);
11059   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11060     return performCvtPkRTZCombine(N, DCI);
11061   case AMDGPUISD::CLAMP:
11062     return performClampCombine(N, DCI);
11063   case ISD::SCALAR_TO_VECTOR: {
11064     SelectionDAG &DAG = DCI.DAG;
11065     EVT VT = N->getValueType(0);
11066 
11067     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11068     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11069       SDLoc SL(N);
11070       SDValue Src = N->getOperand(0);
11071       EVT EltVT = Src.getValueType();
11072       if (EltVT == MVT::f16)
11073         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11074 
11075       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11076       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11077     }
11078 
11079     break;
11080   }
11081   case ISD::EXTRACT_VECTOR_ELT:
11082     return performExtractVectorEltCombine(N, DCI);
11083   case ISD::INSERT_VECTOR_ELT:
11084     return performInsertVectorEltCombine(N, DCI);
11085   case ISD::LOAD: {
11086     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11087       return Widended;
11088     LLVM_FALLTHROUGH;
11089   }
11090   default: {
11091     if (!DCI.isBeforeLegalize()) {
11092       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11093         return performMemSDNodeCombine(MemNode, DCI);
11094     }
11095 
11096     break;
11097   }
11098   }
11099 
11100   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11101 }
11102 
11103 /// Helper function for adjustWritemask
11104 static unsigned SubIdx2Lane(unsigned Idx) {
11105   switch (Idx) {
11106   default: return ~0u;
11107   case AMDGPU::sub0: return 0;
11108   case AMDGPU::sub1: return 1;
11109   case AMDGPU::sub2: return 2;
11110   case AMDGPU::sub3: return 3;
11111   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11112   }
11113 }
11114 
11115 /// Adjust the writemask of MIMG instructions
11116 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11117                                           SelectionDAG &DAG) const {
11118   unsigned Opcode = Node->getMachineOpcode();
11119 
11120   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11121   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11122   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11123     return Node; // not implemented for D16
11124 
11125   SDNode *Users[5] = { nullptr };
11126   unsigned Lane = 0;
11127   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11128   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11129   unsigned NewDmask = 0;
11130   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11131   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11132   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11133                   Node->getConstantOperandVal(LWEIdx))
11134                      ? true
11135                      : false;
11136   unsigned TFCLane = 0;
11137   bool HasChain = Node->getNumValues() > 1;
11138 
11139   if (OldDmask == 0) {
11140     // These are folded out, but on the chance it happens don't assert.
11141     return Node;
11142   }
11143 
11144   unsigned OldBitsSet = countPopulation(OldDmask);
11145   // Work out which is the TFE/LWE lane if that is enabled.
11146   if (UsesTFC) {
11147     TFCLane = OldBitsSet;
11148   }
11149 
11150   // Try to figure out the used register components
11151   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11152        I != E; ++I) {
11153 
11154     // Don't look at users of the chain.
11155     if (I.getUse().getResNo() != 0)
11156       continue;
11157 
11158     // Abort if we can't understand the usage
11159     if (!I->isMachineOpcode() ||
11160         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11161       return Node;
11162 
11163     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11164     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11165     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11166     // set, etc.
11167     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11168     if (Lane == ~0u)
11169       return Node;
11170 
11171     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11172     if (UsesTFC && Lane == TFCLane) {
11173       Users[Lane] = *I;
11174     } else {
11175       // Set which texture component corresponds to the lane.
11176       unsigned Comp;
11177       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11178         Comp = countTrailingZeros(Dmask);
11179         Dmask &= ~(1 << Comp);
11180       }
11181 
11182       // Abort if we have more than one user per component.
11183       if (Users[Lane])
11184         return Node;
11185 
11186       Users[Lane] = *I;
11187       NewDmask |= 1 << Comp;
11188     }
11189   }
11190 
11191   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11192   bool NoChannels = !NewDmask;
11193   if (NoChannels) {
11194     if (!UsesTFC) {
11195       // No uses of the result and not using TFC. Then do nothing.
11196       return Node;
11197     }
11198     // If the original dmask has one channel - then nothing to do
11199     if (OldBitsSet == 1)
11200       return Node;
11201     // Use an arbitrary dmask - required for the instruction to work
11202     NewDmask = 1;
11203   }
11204   // Abort if there's no change
11205   if (NewDmask == OldDmask)
11206     return Node;
11207 
11208   unsigned BitsSet = countPopulation(NewDmask);
11209 
11210   // Check for TFE or LWE - increase the number of channels by one to account
11211   // for the extra return value
11212   // This will need adjustment for D16 if this is also included in
11213   // adjustWriteMask (this function) but at present D16 are excluded.
11214   unsigned NewChannels = BitsSet + UsesTFC;
11215 
11216   int NewOpcode =
11217       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11218   assert(NewOpcode != -1 &&
11219          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11220          "failed to find equivalent MIMG op");
11221 
11222   // Adjust the writemask in the node
11223   SmallVector<SDValue, 12> Ops;
11224   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11225   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11226   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11227 
11228   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11229 
11230   MVT ResultVT = NewChannels == 1 ?
11231     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11232                            NewChannels == 5 ? 8 : NewChannels);
11233   SDVTList NewVTList = HasChain ?
11234     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11235 
11236 
11237   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11238                                               NewVTList, Ops);
11239 
11240   if (HasChain) {
11241     // Update chain.
11242     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11243     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11244   }
11245 
11246   if (NewChannels == 1) {
11247     assert(Node->hasNUsesOfValue(1, 0));
11248     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11249                                       SDLoc(Node), Users[Lane]->getValueType(0),
11250                                       SDValue(NewNode, 0));
11251     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11252     return nullptr;
11253   }
11254 
11255   // Update the users of the node with the new indices
11256   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11257     SDNode *User = Users[i];
11258     if (!User) {
11259       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11260       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11261       if (i || !NoChannels)
11262         continue;
11263     } else {
11264       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11265       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11266     }
11267 
11268     switch (Idx) {
11269     default: break;
11270     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11271     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11272     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11273     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11274     }
11275   }
11276 
11277   DAG.RemoveDeadNode(Node);
11278   return nullptr;
11279 }
11280 
11281 static bool isFrameIndexOp(SDValue Op) {
11282   if (Op.getOpcode() == ISD::AssertZext)
11283     Op = Op.getOperand(0);
11284 
11285   return isa<FrameIndexSDNode>(Op);
11286 }
11287 
11288 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11289 /// with frame index operands.
11290 /// LLVM assumes that inputs are to these instructions are registers.
11291 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11292                                                         SelectionDAG &DAG) const {
11293   if (Node->getOpcode() == ISD::CopyToReg) {
11294     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11295     SDValue SrcVal = Node->getOperand(2);
11296 
11297     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11298     // to try understanding copies to physical registers.
11299     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11300       SDLoc SL(Node);
11301       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11302       SDValue VReg = DAG.getRegister(
11303         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11304 
11305       SDNode *Glued = Node->getGluedNode();
11306       SDValue ToVReg
11307         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11308                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11309       SDValue ToResultReg
11310         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11311                            VReg, ToVReg.getValue(1));
11312       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11313       DAG.RemoveDeadNode(Node);
11314       return ToResultReg.getNode();
11315     }
11316   }
11317 
11318   SmallVector<SDValue, 8> Ops;
11319   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11320     if (!isFrameIndexOp(Node->getOperand(i))) {
11321       Ops.push_back(Node->getOperand(i));
11322       continue;
11323     }
11324 
11325     SDLoc DL(Node);
11326     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11327                                      Node->getOperand(i).getValueType(),
11328                                      Node->getOperand(i)), 0));
11329   }
11330 
11331   return DAG.UpdateNodeOperands(Node, Ops);
11332 }
11333 
11334 /// Fold the instructions after selecting them.
11335 /// Returns null if users were already updated.
11336 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11337                                           SelectionDAG &DAG) const {
11338   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11339   unsigned Opcode = Node->getMachineOpcode();
11340 
11341   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11342       !TII->isGather4(Opcode) &&
11343       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11344     return adjustWritemask(Node, DAG);
11345   }
11346 
11347   if (Opcode == AMDGPU::INSERT_SUBREG ||
11348       Opcode == AMDGPU::REG_SEQUENCE) {
11349     legalizeTargetIndependentNode(Node, DAG);
11350     return Node;
11351   }
11352 
11353   switch (Opcode) {
11354   case AMDGPU::V_DIV_SCALE_F32_e64:
11355   case AMDGPU::V_DIV_SCALE_F64_e64: {
11356     // Satisfy the operand register constraint when one of the inputs is
11357     // undefined. Ordinarily each undef value will have its own implicit_def of
11358     // a vreg, so force these to use a single register.
11359     SDValue Src0 = Node->getOperand(1);
11360     SDValue Src1 = Node->getOperand(3);
11361     SDValue Src2 = Node->getOperand(5);
11362 
11363     if ((Src0.isMachineOpcode() &&
11364          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11365         (Src0 == Src1 || Src0 == Src2))
11366       break;
11367 
11368     MVT VT = Src0.getValueType().getSimpleVT();
11369     const TargetRegisterClass *RC =
11370         getRegClassFor(VT, Src0.getNode()->isDivergent());
11371 
11372     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11373     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11374 
11375     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11376                                       UndefReg, Src0, SDValue());
11377 
11378     // src0 must be the same register as src1 or src2, even if the value is
11379     // undefined, so make sure we don't violate this constraint.
11380     if (Src0.isMachineOpcode() &&
11381         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11382       if (Src1.isMachineOpcode() &&
11383           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11384         Src0 = Src1;
11385       else if (Src2.isMachineOpcode() &&
11386                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11387         Src0 = Src2;
11388       else {
11389         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11390         Src0 = UndefReg;
11391         Src1 = UndefReg;
11392       }
11393     } else
11394       break;
11395 
11396     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11397     Ops[1] = Src0;
11398     Ops[3] = Src1;
11399     Ops[5] = Src2;
11400     Ops.push_back(ImpDef.getValue(1));
11401     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11402   }
11403   default:
11404     break;
11405   }
11406 
11407   return Node;
11408 }
11409 
11410 // Any MIMG instructions that use tfe or lwe require an initialization of the
11411 // result register that will be written in the case of a memory access failure.
11412 // The required code is also added to tie this init code to the result of the
11413 // img instruction.
11414 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11415   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11416   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11417   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11418   MachineBasicBlock &MBB = *MI.getParent();
11419 
11420   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11421   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11422   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11423 
11424   if (!TFE && !LWE) // intersect_ray
11425     return;
11426 
11427   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11428   unsigned LWEVal = LWE->getImm();
11429   unsigned D16Val = D16 ? D16->getImm() : 0;
11430 
11431   if (!TFEVal && !LWEVal)
11432     return;
11433 
11434   // At least one of TFE or LWE are non-zero
11435   // We have to insert a suitable initialization of the result value and
11436   // tie this to the dest of the image instruction.
11437 
11438   const DebugLoc &DL = MI.getDebugLoc();
11439 
11440   int DstIdx =
11441       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11442 
11443   // Calculate which dword we have to initialize to 0.
11444   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11445 
11446   // check that dmask operand is found.
11447   assert(MO_Dmask && "Expected dmask operand in instruction");
11448 
11449   unsigned dmask = MO_Dmask->getImm();
11450   // Determine the number of active lanes taking into account the
11451   // Gather4 special case
11452   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11453 
11454   bool Packed = !Subtarget->hasUnpackedD16VMem();
11455 
11456   unsigned InitIdx =
11457       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11458 
11459   // Abandon attempt if the dst size isn't large enough
11460   // - this is in fact an error but this is picked up elsewhere and
11461   // reported correctly.
11462   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11463   if (DstSize < InitIdx)
11464     return;
11465 
11466   // Create a register for the intialization value.
11467   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11468   unsigned NewDst = 0; // Final initialized value will be in here
11469 
11470   // If PRTStrictNull feature is enabled (the default) then initialize
11471   // all the result registers to 0, otherwise just the error indication
11472   // register (VGPRn+1)
11473   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11474   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11475 
11476   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11477   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11478     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11479     // Initialize dword
11480     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11481     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11482       .addImm(0);
11483     // Insert into the super-reg
11484     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11485       .addReg(PrevDst)
11486       .addReg(SubReg)
11487       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11488 
11489     PrevDst = NewDst;
11490   }
11491 
11492   // Add as an implicit operand
11493   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11494 
11495   // Tie the just added implicit operand to the dst
11496   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11497 }
11498 
11499 /// Assign the register class depending on the number of
11500 /// bits set in the writemask
11501 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11502                                                      SDNode *Node) const {
11503   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11504 
11505   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11506 
11507   if (TII->isVOP3(MI.getOpcode())) {
11508     // Make sure constant bus requirements are respected.
11509     TII->legalizeOperandsVOP3(MRI, MI);
11510 
11511     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11512     // This saves a chain-copy of registers and better ballance register
11513     // use between vgpr and agpr as agpr tuples tend to be big.
11514     if (MI.getDesc().OpInfo) {
11515       unsigned Opc = MI.getOpcode();
11516       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11517       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11518                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11519         if (I == -1)
11520           break;
11521         MachineOperand &Op = MI.getOperand(I);
11522         if (!Op.isReg() || !Op.getReg().isVirtual())
11523           continue;
11524         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11525         if (!TRI->hasAGPRs(RC))
11526           continue;
11527         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11528         if (!Src || !Src->isCopy() ||
11529             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11530           continue;
11531         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11532         // All uses of agpr64 and agpr32 can also accept vgpr except for
11533         // v_accvgpr_read, but we do not produce agpr reads during selection,
11534         // so no use checks are needed.
11535         MRI.setRegClass(Op.getReg(), NewRC);
11536       }
11537     }
11538 
11539     return;
11540   }
11541 
11542   // Replace unused atomics with the no return version.
11543   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11544   if (NoRetAtomicOp != -1) {
11545     if (!Node->hasAnyUseOfValue(0)) {
11546       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11547                                                AMDGPU::OpName::cpol);
11548       if (CPolIdx != -1) {
11549         MachineOperand &CPol = MI.getOperand(CPolIdx);
11550         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11551       }
11552       MI.RemoveOperand(0);
11553       MI.setDesc(TII->get(NoRetAtomicOp));
11554       return;
11555     }
11556 
11557     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11558     // instruction, because the return type of these instructions is a vec2 of
11559     // the memory type, so it can be tied to the input operand.
11560     // This means these instructions always have a use, so we need to add a
11561     // special case to check if the atomic has only one extract_subreg use,
11562     // which itself has no uses.
11563     if ((Node->hasNUsesOfValue(1, 0) &&
11564          Node->use_begin()->isMachineOpcode() &&
11565          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11566          !Node->use_begin()->hasAnyUseOfValue(0))) {
11567       Register Def = MI.getOperand(0).getReg();
11568 
11569       // Change this into a noret atomic.
11570       MI.setDesc(TII->get(NoRetAtomicOp));
11571       MI.RemoveOperand(0);
11572 
11573       // If we only remove the def operand from the atomic instruction, the
11574       // extract_subreg will be left with a use of a vreg without a def.
11575       // So we need to insert an implicit_def to avoid machine verifier
11576       // errors.
11577       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11578               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11579     }
11580     return;
11581   }
11582 
11583   if (TII->isMIMG(MI) && !MI.mayStore())
11584     AddIMGInit(MI);
11585 }
11586 
11587 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11588                               uint64_t Val) {
11589   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11590   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11591 }
11592 
11593 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11594                                                 const SDLoc &DL,
11595                                                 SDValue Ptr) const {
11596   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11597 
11598   // Build the half of the subregister with the constants before building the
11599   // full 128-bit register. If we are building multiple resource descriptors,
11600   // this will allow CSEing of the 2-component register.
11601   const SDValue Ops0[] = {
11602     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11603     buildSMovImm32(DAG, DL, 0),
11604     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11605     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11606     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11607   };
11608 
11609   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11610                                                 MVT::v2i32, Ops0), 0);
11611 
11612   // Combine the constants and the pointer.
11613   const SDValue Ops1[] = {
11614     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11615     Ptr,
11616     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11617     SubRegHi,
11618     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11619   };
11620 
11621   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11622 }
11623 
11624 /// Return a resource descriptor with the 'Add TID' bit enabled
11625 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11626 ///        of the resource descriptor) to create an offset, which is added to
11627 ///        the resource pointer.
11628 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11629                                            SDValue Ptr, uint32_t RsrcDword1,
11630                                            uint64_t RsrcDword2And3) const {
11631   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11632   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11633   if (RsrcDword1) {
11634     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11635                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11636                     0);
11637   }
11638 
11639   SDValue DataLo = buildSMovImm32(DAG, DL,
11640                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11641   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11642 
11643   const SDValue Ops[] = {
11644     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11645     PtrLo,
11646     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11647     PtrHi,
11648     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11649     DataLo,
11650     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11651     DataHi,
11652     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11653   };
11654 
11655   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11656 }
11657 
11658 //===----------------------------------------------------------------------===//
11659 //                         SI Inline Assembly Support
11660 //===----------------------------------------------------------------------===//
11661 
11662 std::pair<unsigned, const TargetRegisterClass *>
11663 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11664                                                StringRef Constraint,
11665                                                MVT VT) const {
11666   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11667 
11668   const TargetRegisterClass *RC = nullptr;
11669   if (Constraint.size() == 1) {
11670     const unsigned BitWidth = VT.getSizeInBits();
11671     switch (Constraint[0]) {
11672     default:
11673       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11674     case 's':
11675     case 'r':
11676       switch (BitWidth) {
11677       case 16:
11678         RC = &AMDGPU::SReg_32RegClass;
11679         break;
11680       case 64:
11681         RC = &AMDGPU::SGPR_64RegClass;
11682         break;
11683       default:
11684         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11685         if (!RC)
11686           return std::make_pair(0U, nullptr);
11687         break;
11688       }
11689       break;
11690     case 'v':
11691       switch (BitWidth) {
11692       case 16:
11693         RC = &AMDGPU::VGPR_32RegClass;
11694         break;
11695       default:
11696         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11697         if (!RC)
11698           return std::make_pair(0U, nullptr);
11699         break;
11700       }
11701       break;
11702     case 'a':
11703       if (!Subtarget->hasMAIInsts())
11704         break;
11705       switch (BitWidth) {
11706       case 16:
11707         RC = &AMDGPU::AGPR_32RegClass;
11708         break;
11709       default:
11710         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11711         if (!RC)
11712           return std::make_pair(0U, nullptr);
11713         break;
11714       }
11715       break;
11716     }
11717     // We actually support i128, i16 and f16 as inline parameters
11718     // even if they are not reported as legal
11719     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11720                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11721       return std::make_pair(0U, RC);
11722   }
11723 
11724   if (Constraint.size() > 1) {
11725     if (Constraint[1] == 'v') {
11726       RC = &AMDGPU::VGPR_32RegClass;
11727     } else if (Constraint[1] == 's') {
11728       RC = &AMDGPU::SGPR_32RegClass;
11729     } else if (Constraint[1] == 'a') {
11730       RC = &AMDGPU::AGPR_32RegClass;
11731     }
11732 
11733     if (RC) {
11734       uint32_t Idx;
11735       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11736       if (!Failed && Idx < RC->getNumRegs())
11737         return std::make_pair(RC->getRegister(Idx), RC);
11738     }
11739   }
11740 
11741   // FIXME: Returns VS_32 for physical SGPR constraints
11742   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11743 }
11744 
11745 static bool isImmConstraint(StringRef Constraint) {
11746   if (Constraint.size() == 1) {
11747     switch (Constraint[0]) {
11748     default: break;
11749     case 'I':
11750     case 'J':
11751     case 'A':
11752     case 'B':
11753     case 'C':
11754       return true;
11755     }
11756   } else if (Constraint == "DA" ||
11757              Constraint == "DB") {
11758     return true;
11759   }
11760   return false;
11761 }
11762 
11763 SITargetLowering::ConstraintType
11764 SITargetLowering::getConstraintType(StringRef Constraint) const {
11765   if (Constraint.size() == 1) {
11766     switch (Constraint[0]) {
11767     default: break;
11768     case 's':
11769     case 'v':
11770     case 'a':
11771       return C_RegisterClass;
11772     }
11773   }
11774   if (isImmConstraint(Constraint)) {
11775     return C_Other;
11776   }
11777   return TargetLowering::getConstraintType(Constraint);
11778 }
11779 
11780 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11781   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11782     Val = Val & maskTrailingOnes<uint64_t>(Size);
11783   }
11784   return Val;
11785 }
11786 
11787 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11788                                                     std::string &Constraint,
11789                                                     std::vector<SDValue> &Ops,
11790                                                     SelectionDAG &DAG) const {
11791   if (isImmConstraint(Constraint)) {
11792     uint64_t Val;
11793     if (getAsmOperandConstVal(Op, Val) &&
11794         checkAsmConstraintVal(Op, Constraint, Val)) {
11795       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11796       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11797     }
11798   } else {
11799     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11800   }
11801 }
11802 
11803 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11804   unsigned Size = Op.getScalarValueSizeInBits();
11805   if (Size > 64)
11806     return false;
11807 
11808   if (Size == 16 && !Subtarget->has16BitInsts())
11809     return false;
11810 
11811   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11812     Val = C->getSExtValue();
11813     return true;
11814   }
11815   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11816     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11817     return true;
11818   }
11819   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11820     if (Size != 16 || Op.getNumOperands() != 2)
11821       return false;
11822     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11823       return false;
11824     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11825       Val = C->getSExtValue();
11826       return true;
11827     }
11828     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11829       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11830       return true;
11831     }
11832   }
11833 
11834   return false;
11835 }
11836 
11837 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11838                                              const std::string &Constraint,
11839                                              uint64_t Val) const {
11840   if (Constraint.size() == 1) {
11841     switch (Constraint[0]) {
11842     case 'I':
11843       return AMDGPU::isInlinableIntLiteral(Val);
11844     case 'J':
11845       return isInt<16>(Val);
11846     case 'A':
11847       return checkAsmConstraintValA(Op, Val);
11848     case 'B':
11849       return isInt<32>(Val);
11850     case 'C':
11851       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11852              AMDGPU::isInlinableIntLiteral(Val);
11853     default:
11854       break;
11855     }
11856   } else if (Constraint.size() == 2) {
11857     if (Constraint == "DA") {
11858       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11859       int64_t LoBits = static_cast<int32_t>(Val);
11860       return checkAsmConstraintValA(Op, HiBits, 32) &&
11861              checkAsmConstraintValA(Op, LoBits, 32);
11862     }
11863     if (Constraint == "DB") {
11864       return true;
11865     }
11866   }
11867   llvm_unreachable("Invalid asm constraint");
11868 }
11869 
11870 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11871                                               uint64_t Val,
11872                                               unsigned MaxSize) const {
11873   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11874   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11875   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11876       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11877       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11878     return true;
11879   }
11880   return false;
11881 }
11882 
11883 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11884   switch (UnalignedClassID) {
11885   case AMDGPU::VReg_64RegClassID:
11886     return AMDGPU::VReg_64_Align2RegClassID;
11887   case AMDGPU::VReg_96RegClassID:
11888     return AMDGPU::VReg_96_Align2RegClassID;
11889   case AMDGPU::VReg_128RegClassID:
11890     return AMDGPU::VReg_128_Align2RegClassID;
11891   case AMDGPU::VReg_160RegClassID:
11892     return AMDGPU::VReg_160_Align2RegClassID;
11893   case AMDGPU::VReg_192RegClassID:
11894     return AMDGPU::VReg_192_Align2RegClassID;
11895   case AMDGPU::VReg_224RegClassID:
11896     return AMDGPU::VReg_224_Align2RegClassID;
11897   case AMDGPU::VReg_256RegClassID:
11898     return AMDGPU::VReg_256_Align2RegClassID;
11899   case AMDGPU::VReg_512RegClassID:
11900     return AMDGPU::VReg_512_Align2RegClassID;
11901   case AMDGPU::VReg_1024RegClassID:
11902     return AMDGPU::VReg_1024_Align2RegClassID;
11903   case AMDGPU::AReg_64RegClassID:
11904     return AMDGPU::AReg_64_Align2RegClassID;
11905   case AMDGPU::AReg_96RegClassID:
11906     return AMDGPU::AReg_96_Align2RegClassID;
11907   case AMDGPU::AReg_128RegClassID:
11908     return AMDGPU::AReg_128_Align2RegClassID;
11909   case AMDGPU::AReg_160RegClassID:
11910     return AMDGPU::AReg_160_Align2RegClassID;
11911   case AMDGPU::AReg_192RegClassID:
11912     return AMDGPU::AReg_192_Align2RegClassID;
11913   case AMDGPU::AReg_256RegClassID:
11914     return AMDGPU::AReg_256_Align2RegClassID;
11915   case AMDGPU::AReg_512RegClassID:
11916     return AMDGPU::AReg_512_Align2RegClassID;
11917   case AMDGPU::AReg_1024RegClassID:
11918     return AMDGPU::AReg_1024_Align2RegClassID;
11919   default:
11920     return -1;
11921   }
11922 }
11923 
11924 // Figure out which registers should be reserved for stack access. Only after
11925 // the function is legalized do we know all of the non-spill stack objects or if
11926 // calls are present.
11927 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11928   MachineRegisterInfo &MRI = MF.getRegInfo();
11929   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11930   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11931   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11932   const SIInstrInfo *TII = ST.getInstrInfo();
11933 
11934   if (Info->isEntryFunction()) {
11935     // Callable functions have fixed registers used for stack access.
11936     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11937   }
11938 
11939   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11940                              Info->getStackPtrOffsetReg()));
11941   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11942     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11943 
11944   // We need to worry about replacing the default register with itself in case
11945   // of MIR testcases missing the MFI.
11946   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11947     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11948 
11949   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11950     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11951 
11952   Info->limitOccupancy(MF);
11953 
11954   if (ST.isWave32() && !MF.empty()) {
11955     for (auto &MBB : MF) {
11956       for (auto &MI : MBB) {
11957         TII->fixImplicitOperands(MI);
11958       }
11959     }
11960   }
11961 
11962   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11963   // classes if required. Ideally the register class constraints would differ
11964   // per-subtarget, but there's no easy way to achieve that right now. This is
11965   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11966   // from using them as the register class for legal types.
11967   if (ST.needsAlignedVGPRs()) {
11968     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11969       const Register Reg = Register::index2VirtReg(I);
11970       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11971       if (!RC)
11972         continue;
11973       int NewClassID = getAlignedAGPRClassID(RC->getID());
11974       if (NewClassID != -1)
11975         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11976     }
11977   }
11978 
11979   TargetLoweringBase::finalizeLowering(MF);
11980 
11981   // Allocate a VGPR for future SGPR Spill if
11982   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11983   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11984   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11985       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11986     Info->reserveVGPRforSGPRSpills(MF);
11987 }
11988 
11989 void SITargetLowering::computeKnownBitsForFrameIndex(
11990   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11991   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11992 
11993   // Set the high bits to zero based on the maximum allowed scratch size per
11994   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11995   // calculation won't overflow, so assume the sign bit is never set.
11996   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11997 }
11998 
11999 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12000                                    KnownBits &Known, unsigned Dim) {
12001   unsigned MaxValue =
12002       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12003   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12004 }
12005 
12006 void SITargetLowering::computeKnownBitsForTargetInstr(
12007     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12008     const MachineRegisterInfo &MRI, unsigned Depth) const {
12009   const MachineInstr *MI = MRI.getVRegDef(R);
12010   switch (MI->getOpcode()) {
12011   case AMDGPU::G_INTRINSIC: {
12012     switch (MI->getIntrinsicID()) {
12013     case Intrinsic::amdgcn_workitem_id_x:
12014       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12015       break;
12016     case Intrinsic::amdgcn_workitem_id_y:
12017       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12018       break;
12019     case Intrinsic::amdgcn_workitem_id_z:
12020       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12021       break;
12022     case Intrinsic::amdgcn_mbcnt_lo:
12023     case Intrinsic::amdgcn_mbcnt_hi: {
12024       // These return at most the wavefront size - 1.
12025       unsigned Size = MRI.getType(R).getSizeInBits();
12026       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12027       break;
12028     }
12029     case Intrinsic::amdgcn_groupstaticsize: {
12030       // We can report everything over the maximum size as 0. We can't report
12031       // based on the actual size because we don't know if it's accurate or not
12032       // at any given point.
12033       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12034       break;
12035     }
12036     }
12037     break;
12038   }
12039   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12040     Known.Zero.setHighBits(24);
12041     break;
12042   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12043     Known.Zero.setHighBits(16);
12044     break;
12045   }
12046 }
12047 
12048 Align SITargetLowering::computeKnownAlignForTargetInstr(
12049   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12050   unsigned Depth) const {
12051   const MachineInstr *MI = MRI.getVRegDef(R);
12052   switch (MI->getOpcode()) {
12053   case AMDGPU::G_INTRINSIC:
12054   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12055     // FIXME: Can this move to generic code? What about the case where the call
12056     // site specifies a lower alignment?
12057     Intrinsic::ID IID = MI->getIntrinsicID();
12058     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12059     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12060     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12061       return *RetAlign;
12062     return Align(1);
12063   }
12064   default:
12065     return Align(1);
12066   }
12067 }
12068 
12069 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12070   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12071   const Align CacheLineAlign = Align(64);
12072 
12073   // Pre-GFX10 target did not benefit from loop alignment
12074   if (!ML || DisableLoopAlignment ||
12075       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12076       getSubtarget()->hasInstFwdPrefetchBug())
12077     return PrefAlign;
12078 
12079   // On GFX10 I$ is 4 x 64 bytes cache lines.
12080   // By default prefetcher keeps one cache line behind and reads two ahead.
12081   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12082   // behind and one ahead.
12083   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12084   // If loop fits 64 bytes it always spans no more than two cache lines and
12085   // does not need an alignment.
12086   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12087   // Else if loop is less or equal 192 bytes we need two lines behind.
12088 
12089   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12090   const MachineBasicBlock *Header = ML->getHeader();
12091   if (Header->getAlignment() != PrefAlign)
12092     return Header->getAlignment(); // Already processed.
12093 
12094   unsigned LoopSize = 0;
12095   for (const MachineBasicBlock *MBB : ML->blocks()) {
12096     // If inner loop block is aligned assume in average half of the alignment
12097     // size to be added as nops.
12098     if (MBB != Header)
12099       LoopSize += MBB->getAlignment().value() / 2;
12100 
12101     for (const MachineInstr &MI : *MBB) {
12102       LoopSize += TII->getInstSizeInBytes(MI);
12103       if (LoopSize > 192)
12104         return PrefAlign;
12105     }
12106   }
12107 
12108   if (LoopSize <= 64)
12109     return PrefAlign;
12110 
12111   if (LoopSize <= 128)
12112     return CacheLineAlign;
12113 
12114   // If any of parent loops is surrounded by prefetch instructions do not
12115   // insert new for inner loop, which would reset parent's settings.
12116   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12117     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12118       auto I = Exit->getFirstNonDebugInstr();
12119       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12120         return CacheLineAlign;
12121     }
12122   }
12123 
12124   MachineBasicBlock *Pre = ML->getLoopPreheader();
12125   MachineBasicBlock *Exit = ML->getExitBlock();
12126 
12127   if (Pre && Exit) {
12128     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12129             TII->get(AMDGPU::S_INST_PREFETCH))
12130       .addImm(1); // prefetch 2 lines behind PC
12131 
12132     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12133             TII->get(AMDGPU::S_INST_PREFETCH))
12134       .addImm(2); // prefetch 1 line behind PC
12135   }
12136 
12137   return CacheLineAlign;
12138 }
12139 
12140 LLVM_ATTRIBUTE_UNUSED
12141 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12142   assert(N->getOpcode() == ISD::CopyFromReg);
12143   do {
12144     // Follow the chain until we find an INLINEASM node.
12145     N = N->getOperand(0).getNode();
12146     if (N->getOpcode() == ISD::INLINEASM ||
12147         N->getOpcode() == ISD::INLINEASM_BR)
12148       return true;
12149   } while (N->getOpcode() == ISD::CopyFromReg);
12150   return false;
12151 }
12152 
12153 bool SITargetLowering::isSDNodeSourceOfDivergence(
12154     const SDNode *N, FunctionLoweringInfo *FLI,
12155     LegacyDivergenceAnalysis *KDA) const {
12156   switch (N->getOpcode()) {
12157   case ISD::CopyFromReg: {
12158     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12159     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12160     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12161     Register Reg = R->getReg();
12162 
12163     // FIXME: Why does this need to consider isLiveIn?
12164     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12165       return !TRI->isSGPRReg(MRI, Reg);
12166 
12167     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12168       return KDA->isDivergent(V);
12169 
12170     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12171     return !TRI->isSGPRReg(MRI, Reg);
12172   }
12173   case ISD::LOAD: {
12174     const LoadSDNode *L = cast<LoadSDNode>(N);
12175     unsigned AS = L->getAddressSpace();
12176     // A flat load may access private memory.
12177     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12178   }
12179   case ISD::CALLSEQ_END:
12180     return true;
12181   case ISD::INTRINSIC_WO_CHAIN:
12182     return AMDGPU::isIntrinsicSourceOfDivergence(
12183         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12184   case ISD::INTRINSIC_W_CHAIN:
12185     return AMDGPU::isIntrinsicSourceOfDivergence(
12186         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12187   case AMDGPUISD::ATOMIC_CMP_SWAP:
12188   case AMDGPUISD::ATOMIC_INC:
12189   case AMDGPUISD::ATOMIC_DEC:
12190   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12191   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12192   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12193   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12194   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12195   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12196   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12197   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12198   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12199   case AMDGPUISD::BUFFER_ATOMIC_AND:
12200   case AMDGPUISD::BUFFER_ATOMIC_OR:
12201   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12202   case AMDGPUISD::BUFFER_ATOMIC_INC:
12203   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12204   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12205   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12206   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12207   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12208   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12209     // Target-specific read-modify-write atomics are sources of divergence.
12210     return true;
12211   default:
12212     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12213       // Generic read-modify-write atomics are sources of divergence.
12214       return A->readMem() && A->writeMem();
12215     }
12216     return false;
12217   }
12218 }
12219 
12220 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12221                                                EVT VT) const {
12222   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12223   case MVT::f32:
12224     return hasFP32Denormals(DAG.getMachineFunction());
12225   case MVT::f64:
12226   case MVT::f16:
12227     return hasFP64FP16Denormals(DAG.getMachineFunction());
12228   default:
12229     return false;
12230   }
12231 }
12232 
12233 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12234                                                MachineFunction &MF) const {
12235   switch (Ty.getScalarSizeInBits()) {
12236   case 32:
12237     return hasFP32Denormals(MF);
12238   case 64:
12239   case 16:
12240     return hasFP64FP16Denormals(MF);
12241   default:
12242     return false;
12243   }
12244 }
12245 
12246 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12247                                                     const SelectionDAG &DAG,
12248                                                     bool SNaN,
12249                                                     unsigned Depth) const {
12250   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12251     const MachineFunction &MF = DAG.getMachineFunction();
12252     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12253 
12254     if (Info->getMode().DX10Clamp)
12255       return true; // Clamped to 0.
12256     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12257   }
12258 
12259   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12260                                                             SNaN, Depth);
12261 }
12262 
12263 // Global FP atomic instructions have a hardcoded FP mode and do not support
12264 // FP32 denormals, and only support v2f16 denormals.
12265 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12266   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12267   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12268   if (&Flt == &APFloat::IEEEsingle())
12269     return DenormMode == DenormalMode::getPreserveSign();
12270   return DenormMode == DenormalMode::getIEEE();
12271 }
12272 
12273 TargetLowering::AtomicExpansionKind
12274 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12275 
12276   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12277     OptimizationRemarkEmitter ORE(RMW->getFunction());
12278     LLVMContext &Ctx = RMW->getFunction()->getContext();
12279     SmallVector<StringRef> SSNs;
12280     Ctx.getSyncScopeNames(SSNs);
12281     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12282                         ? "system"
12283                         : SSNs[RMW->getSyncScopeID()];
12284     ORE.emit([&]() {
12285       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12286              << "Hardware instruction generated for atomic "
12287              << RMW->getOperationName(RMW->getOperation())
12288              << " operation at memory scope " << MemScope
12289              << " due to an unsafe request.";
12290     });
12291     return Kind;
12292   };
12293 
12294   switch (RMW->getOperation()) {
12295   case AtomicRMWInst::FAdd: {
12296     Type *Ty = RMW->getType();
12297 
12298     // We don't have a way to support 16-bit atomics now, so just leave them
12299     // as-is.
12300     if (Ty->isHalfTy())
12301       return AtomicExpansionKind::None;
12302 
12303     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12304       return AtomicExpansionKind::CmpXChg;
12305 
12306     unsigned AS = RMW->getPointerAddressSpace();
12307 
12308     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12309          Subtarget->hasAtomicFaddInsts()) {
12310       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12311       // floating point atomic instructions. May generate more efficient code,
12312       // but may not respect rounding and denormal modes, and may give incorrect
12313       // results for certain memory destinations.
12314       if (RMW->getFunction()
12315               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12316               .getValueAsString() != "true")
12317         return AtomicExpansionKind::CmpXChg;
12318 
12319       if (Subtarget->hasGFX90AInsts()) {
12320         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12321           return AtomicExpansionKind::CmpXChg;
12322 
12323         auto SSID = RMW->getSyncScopeID();
12324         if (SSID == SyncScope::System ||
12325             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12326           return AtomicExpansionKind::CmpXChg;
12327 
12328         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12329       }
12330 
12331       if (AS == AMDGPUAS::FLAT_ADDRESS)
12332         return AtomicExpansionKind::CmpXChg;
12333 
12334       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12335                               : AtomicExpansionKind::CmpXChg;
12336     }
12337 
12338     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12339     // to round-to-nearest-even.
12340     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12341     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12342       if (!Ty->isDoubleTy())
12343         return AtomicExpansionKind::None;
12344 
12345       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12346         return AtomicExpansionKind::None;
12347 
12348       return RMW->getFunction()
12349                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12350                          .getValueAsString() == "true"
12351                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12352                  : AtomicExpansionKind::CmpXChg;
12353     }
12354 
12355     return AtomicExpansionKind::CmpXChg;
12356   }
12357   default:
12358     break;
12359   }
12360 
12361   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12362 }
12363 
12364 const TargetRegisterClass *
12365 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12366   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12367   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12368   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12369     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12370                                                : &AMDGPU::SReg_32RegClass;
12371   if (!TRI->isSGPRClass(RC) && !isDivergent)
12372     return TRI->getEquivalentSGPRClass(RC);
12373   else if (TRI->isSGPRClass(RC) && isDivergent)
12374     return TRI->getEquivalentVGPRClass(RC);
12375 
12376   return RC;
12377 }
12378 
12379 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12380 // uniform values (as produced by the mask results of control flow intrinsics)
12381 // used outside of divergent blocks. The phi users need to also be treated as
12382 // always uniform.
12383 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12384                       unsigned WaveSize) {
12385   // FIXME: We asssume we never cast the mask results of a control flow
12386   // intrinsic.
12387   // Early exit if the type won't be consistent as a compile time hack.
12388   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12389   if (!IT || IT->getBitWidth() != WaveSize)
12390     return false;
12391 
12392   if (!isa<Instruction>(V))
12393     return false;
12394   if (!Visited.insert(V).second)
12395     return false;
12396   bool Result = false;
12397   for (auto U : V->users()) {
12398     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12399       if (V == U->getOperand(1)) {
12400         switch (Intrinsic->getIntrinsicID()) {
12401         default:
12402           Result = false;
12403           break;
12404         case Intrinsic::amdgcn_if_break:
12405         case Intrinsic::amdgcn_if:
12406         case Intrinsic::amdgcn_else:
12407           Result = true;
12408           break;
12409         }
12410       }
12411       if (V == U->getOperand(0)) {
12412         switch (Intrinsic->getIntrinsicID()) {
12413         default:
12414           Result = false;
12415           break;
12416         case Intrinsic::amdgcn_end_cf:
12417         case Intrinsic::amdgcn_loop:
12418           Result = true;
12419           break;
12420         }
12421       }
12422     } else {
12423       Result = hasCFUser(U, Visited, WaveSize);
12424     }
12425     if (Result)
12426       break;
12427   }
12428   return Result;
12429 }
12430 
12431 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12432                                                const Value *V) const {
12433   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12434     if (CI->isInlineAsm()) {
12435       // FIXME: This cannot give a correct answer. This should only trigger in
12436       // the case where inline asm returns mixed SGPR and VGPR results, used
12437       // outside the defining block. We don't have a specific result to
12438       // consider, so this assumes if any value is SGPR, the overall register
12439       // also needs to be SGPR.
12440       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12441       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12442           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12443       for (auto &TC : TargetConstraints) {
12444         if (TC.Type == InlineAsm::isOutput) {
12445           ComputeConstraintToUse(TC, SDValue());
12446           unsigned AssignedReg;
12447           const TargetRegisterClass *RC;
12448           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12449               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12450           if (RC) {
12451             MachineRegisterInfo &MRI = MF.getRegInfo();
12452             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12453               return true;
12454             else if (SIRI->isSGPRClass(RC))
12455               return true;
12456           }
12457         }
12458       }
12459     }
12460   }
12461   SmallPtrSet<const Value *, 16> Visited;
12462   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12463 }
12464 
12465 std::pair<InstructionCost, MVT>
12466 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12467                                           Type *Ty) const {
12468   std::pair<InstructionCost, MVT> Cost =
12469       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12470   auto Size = DL.getTypeSizeInBits(Ty);
12471   // Maximum load or store can handle 8 dwords for scalar and 4 for
12472   // vector ALU. Let's assume anything above 8 dwords is expensive
12473   // even if legal.
12474   if (Size <= 256)
12475     return Cost;
12476 
12477   Cost.first += (Size + 255) / 256;
12478   return Cost;
12479 }
12480