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/MachineFunction.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/IntrinsicsAMDGPU.h"
32 #include "llvm/IR/IntrinsicsR600.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/KnownBits.h"
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "si-lower"
39 
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 
42 static cl::opt<bool> DisableLoopAlignment(
43   "amdgpu-disable-loop-alignment",
44   cl::desc("Do not align and prefetch loops"),
45   cl::init(false));
46 
47 static cl::opt<bool> VGPRReserveforSGPRSpill(
48     "amdgpu-reserve-vgpr-for-sgpr-spill",
49     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
50 
51 static cl::opt<bool> UseDivergentRegisterIndexing(
52   "amdgpu-use-divergent-register-indexing",
53   cl::Hidden,
54   cl::desc("Use indirect register addressing for divergent indexes"),
55   cl::init(false));
56 
57 static bool hasFP32Denormals(const MachineFunction &MF) {
58   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
59   return Info->getMode().allFP32Denormals();
60 }
61 
62 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
63   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
64   return Info->getMode().allFP64FP16Denormals();
65 }
66 
67 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
68   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
69   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
70     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
71       return AMDGPU::SGPR0 + Reg;
72     }
73   }
74   llvm_unreachable("Cannot allocate sgpr");
75 }
76 
77 SITargetLowering::SITargetLowering(const TargetMachine &TM,
78                                    const GCNSubtarget &STI)
79     : AMDGPUTargetLowering(TM, STI),
80       Subtarget(&STI) {
81   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
82   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
83 
84   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
85   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
86 
87   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
88 
89   const SIRegisterInfo *TRI = STI.getRegisterInfo();
90   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
91 
92   addRegisterClass(MVT::f64, V64RegClass);
93   addRegisterClass(MVT::v2f32, V64RegClass);
94 
95   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
96   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
97 
98   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
100 
101   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
102   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
103 
104   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
105   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
106 
107   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
108   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
109 
110   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
111   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
112 
113   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
114   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
115 
116   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
117   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
118 
119   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
120   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
121 
122   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
123   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
124 
125   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
126   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
127 
128   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
129   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
130 
131   if (Subtarget->has16BitInsts()) {
132     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
133     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
134 
135     // Unless there are also VOP3P operations, not operations are really legal.
136     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
138     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
140   }
141 
142   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
143   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
144 
145   computeRegisterProperties(Subtarget->getRegisterInfo());
146 
147   // The boolean content concept here is too inflexible. Compares only ever
148   // really produce a 1-bit result. Any copy/extend from these will turn into a
149   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
150   // it's what most targets use.
151   setBooleanContents(ZeroOrOneBooleanContent);
152   setBooleanVectorContents(ZeroOrOneBooleanContent);
153 
154   // We need to custom lower vector stores from local memory
155   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::i1, Custom);
164   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165 
166   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
174   setOperationAction(ISD::STORE, MVT::i1, Custom);
175   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
176 
177   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
178   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
179   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
180   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
181   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
182   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
183   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
184   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
185   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
186   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
187   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
188   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
189   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
192   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
193 
194   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
195   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
196   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
200   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
201 
202   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
203   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
204 
205   setOperationAction(ISD::SELECT, MVT::i1, Promote);
206   setOperationAction(ISD::SELECT, MVT::i64, Custom);
207   setOperationAction(ISD::SELECT, MVT::f64, Promote);
208   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
209 
210   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
215 
216   setOperationAction(ISD::SETCC, MVT::i1, Promote);
217   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
218   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
219   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
220 
221   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
222   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
223   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
224   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
225   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
227   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
228   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
229   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
230   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
231   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
232   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
233   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
234   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
235   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
236   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
237 
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
246 
247   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
253 
254   setOperationAction(ISD::UADDO, MVT::i32, Legal);
255   setOperationAction(ISD::USUBO, MVT::i32, Legal);
256 
257   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
258   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
259 
260   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
263 
264 #if 0
265   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
266   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
267 #endif
268 
269   // We only support LOAD/STORE and vector manipulation ops for vectors
270   // with > 4 elements.
271   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
272                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
273                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
274                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
275                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
276     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
277       switch (Op) {
278       case ISD::LOAD:
279       case ISD::STORE:
280       case ISD::BUILD_VECTOR:
281       case ISD::BITCAST:
282       case ISD::EXTRACT_VECTOR_ELT:
283       case ISD::INSERT_VECTOR_ELT:
284       case ISD::EXTRACT_SUBVECTOR:
285       case ISD::SCALAR_TO_VECTOR:
286         break;
287       case ISD::INSERT_SUBVECTOR:
288       case ISD::CONCAT_VECTORS:
289         setOperationAction(Op, VT, Custom);
290         break;
291       default:
292         setOperationAction(Op, VT, Expand);
293         break;
294       }
295     }
296   }
297 
298   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
299 
300   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
301   // is expanded to avoid having two separate loops in case the index is a VGPR.
302 
303   // Most operations are naturally 32-bit vector operations. We only support
304   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
305   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
306     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
314 
315     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
317   }
318 
319   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
320     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
322 
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
325 
326     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
328 
329     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
331   }
332 
333   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
334     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
341     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
344     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
345   }
346 
347   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
348     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
355     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
358     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
359   }
360 
361   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
362     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
369     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
372     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
373   }
374 
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
379 
380   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
382 
383   // Avoid stack access for these.
384   // TODO: Generalize to more vector types.
385   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
387   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
389 
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396 
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401 
402   // Deal with vec3 vector operations when widened to vec4.
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407 
408   // Deal with vec5/6/7 vector operations when widened to vec8.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
417 
418   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
419   // and output demarshalling
420   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
422 
423   // We can't return success/failure, only the old value,
424   // let LLVM add the comparison
425   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
427 
428   if (Subtarget->hasFlatAddressSpace()) {
429     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
431   }
432 
433   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
434   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
435 
436   // FIXME: This should be narrowed to i32, but that only happens if i64 is
437   // illegal.
438   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
439   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
440   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
441 
442   // On SI this is s_memtime and s_memrealtime on VI.
443   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444   setOperationAction(ISD::TRAP, MVT::Other, Custom);
445   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
446 
447   if (Subtarget->has16BitInsts()) {
448     setOperationAction(ISD::FPOW, MVT::f16, Promote);
449     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
450     setOperationAction(ISD::FLOG, MVT::f16, Custom);
451     setOperationAction(ISD::FEXP, MVT::f16, Custom);
452     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453   }
454 
455   if (Subtarget->hasMadMacF32Insts())
456     setOperationAction(ISD::FMAD, MVT::f32, Legal);
457 
458   if (!Subtarget->hasBFI()) {
459     // fcopysign can be done in a single instruction with BFI.
460     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
461     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
462   }
463 
464   if (!Subtarget->hasBCNT(32))
465     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
466 
467   if (!Subtarget->hasBCNT(64))
468     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
469 
470   if (Subtarget->hasFFBH()) {
471     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473   }
474 
475   if (Subtarget->hasFFBL()) {
476     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478   }
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773 
774     if (Subtarget->hasPackedFP32Ops()) {
775       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
776       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
777       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
778       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
779 
780       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
781         setOperationAction(ISD::FADD, VT, Custom);
782         setOperationAction(ISD::FMUL, VT, Custom);
783         setOperationAction(ISD::FMA, VT, Custom);
784       }
785     }
786   }
787 
788   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
789   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
790 
791   if (Subtarget->has16BitInsts()) {
792     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
793     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
794     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
795     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
796   } else {
797     // Legalization hack.
798     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
799     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
800 
801     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
802     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
803   }
804 
805   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
806     setOperationAction(ISD::SELECT, VT, Custom);
807   }
808 
809   setOperationAction(ISD::SMULO, MVT::i64, Custom);
810   setOperationAction(ISD::UMULO, MVT::i64, Custom);
811 
812   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
814   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
815   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
816   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
817   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
819 
820   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
821   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
822   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
823   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
824   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
831 
832   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
833   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
834   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
835   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
836   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
837   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
842 
843   setTargetDAGCombine(ISD::ADD);
844   setTargetDAGCombine(ISD::ADDCARRY);
845   setTargetDAGCombine(ISD::SUB);
846   setTargetDAGCombine(ISD::SUBCARRY);
847   setTargetDAGCombine(ISD::FADD);
848   setTargetDAGCombine(ISD::FSUB);
849   setTargetDAGCombine(ISD::FMINNUM);
850   setTargetDAGCombine(ISD::FMAXNUM);
851   setTargetDAGCombine(ISD::FMINNUM_IEEE);
852   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
853   setTargetDAGCombine(ISD::FMA);
854   setTargetDAGCombine(ISD::SMIN);
855   setTargetDAGCombine(ISD::SMAX);
856   setTargetDAGCombine(ISD::UMIN);
857   setTargetDAGCombine(ISD::UMAX);
858   setTargetDAGCombine(ISD::SETCC);
859   setTargetDAGCombine(ISD::AND);
860   setTargetDAGCombine(ISD::OR);
861   setTargetDAGCombine(ISD::XOR);
862   setTargetDAGCombine(ISD::SINT_TO_FP);
863   setTargetDAGCombine(ISD::UINT_TO_FP);
864   setTargetDAGCombine(ISD::FCANONICALIZE);
865   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
866   setTargetDAGCombine(ISD::ZERO_EXTEND);
867   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
868   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
869   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
870 
871   // All memory operations. Some folding on the pointer operand is done to help
872   // matching the constant offsets in the addressing modes.
873   setTargetDAGCombine(ISD::LOAD);
874   setTargetDAGCombine(ISD::STORE);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD);
876   setTargetDAGCombine(ISD::ATOMIC_STORE);
877   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
878   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
879   setTargetDAGCombine(ISD::ATOMIC_SWAP);
880   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
881   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
882   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
883   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
884   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
885   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
891   setTargetDAGCombine(ISD::INTRINSIC_VOID);
892   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
893 
894   // FIXME: In other contexts we pretend this is a per-function property.
895   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
896 
897   setSchedulingPreference(Sched::RegPressure);
898 }
899 
900 const GCNSubtarget *SITargetLowering::getSubtarget() const {
901   return Subtarget;
902 }
903 
904 //===----------------------------------------------------------------------===//
905 // TargetLowering queries
906 //===----------------------------------------------------------------------===//
907 
908 // v_mad_mix* support a conversion from f16 to f32.
909 //
910 // There is only one special case when denormals are enabled we don't currently,
911 // where this is OK to use.
912 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
913                                        EVT DestVT, EVT SrcVT) const {
914   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
915           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
916     DestVT.getScalarType() == MVT::f32 &&
917     SrcVT.getScalarType() == MVT::f16 &&
918     // TODO: This probably only requires no input flushing?
919     !hasFP32Denormals(DAG.getMachineFunction());
920 }
921 
922 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
923   // SI has some legal vector types, but no legal vector operations. Say no
924   // shuffles are legal in order to prefer scalarizing some vector operations.
925   return false;
926 }
927 
928 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
929                                                     CallingConv::ID CC,
930                                                     EVT VT) const {
931   if (CC == CallingConv::AMDGPU_KERNEL)
932     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
933 
934   if (VT.isVector()) {
935     EVT ScalarVT = VT.getScalarType();
936     unsigned Size = ScalarVT.getSizeInBits();
937     if (Size == 16) {
938       if (Subtarget->has16BitInsts())
939         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
940       return VT.isInteger() ? MVT::i32 : MVT::f32;
941     }
942 
943     if (Size < 16)
944       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
945     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
946   }
947 
948   if (VT.getSizeInBits() > 32)
949     return MVT::i32;
950 
951   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
952 }
953 
954 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
955                                                          CallingConv::ID CC,
956                                                          EVT VT) const {
957   if (CC == CallingConv::AMDGPU_KERNEL)
958     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
959 
960   if (VT.isVector()) {
961     unsigned NumElts = VT.getVectorNumElements();
962     EVT ScalarVT = VT.getScalarType();
963     unsigned Size = ScalarVT.getSizeInBits();
964 
965     // FIXME: Should probably promote 8-bit vectors to i16.
966     if (Size == 16 && Subtarget->has16BitInsts())
967       return (NumElts + 1) / 2;
968 
969     if (Size <= 32)
970       return NumElts;
971 
972     if (Size > 32)
973       return NumElts * ((Size + 31) / 32);
974   } else if (VT.getSizeInBits() > 32)
975     return (VT.getSizeInBits() + 31) / 32;
976 
977   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
978 }
979 
980 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
981   LLVMContext &Context, CallingConv::ID CC,
982   EVT VT, EVT &IntermediateVT,
983   unsigned &NumIntermediates, MVT &RegisterVT) const {
984   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
985     unsigned NumElts = VT.getVectorNumElements();
986     EVT ScalarVT = VT.getScalarType();
987     unsigned Size = ScalarVT.getSizeInBits();
988     // FIXME: We should fix the ABI to be the same on targets without 16-bit
989     // support, but unless we can properly handle 3-vectors, it will be still be
990     // inconsistent.
991     if (Size == 16 && Subtarget->has16BitInsts()) {
992       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
993       IntermediateVT = RegisterVT;
994       NumIntermediates = (NumElts + 1) / 2;
995       return NumIntermediates;
996     }
997 
998     if (Size == 32) {
999       RegisterVT = ScalarVT.getSimpleVT();
1000       IntermediateVT = RegisterVT;
1001       NumIntermediates = NumElts;
1002       return NumIntermediates;
1003     }
1004 
1005     if (Size < 16 && Subtarget->has16BitInsts()) {
1006       // FIXME: Should probably form v2i16 pieces
1007       RegisterVT = MVT::i16;
1008       IntermediateVT = ScalarVT;
1009       NumIntermediates = NumElts;
1010       return NumIntermediates;
1011     }
1012 
1013 
1014     if (Size != 16 && Size <= 32) {
1015       RegisterVT = MVT::i32;
1016       IntermediateVT = ScalarVT;
1017       NumIntermediates = NumElts;
1018       return NumIntermediates;
1019     }
1020 
1021     if (Size > 32) {
1022       RegisterVT = MVT::i32;
1023       IntermediateVT = RegisterVT;
1024       NumIntermediates = NumElts * ((Size + 31) / 32);
1025       return NumIntermediates;
1026     }
1027   }
1028 
1029   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1030     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1031 }
1032 
1033 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1034   assert(DMaskLanes != 0);
1035 
1036   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1037     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1038     return EVT::getVectorVT(Ty->getContext(),
1039                             EVT::getEVT(VT->getElementType()),
1040                             NumElts);
1041   }
1042 
1043   return EVT::getEVT(Ty);
1044 }
1045 
1046 // Peek through TFE struct returns to only use the data size.
1047 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1048   auto *ST = dyn_cast<StructType>(Ty);
1049   if (!ST)
1050     return memVTFromImageData(Ty, DMaskLanes);
1051 
1052   // Some intrinsics return an aggregate type - special case to work out the
1053   // correct memVT.
1054   //
1055   // Only limited forms of aggregate type currently expected.
1056   if (ST->getNumContainedTypes() != 2 ||
1057       !ST->getContainedType(1)->isIntegerTy(32))
1058     return EVT();
1059   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1060 }
1061 
1062 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1063                                           const CallInst &CI,
1064                                           MachineFunction &MF,
1065                                           unsigned IntrID) const {
1066   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1067           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1068     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1069                                                   (Intrinsic::ID)IntrID);
1070     if (Attr.hasFnAttr(Attribute::ReadNone))
1071       return false;
1072 
1073     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1074 
1075     if (RsrcIntr->IsImage) {
1076       Info.ptrVal =
1077           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1078       Info.align.reset();
1079     } else {
1080       Info.ptrVal =
1081           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1082     }
1083 
1084     Info.flags = MachineMemOperand::MODereferenceable;
1085     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1086       unsigned DMaskLanes = 4;
1087 
1088       if (RsrcIntr->IsImage) {
1089         const AMDGPU::ImageDimIntrinsicInfo *Intr
1090           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1091         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1092           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1093 
1094         if (!BaseOpcode->Gather4) {
1095           // If this isn't a gather, we may have excess loaded elements in the
1096           // IR type. Check the dmask for the real number of elements loaded.
1097           unsigned DMask
1098             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1099           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1100         }
1101 
1102         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1103       } else
1104         Info.memVT = EVT::getEVT(CI.getType());
1105 
1106       // FIXME: What does alignment mean for an image?
1107       Info.opc = ISD::INTRINSIC_W_CHAIN;
1108       Info.flags |= MachineMemOperand::MOLoad;
1109     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1110       Info.opc = ISD::INTRINSIC_VOID;
1111 
1112       Type *DataTy = CI.getArgOperand(0)->getType();
1113       if (RsrcIntr->IsImage) {
1114         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1115         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1116         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1117       } else
1118         Info.memVT = EVT::getEVT(DataTy);
1119 
1120       Info.flags |= MachineMemOperand::MOStore;
1121     } else {
1122       // Atomic
1123       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1124                                             ISD::INTRINSIC_W_CHAIN;
1125       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1126       Info.flags = MachineMemOperand::MOLoad |
1127                    MachineMemOperand::MOStore |
1128                    MachineMemOperand::MODereferenceable;
1129 
1130       // XXX - Should this be volatile without known ordering?
1131       Info.flags |= MachineMemOperand::MOVolatile;
1132     }
1133     return true;
1134   }
1135 
1136   switch (IntrID) {
1137   case Intrinsic::amdgcn_atomic_inc:
1138   case Intrinsic::amdgcn_atomic_dec:
1139   case Intrinsic::amdgcn_ds_ordered_add:
1140   case Intrinsic::amdgcn_ds_ordered_swap:
1141   case Intrinsic::amdgcn_ds_fadd:
1142   case Intrinsic::amdgcn_ds_fmin:
1143   case Intrinsic::amdgcn_ds_fmax: {
1144     Info.opc = ISD::INTRINSIC_W_CHAIN;
1145     Info.memVT = MVT::getVT(CI.getType());
1146     Info.ptrVal = CI.getOperand(0);
1147     Info.align.reset();
1148     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1149 
1150     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1151     if (!Vol->isZero())
1152       Info.flags |= MachineMemOperand::MOVolatile;
1153 
1154     return true;
1155   }
1156   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1157     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1158 
1159     Info.opc = ISD::INTRINSIC_W_CHAIN;
1160     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1161     Info.ptrVal =
1162         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1165 
1166     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1167     if (!Vol || !Vol->isZero())
1168       Info.flags |= MachineMemOperand::MOVolatile;
1169 
1170     return true;
1171   }
1172   case Intrinsic::amdgcn_ds_append:
1173   case Intrinsic::amdgcn_ds_consume: {
1174     Info.opc = ISD::INTRINSIC_W_CHAIN;
1175     Info.memVT = MVT::getVT(CI.getType());
1176     Info.ptrVal = CI.getOperand(0);
1177     Info.align.reset();
1178     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1179 
1180     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1181     if (!Vol->isZero())
1182       Info.flags |= MachineMemOperand::MOVolatile;
1183 
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_csub: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MOVolatile;
1194     return true;
1195   }
1196   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1197     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1198     Info.opc = ISD::INTRINSIC_W_CHAIN;
1199     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1200     Info.ptrVal =
1201         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1202     Info.align.reset();
1203     Info.flags = MachineMemOperand::MOLoad |
1204                  MachineMemOperand::MODereferenceable;
1205     return true;
1206   }
1207   case Intrinsic::amdgcn_global_atomic_fadd:
1208   case Intrinsic::amdgcn_global_atomic_fmin:
1209   case Intrinsic::amdgcn_global_atomic_fmax:
1210   case Intrinsic::amdgcn_flat_atomic_fadd:
1211   case Intrinsic::amdgcn_flat_atomic_fmin:
1212   case Intrinsic::amdgcn_flat_atomic_fmax: {
1213     Info.opc = ISD::INTRINSIC_W_CHAIN;
1214     Info.memVT = MVT::getVT(CI.getType());
1215     Info.ptrVal = CI.getOperand(0);
1216     Info.align.reset();
1217     Info.flags = MachineMemOperand::MOLoad |
1218                  MachineMemOperand::MOStore |
1219                  MachineMemOperand::MODereferenceable |
1220                  MachineMemOperand::MOVolatile;
1221     return true;
1222   }
1223   case Intrinsic::amdgcn_ds_gws_init:
1224   case Intrinsic::amdgcn_ds_gws_barrier:
1225   case Intrinsic::amdgcn_ds_gws_sema_v:
1226   case Intrinsic::amdgcn_ds_gws_sema_br:
1227   case Intrinsic::amdgcn_ds_gws_sema_p:
1228   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1229     Info.opc = ISD::INTRINSIC_VOID;
1230 
1231     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1232     Info.ptrVal =
1233         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1234 
1235     // This is an abstract access, but we need to specify a type and size.
1236     Info.memVT = MVT::i32;
1237     Info.size = 4;
1238     Info.align = Align(4);
1239 
1240     Info.flags = MachineMemOperand::MOStore;
1241     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1242       Info.flags = MachineMemOperand::MOLoad;
1243     return true;
1244   }
1245   default:
1246     return false;
1247   }
1248 }
1249 
1250 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1251                                             SmallVectorImpl<Value*> &Ops,
1252                                             Type *&AccessTy) const {
1253   switch (II->getIntrinsicID()) {
1254   case Intrinsic::amdgcn_atomic_inc:
1255   case Intrinsic::amdgcn_atomic_dec:
1256   case Intrinsic::amdgcn_ds_ordered_add:
1257   case Intrinsic::amdgcn_ds_ordered_swap:
1258   case Intrinsic::amdgcn_ds_append:
1259   case Intrinsic::amdgcn_ds_consume:
1260   case Intrinsic::amdgcn_ds_fadd:
1261   case Intrinsic::amdgcn_ds_fmin:
1262   case Intrinsic::amdgcn_ds_fmax:
1263   case Intrinsic::amdgcn_global_atomic_fadd:
1264   case Intrinsic::amdgcn_flat_atomic_fadd:
1265   case Intrinsic::amdgcn_flat_atomic_fmin:
1266   case Intrinsic::amdgcn_flat_atomic_fmax:
1267   case Intrinsic::amdgcn_global_atomic_csub: {
1268     Value *Ptr = II->getArgOperand(0);
1269     AccessTy = II->getType();
1270     Ops.push_back(Ptr);
1271     return true;
1272   }
1273   default:
1274     return false;
1275   }
1276 }
1277 
1278 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1279   if (!Subtarget->hasFlatInstOffsets()) {
1280     // Flat instructions do not have offsets, and only have the register
1281     // address.
1282     return AM.BaseOffs == 0 && AM.Scale == 0;
1283   }
1284 
1285   return AM.Scale == 0 &&
1286          (AM.BaseOffs == 0 ||
1287           Subtarget->getInstrInfo()->isLegalFLATOffset(
1288               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1289 }
1290 
1291 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1292   if (Subtarget->hasFlatGlobalInsts())
1293     return AM.Scale == 0 &&
1294            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1295                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1296                                     SIInstrFlags::FlatGlobal));
1297 
1298   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1299       // Assume the we will use FLAT for all global memory accesses
1300       // on VI.
1301       // FIXME: This assumption is currently wrong.  On VI we still use
1302       // MUBUF instructions for the r + i addressing mode.  As currently
1303       // implemented, the MUBUF instructions only work on buffer < 4GB.
1304       // It may be possible to support > 4GB buffers with MUBUF instructions,
1305       // by setting the stride value in the resource descriptor which would
1306       // increase the size limit to (stride * 4GB).  However, this is risky,
1307       // because it has never been validated.
1308     return isLegalFlatAddressingMode(AM);
1309   }
1310 
1311   return isLegalMUBUFAddressingMode(AM);
1312 }
1313 
1314 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1315   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1316   // additionally can do r + r + i with addr64. 32-bit has more addressing
1317   // mode options. Depending on the resource constant, it can also do
1318   // (i64 r0) + (i32 r1) * (i14 i).
1319   //
1320   // Private arrays end up using a scratch buffer most of the time, so also
1321   // assume those use MUBUF instructions. Scratch loads / stores are currently
1322   // implemented as mubuf instructions with offen bit set, so slightly
1323   // different than the normal addr64.
1324   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1325     return false;
1326 
1327   // FIXME: Since we can split immediate into soffset and immediate offset,
1328   // would it make sense to allow any immediate?
1329 
1330   switch (AM.Scale) {
1331   case 0: // r + i or just i, depending on HasBaseReg.
1332     return true;
1333   case 1:
1334     return true; // We have r + r or r + i.
1335   case 2:
1336     if (AM.HasBaseReg) {
1337       // Reject 2 * r + r.
1338       return false;
1339     }
1340 
1341     // Allow 2 * r as r + r
1342     // Or  2 * r + i is allowed as r + r + i.
1343     return true;
1344   default: // Don't allow n * r
1345     return false;
1346   }
1347 }
1348 
1349 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1350                                              const AddrMode &AM, Type *Ty,
1351                                              unsigned AS, Instruction *I) const {
1352   // No global is ever allowed as a base.
1353   if (AM.BaseGV)
1354     return false;
1355 
1356   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1357     return isLegalGlobalAddressingMode(AM);
1358 
1359   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1360       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1361       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1362     // If the offset isn't a multiple of 4, it probably isn't going to be
1363     // correctly aligned.
1364     // FIXME: Can we get the real alignment here?
1365     if (AM.BaseOffs % 4 != 0)
1366       return isLegalMUBUFAddressingMode(AM);
1367 
1368     // There are no SMRD extloads, so if we have to do a small type access we
1369     // will use a MUBUF load.
1370     // FIXME?: We also need to do this if unaligned, but we don't know the
1371     // alignment here.
1372     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1373       return isLegalGlobalAddressingMode(AM);
1374 
1375     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1376       // SMRD instructions have an 8-bit, dword offset on SI.
1377       if (!isUInt<8>(AM.BaseOffs / 4))
1378         return false;
1379     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1380       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1381       // in 8-bits, it can use a smaller encoding.
1382       if (!isUInt<32>(AM.BaseOffs / 4))
1383         return false;
1384     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1385       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1386       if (!isUInt<20>(AM.BaseOffs))
1387         return false;
1388     } else
1389       llvm_unreachable("unhandled generation");
1390 
1391     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1392       return true;
1393 
1394     if (AM.Scale == 1 && AM.HasBaseReg)
1395       return true;
1396 
1397     return false;
1398 
1399   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1400     return isLegalMUBUFAddressingMode(AM);
1401   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1402              AS == AMDGPUAS::REGION_ADDRESS) {
1403     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1404     // field.
1405     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1406     // an 8-bit dword offset but we don't know the alignment here.
1407     if (!isUInt<16>(AM.BaseOffs))
1408       return false;
1409 
1410     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1411       return true;
1412 
1413     if (AM.Scale == 1 && AM.HasBaseReg)
1414       return true;
1415 
1416     return false;
1417   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1418              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1419     // For an unknown address space, this usually means that this is for some
1420     // reason being used for pure arithmetic, and not based on some addressing
1421     // computation. We don't have instructions that compute pointers with any
1422     // addressing modes, so treat them as having no offset like flat
1423     // instructions.
1424     return isLegalFlatAddressingMode(AM);
1425   }
1426 
1427   // Assume a user alias of global for unknown address spaces.
1428   return isLegalGlobalAddressingMode(AM);
1429 }
1430 
1431 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1432                                         const MachineFunction &MF) const {
1433   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1434     return (MemVT.getSizeInBits() <= 4 * 32);
1435   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1436     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1437     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1438   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1439     return (MemVT.getSizeInBits() <= 2 * 32);
1440   }
1441   return true;
1442 }
1443 
1444 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1445     unsigned Size, unsigned AddrSpace, Align Alignment,
1446     MachineMemOperand::Flags Flags, bool *IsFast) const {
1447   if (IsFast)
1448     *IsFast = false;
1449 
1450   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1451       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1452     // Check if alignment requirements for ds_read/write instructions are
1453     // disabled.
1454     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1455         !Subtarget->hasLDSMisalignedBug()) {
1456       if (IsFast)
1457         *IsFast = Alignment != Align(2);
1458       return true;
1459     }
1460 
1461     // Either, the alignment requirements are "enabled", or there is an
1462     // unaligned LDS access related hardware bug though alignment requirements
1463     // are "disabled". In either case, we need to check for proper alignment
1464     // requirements.
1465     //
1466     if (Size == 64) {
1467       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1468       // can do a 4 byte aligned, 8 byte access in a single operation using
1469       // ds_read2/write2_b32 with adjacent offsets.
1470       bool AlignedBy4 = Alignment >= Align(4);
1471       if (IsFast)
1472         *IsFast = AlignedBy4;
1473 
1474       return AlignedBy4;
1475     }
1476     if (Size == 96) {
1477       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1478       // gfx8 and older.
1479       bool AlignedBy16 = Alignment >= Align(16);
1480       if (IsFast)
1481         *IsFast = AlignedBy16;
1482 
1483       return AlignedBy16;
1484     }
1485     if (Size == 128) {
1486       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1487       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1488       // single operation using ds_read2/write2_b64.
1489       bool AlignedBy8 = Alignment >= Align(8);
1490       if (IsFast)
1491         *IsFast = AlignedBy8;
1492 
1493       return AlignedBy8;
1494     }
1495   }
1496 
1497   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1498     bool AlignedBy4 = Alignment >= Align(4);
1499     if (IsFast)
1500       *IsFast = AlignedBy4;
1501 
1502     return AlignedBy4 ||
1503            Subtarget->enableFlatScratch() ||
1504            Subtarget->hasUnalignedScratchAccess();
1505   }
1506 
1507   // FIXME: We have to be conservative here and assume that flat operations
1508   // will access scratch.  If we had access to the IR function, then we
1509   // could determine if any private memory was used in the function.
1510   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1511       !Subtarget->hasUnalignedScratchAccess()) {
1512     bool AlignedBy4 = Alignment >= Align(4);
1513     if (IsFast)
1514       *IsFast = AlignedBy4;
1515 
1516     return AlignedBy4;
1517   }
1518 
1519   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1520       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1521         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1522     // If we have an uniform constant load, it still requires using a slow
1523     // buffer instruction if unaligned.
1524     if (IsFast) {
1525       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1526       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1527       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1528                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1529         Alignment >= Align(4) : Alignment != Align(2);
1530     }
1531 
1532     return true;
1533   }
1534 
1535   // Smaller than dword value must be aligned.
1536   if (Size < 32)
1537     return false;
1538 
1539   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1540   // byte-address are ignored, thus forcing Dword alignment.
1541   // This applies to private, global, and constant memory.
1542   if (IsFast)
1543     *IsFast = true;
1544 
1545   return Size >= 32 && Alignment >= Align(4);
1546 }
1547 
1548 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1549     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1550     bool *IsFast) const {
1551   if (IsFast)
1552     *IsFast = false;
1553 
1554   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1555   // which isn't a simple VT.
1556   // Until MVT is extended to handle this, simply check for the size and
1557   // rely on the condition below: allow accesses if the size is a multiple of 4.
1558   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1559                            VT.getStoreSize() > 16)) {
1560     return false;
1561   }
1562 
1563   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1564                                             Alignment, Flags, IsFast);
1565 }
1566 
1567 EVT SITargetLowering::getOptimalMemOpType(
1568     const MemOp &Op, const AttributeList &FuncAttributes) const {
1569   // FIXME: Should account for address space here.
1570 
1571   // The default fallback uses the private pointer size as a guess for a type to
1572   // use. Make sure we switch these to 64-bit accesses.
1573 
1574   if (Op.size() >= 16 &&
1575       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1576     return MVT::v4i32;
1577 
1578   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1579     return MVT::v2i32;
1580 
1581   // Use the default.
1582   return MVT::Other;
1583 }
1584 
1585 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1586   const MemSDNode *MemNode = cast<MemSDNode>(N);
1587   const Value *Ptr = MemNode->getMemOperand()->getValue();
1588   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1589   return I && I->getMetadata("amdgpu.noclobber");
1590 }
1591 
1592 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1593   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1594          AS == AMDGPUAS::PRIVATE_ADDRESS;
1595 }
1596 
1597 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1598                                            unsigned DestAS) const {
1599   // Flat -> private/local is a simple truncate.
1600   // Flat -> global is no-op
1601   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1602     return true;
1603 
1604   const GCNTargetMachine &TM =
1605       static_cast<const GCNTargetMachine &>(getTargetMachine());
1606   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1607 }
1608 
1609 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1610   const MemSDNode *MemNode = cast<MemSDNode>(N);
1611 
1612   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1613 }
1614 
1615 TargetLoweringBase::LegalizeTypeAction
1616 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1617   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1618       VT.getScalarType().bitsLE(MVT::i16))
1619     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1620   return TargetLoweringBase::getPreferredVectorAction(VT);
1621 }
1622 
1623 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1624                                                          Type *Ty) const {
1625   // FIXME: Could be smarter if called for vector constants.
1626   return true;
1627 }
1628 
1629 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1630   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1631     switch (Op) {
1632     case ISD::LOAD:
1633     case ISD::STORE:
1634 
1635     // These operations are done with 32-bit instructions anyway.
1636     case ISD::AND:
1637     case ISD::OR:
1638     case ISD::XOR:
1639     case ISD::SELECT:
1640       // TODO: Extensions?
1641       return true;
1642     default:
1643       return false;
1644     }
1645   }
1646 
1647   // SimplifySetCC uses this function to determine whether or not it should
1648   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1649   if (VT == MVT::i1 && Op == ISD::SETCC)
1650     return false;
1651 
1652   return TargetLowering::isTypeDesirableForOp(Op, VT);
1653 }
1654 
1655 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1656                                                    const SDLoc &SL,
1657                                                    SDValue Chain,
1658                                                    uint64_t Offset) const {
1659   const DataLayout &DL = DAG.getDataLayout();
1660   MachineFunction &MF = DAG.getMachineFunction();
1661   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1662 
1663   const ArgDescriptor *InputPtrReg;
1664   const TargetRegisterClass *RC;
1665   LLT ArgTy;
1666   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1667 
1668   std::tie(InputPtrReg, RC, ArgTy) =
1669       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1670 
1671   // We may not have the kernarg segment argument if we have no kernel
1672   // arguments.
1673   if (!InputPtrReg)
1674     return DAG.getConstant(0, SL, PtrVT);
1675 
1676   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1677   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1678     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1679 
1680   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1681 }
1682 
1683 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1684                                             const SDLoc &SL) const {
1685   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1686                                                FIRST_IMPLICIT);
1687   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1688 }
1689 
1690 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1691                                          const SDLoc &SL, SDValue Val,
1692                                          bool Signed,
1693                                          const ISD::InputArg *Arg) const {
1694   // First, if it is a widened vector, narrow it.
1695   if (VT.isVector() &&
1696       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1697     EVT NarrowedVT =
1698         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1699                          VT.getVectorNumElements());
1700     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1701                       DAG.getConstant(0, SL, MVT::i32));
1702   }
1703 
1704   // Then convert the vector elements or scalar value.
1705   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1706       VT.bitsLT(MemVT)) {
1707     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1708     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1709   }
1710 
1711   if (MemVT.isFloatingPoint())
1712     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1713   else if (Signed)
1714     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1715   else
1716     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1717 
1718   return Val;
1719 }
1720 
1721 SDValue SITargetLowering::lowerKernargMemParameter(
1722     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1723     uint64_t Offset, Align Alignment, bool Signed,
1724     const ISD::InputArg *Arg) const {
1725   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1726 
1727   // Try to avoid using an extload by loading earlier than the argument address,
1728   // and extracting the relevant bits. The load should hopefully be merged with
1729   // the previous argument.
1730   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1731     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1732     int64_t AlignDownOffset = alignDown(Offset, 4);
1733     int64_t OffsetDiff = Offset - AlignDownOffset;
1734 
1735     EVT IntVT = MemVT.changeTypeToInteger();
1736 
1737     // TODO: If we passed in the base kernel offset we could have a better
1738     // alignment than 4, but we don't really need it.
1739     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1740     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1741                                MachineMemOperand::MODereferenceable |
1742                                    MachineMemOperand::MOInvariant);
1743 
1744     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1745     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1746 
1747     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1748     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1749     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1750 
1751 
1752     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1753   }
1754 
1755   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1756   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1757                              MachineMemOperand::MODereferenceable |
1758                                  MachineMemOperand::MOInvariant);
1759 
1760   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1761   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1762 }
1763 
1764 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1765                                               const SDLoc &SL, SDValue Chain,
1766                                               const ISD::InputArg &Arg) const {
1767   MachineFunction &MF = DAG.getMachineFunction();
1768   MachineFrameInfo &MFI = MF.getFrameInfo();
1769 
1770   if (Arg.Flags.isByVal()) {
1771     unsigned Size = Arg.Flags.getByValSize();
1772     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1773     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1774   }
1775 
1776   unsigned ArgOffset = VA.getLocMemOffset();
1777   unsigned ArgSize = VA.getValVT().getStoreSize();
1778 
1779   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1780 
1781   // Create load nodes to retrieve arguments from the stack.
1782   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1783   SDValue ArgValue;
1784 
1785   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1786   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1787   MVT MemVT = VA.getValVT();
1788 
1789   switch (VA.getLocInfo()) {
1790   default:
1791     break;
1792   case CCValAssign::BCvt:
1793     MemVT = VA.getLocVT();
1794     break;
1795   case CCValAssign::SExt:
1796     ExtType = ISD::SEXTLOAD;
1797     break;
1798   case CCValAssign::ZExt:
1799     ExtType = ISD::ZEXTLOAD;
1800     break;
1801   case CCValAssign::AExt:
1802     ExtType = ISD::EXTLOAD;
1803     break;
1804   }
1805 
1806   ArgValue = DAG.getExtLoad(
1807     ExtType, SL, VA.getLocVT(), Chain, FIN,
1808     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1809     MemVT);
1810   return ArgValue;
1811 }
1812 
1813 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1814   const SIMachineFunctionInfo &MFI,
1815   EVT VT,
1816   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1817   const ArgDescriptor *Reg;
1818   const TargetRegisterClass *RC;
1819   LLT Ty;
1820 
1821   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1822   if (!Reg) {
1823     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1824       // It's possible for a kernarg intrinsic call to appear in a kernel with
1825       // no allocated segment, in which case we do not add the user sgpr
1826       // argument, so just return null.
1827       return DAG.getConstant(0, SDLoc(), VT);
1828     }
1829 
1830     // It's undefined behavior if a function marked with the amdgpu-no-*
1831     // attributes uses the corresponding intrinsic.
1832     return DAG.getUNDEF(VT);
1833   }
1834 
1835   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1836 }
1837 
1838 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1839                                CallingConv::ID CallConv,
1840                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1841                                FunctionType *FType,
1842                                SIMachineFunctionInfo *Info) {
1843   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1844     const ISD::InputArg *Arg = &Ins[I];
1845 
1846     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1847            "vector type argument should have been split");
1848 
1849     // First check if it's a PS input addr.
1850     if (CallConv == CallingConv::AMDGPU_PS &&
1851         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1852       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1853 
1854       // Inconveniently only the first part of the split is marked as isSplit,
1855       // so skip to the end. We only want to increment PSInputNum once for the
1856       // entire split argument.
1857       if (Arg->Flags.isSplit()) {
1858         while (!Arg->Flags.isSplitEnd()) {
1859           assert((!Arg->VT.isVector() ||
1860                   Arg->VT.getScalarSizeInBits() == 16) &&
1861                  "unexpected vector split in ps argument type");
1862           if (!SkipArg)
1863             Splits.push_back(*Arg);
1864           Arg = &Ins[++I];
1865         }
1866       }
1867 
1868       if (SkipArg) {
1869         // We can safely skip PS inputs.
1870         Skipped.set(Arg->getOrigArgIndex());
1871         ++PSInputNum;
1872         continue;
1873       }
1874 
1875       Info->markPSInputAllocated(PSInputNum);
1876       if (Arg->Used)
1877         Info->markPSInputEnabled(PSInputNum);
1878 
1879       ++PSInputNum;
1880     }
1881 
1882     Splits.push_back(*Arg);
1883   }
1884 }
1885 
1886 // Allocate special inputs passed in VGPRs.
1887 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1888                                                       MachineFunction &MF,
1889                                                       const SIRegisterInfo &TRI,
1890                                                       SIMachineFunctionInfo &Info) const {
1891   const LLT S32 = LLT::scalar(32);
1892   MachineRegisterInfo &MRI = MF.getRegInfo();
1893 
1894   if (Info.hasWorkItemIDX()) {
1895     Register Reg = AMDGPU::VGPR0;
1896     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1897 
1898     CCInfo.AllocateReg(Reg);
1899     unsigned Mask = (Subtarget->hasPackedTID() &&
1900                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1901     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1902   }
1903 
1904   if (Info.hasWorkItemIDY()) {
1905     assert(Info.hasWorkItemIDX());
1906     if (Subtarget->hasPackedTID()) {
1907       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1908                                                         0x3ff << 10));
1909     } else {
1910       unsigned Reg = AMDGPU::VGPR1;
1911       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1912 
1913       CCInfo.AllocateReg(Reg);
1914       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1915     }
1916   }
1917 
1918   if (Info.hasWorkItemIDZ()) {
1919     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1920     if (Subtarget->hasPackedTID()) {
1921       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1922                                                         0x3ff << 20));
1923     } else {
1924       unsigned Reg = AMDGPU::VGPR2;
1925       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1926 
1927       CCInfo.AllocateReg(Reg);
1928       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1929     }
1930   }
1931 }
1932 
1933 // Try to allocate a VGPR at the end of the argument list, or if no argument
1934 // VGPRs are left allocating a stack slot.
1935 // If \p Mask is is given it indicates bitfield position in the register.
1936 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1937 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1938                                          ArgDescriptor Arg = ArgDescriptor()) {
1939   if (Arg.isSet())
1940     return ArgDescriptor::createArg(Arg, Mask);
1941 
1942   ArrayRef<MCPhysReg> ArgVGPRs
1943     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1944   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1945   if (RegIdx == ArgVGPRs.size()) {
1946     // Spill to stack required.
1947     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1948 
1949     return ArgDescriptor::createStack(Offset, Mask);
1950   }
1951 
1952   unsigned Reg = ArgVGPRs[RegIdx];
1953   Reg = CCInfo.AllocateReg(Reg);
1954   assert(Reg != AMDGPU::NoRegister);
1955 
1956   MachineFunction &MF = CCInfo.getMachineFunction();
1957   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1958   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1959   return ArgDescriptor::createRegister(Reg, Mask);
1960 }
1961 
1962 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1963                                              const TargetRegisterClass *RC,
1964                                              unsigned NumArgRegs) {
1965   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1966   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1967   if (RegIdx == ArgSGPRs.size())
1968     report_fatal_error("ran out of SGPRs for arguments");
1969 
1970   unsigned Reg = ArgSGPRs[RegIdx];
1971   Reg = CCInfo.AllocateReg(Reg);
1972   assert(Reg != AMDGPU::NoRegister);
1973 
1974   MachineFunction &MF = CCInfo.getMachineFunction();
1975   MF.addLiveIn(Reg, RC);
1976   return ArgDescriptor::createRegister(Reg);
1977 }
1978 
1979 // If this has a fixed position, we still should allocate the register in the
1980 // CCInfo state. Technically we could get away with this for values passed
1981 // outside of the normal argument range.
1982 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1983                                        const TargetRegisterClass *RC,
1984                                        MCRegister Reg) {
1985   Reg = CCInfo.AllocateReg(Reg);
1986   assert(Reg != AMDGPU::NoRegister);
1987   MachineFunction &MF = CCInfo.getMachineFunction();
1988   MF.addLiveIn(Reg, RC);
1989 }
1990 
1991 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1992   if (Arg) {
1993     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1994                                Arg.getRegister());
1995   } else
1996     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1997 }
1998 
1999 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2000   if (Arg) {
2001     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2002                                Arg.getRegister());
2003   } else
2004     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2005 }
2006 
2007 /// Allocate implicit function VGPR arguments at the end of allocated user
2008 /// arguments.
2009 void SITargetLowering::allocateSpecialInputVGPRs(
2010   CCState &CCInfo, MachineFunction &MF,
2011   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2012   const unsigned Mask = 0x3ff;
2013   ArgDescriptor Arg;
2014 
2015   if (Info.hasWorkItemIDX()) {
2016     Arg = allocateVGPR32Input(CCInfo, Mask);
2017     Info.setWorkItemIDX(Arg);
2018   }
2019 
2020   if (Info.hasWorkItemIDY()) {
2021     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2022     Info.setWorkItemIDY(Arg);
2023   }
2024 
2025   if (Info.hasWorkItemIDZ())
2026     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2027 }
2028 
2029 /// Allocate implicit function VGPR arguments in fixed registers.
2030 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2031   CCState &CCInfo, MachineFunction &MF,
2032   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2033   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2034   if (!Reg)
2035     report_fatal_error("failed to allocated VGPR for implicit arguments");
2036 
2037   const unsigned Mask = 0x3ff;
2038   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2039   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2040   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2041 }
2042 
2043 void SITargetLowering::allocateSpecialInputSGPRs(
2044   CCState &CCInfo,
2045   MachineFunction &MF,
2046   const SIRegisterInfo &TRI,
2047   SIMachineFunctionInfo &Info) const {
2048   auto &ArgInfo = Info.getArgInfo();
2049 
2050   // We need to allocate these in place regardless of their use.
2051   const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI;
2052 
2053   // TODO: Unify handling with private memory pointers.
2054   if (IsFixed || Info.hasDispatchPtr())
2055     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2056 
2057   if (IsFixed || Info.hasQueuePtr())
2058     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2059 
2060   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2061   // constant offset from the kernarg segment.
2062   if (IsFixed || Info.hasImplicitArgPtr())
2063     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2064 
2065   if (IsFixed || Info.hasDispatchID())
2066     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2067 
2068   // flat_scratch_init is not applicable for non-kernel functions.
2069 
2070   if (IsFixed || Info.hasWorkGroupIDX())
2071     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2072 
2073   if (IsFixed || Info.hasWorkGroupIDY())
2074     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2075 
2076   if (IsFixed || Info.hasWorkGroupIDZ())
2077     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2078 }
2079 
2080 // Allocate special inputs passed in user SGPRs.
2081 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2082                                             MachineFunction &MF,
2083                                             const SIRegisterInfo &TRI,
2084                                             SIMachineFunctionInfo &Info) const {
2085   if (Info.hasImplicitBufferPtr()) {
2086     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2087     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2088     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2089   }
2090 
2091   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2092   if (Info.hasPrivateSegmentBuffer()) {
2093     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2094     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2095     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2096   }
2097 
2098   if (Info.hasDispatchPtr()) {
2099     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2100     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2101     CCInfo.AllocateReg(DispatchPtrReg);
2102   }
2103 
2104   if (Info.hasQueuePtr()) {
2105     Register QueuePtrReg = Info.addQueuePtr(TRI);
2106     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2107     CCInfo.AllocateReg(QueuePtrReg);
2108   }
2109 
2110   if (Info.hasKernargSegmentPtr()) {
2111     MachineRegisterInfo &MRI = MF.getRegInfo();
2112     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2113     CCInfo.AllocateReg(InputPtrReg);
2114 
2115     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2116     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2117   }
2118 
2119   if (Info.hasDispatchID()) {
2120     Register DispatchIDReg = Info.addDispatchID(TRI);
2121     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2122     CCInfo.AllocateReg(DispatchIDReg);
2123   }
2124 
2125   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2126     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2127     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2128     CCInfo.AllocateReg(FlatScratchInitReg);
2129   }
2130 
2131   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2132   // these from the dispatch pointer.
2133 }
2134 
2135 // Allocate special input registers that are initialized per-wave.
2136 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2137                                            MachineFunction &MF,
2138                                            SIMachineFunctionInfo &Info,
2139                                            CallingConv::ID CallConv,
2140                                            bool IsShader) const {
2141   if (Info.hasWorkGroupIDX()) {
2142     Register Reg = Info.addWorkGroupIDX();
2143     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2144     CCInfo.AllocateReg(Reg);
2145   }
2146 
2147   if (Info.hasWorkGroupIDY()) {
2148     Register Reg = Info.addWorkGroupIDY();
2149     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2150     CCInfo.AllocateReg(Reg);
2151   }
2152 
2153   if (Info.hasWorkGroupIDZ()) {
2154     Register Reg = Info.addWorkGroupIDZ();
2155     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2156     CCInfo.AllocateReg(Reg);
2157   }
2158 
2159   if (Info.hasWorkGroupInfo()) {
2160     Register Reg = Info.addWorkGroupInfo();
2161     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2162     CCInfo.AllocateReg(Reg);
2163   }
2164 
2165   if (Info.hasPrivateSegmentWaveByteOffset()) {
2166     // Scratch wave offset passed in system SGPR.
2167     unsigned PrivateSegmentWaveByteOffsetReg;
2168 
2169     if (IsShader) {
2170       PrivateSegmentWaveByteOffsetReg =
2171         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2172 
2173       // This is true if the scratch wave byte offset doesn't have a fixed
2174       // location.
2175       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2176         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2177         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2178       }
2179     } else
2180       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2181 
2182     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2183     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2184   }
2185 }
2186 
2187 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2188                                      MachineFunction &MF,
2189                                      const SIRegisterInfo &TRI,
2190                                      SIMachineFunctionInfo &Info) {
2191   // Now that we've figured out where the scratch register inputs are, see if
2192   // should reserve the arguments and use them directly.
2193   MachineFrameInfo &MFI = MF.getFrameInfo();
2194   bool HasStackObjects = MFI.hasStackObjects();
2195   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2196 
2197   // Record that we know we have non-spill stack objects so we don't need to
2198   // check all stack objects later.
2199   if (HasStackObjects)
2200     Info.setHasNonSpillStackObjects(true);
2201 
2202   // Everything live out of a block is spilled with fast regalloc, so it's
2203   // almost certain that spilling will be required.
2204   if (TM.getOptLevel() == CodeGenOpt::None)
2205     HasStackObjects = true;
2206 
2207   // For now assume stack access is needed in any callee functions, so we need
2208   // the scratch registers to pass in.
2209   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2210 
2211   if (!ST.enableFlatScratch()) {
2212     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2213       // If we have stack objects, we unquestionably need the private buffer
2214       // resource. For the Code Object V2 ABI, this will be the first 4 user
2215       // SGPR inputs. We can reserve those and use them directly.
2216 
2217       Register PrivateSegmentBufferReg =
2218           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2219       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2220     } else {
2221       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2222       // We tentatively reserve the last registers (skipping the last registers
2223       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2224       // we'll replace these with the ones immediately after those which were
2225       // really allocated. In the prologue copies will be inserted from the
2226       // argument to these reserved registers.
2227 
2228       // Without HSA, relocations are used for the scratch pointer and the
2229       // buffer resource setup is always inserted in the prologue. Scratch wave
2230       // offset is still in an input SGPR.
2231       Info.setScratchRSrcReg(ReservedBufferReg);
2232     }
2233   }
2234 
2235   MachineRegisterInfo &MRI = MF.getRegInfo();
2236 
2237   // For entry functions we have to set up the stack pointer if we use it,
2238   // whereas non-entry functions get this "for free". This means there is no
2239   // intrinsic advantage to using S32 over S34 in cases where we do not have
2240   // calls but do need a frame pointer (i.e. if we are requested to have one
2241   // because frame pointer elimination is disabled). To keep things simple we
2242   // only ever use S32 as the call ABI stack pointer, and so using it does not
2243   // imply we need a separate frame pointer.
2244   //
2245   // Try to use s32 as the SP, but move it if it would interfere with input
2246   // arguments. This won't work with calls though.
2247   //
2248   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2249   // registers.
2250   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2251     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2252   } else {
2253     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2254 
2255     if (MFI.hasCalls())
2256       report_fatal_error("call in graphics shader with too many input SGPRs");
2257 
2258     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2259       if (!MRI.isLiveIn(Reg)) {
2260         Info.setStackPtrOffsetReg(Reg);
2261         break;
2262       }
2263     }
2264 
2265     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2266       report_fatal_error("failed to find register for SP");
2267   }
2268 
2269   // hasFP should be accurate for entry functions even before the frame is
2270   // finalized, because it does not rely on the known stack size, only
2271   // properties like whether variable sized objects are present.
2272   if (ST.getFrameLowering()->hasFP(MF)) {
2273     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2274   }
2275 }
2276 
2277 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2278   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2279   return !Info->isEntryFunction();
2280 }
2281 
2282 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2283 
2284 }
2285 
2286 void SITargetLowering::insertCopiesSplitCSR(
2287   MachineBasicBlock *Entry,
2288   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2289   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2290 
2291   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2292   if (!IStart)
2293     return;
2294 
2295   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2296   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2297   MachineBasicBlock::iterator MBBI = Entry->begin();
2298   for (const MCPhysReg *I = IStart; *I; ++I) {
2299     const TargetRegisterClass *RC = nullptr;
2300     if (AMDGPU::SReg_64RegClass.contains(*I))
2301       RC = &AMDGPU::SGPR_64RegClass;
2302     else if (AMDGPU::SReg_32RegClass.contains(*I))
2303       RC = &AMDGPU::SGPR_32RegClass;
2304     else
2305       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2306 
2307     Register NewVR = MRI->createVirtualRegister(RC);
2308     // Create copy from CSR to a virtual register.
2309     Entry->addLiveIn(*I);
2310     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2311       .addReg(*I);
2312 
2313     // Insert the copy-back instructions right before the terminator.
2314     for (auto *Exit : Exits)
2315       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2316               TII->get(TargetOpcode::COPY), *I)
2317         .addReg(NewVR);
2318   }
2319 }
2320 
2321 SDValue SITargetLowering::LowerFormalArguments(
2322     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2323     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2324     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2325   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2326 
2327   MachineFunction &MF = DAG.getMachineFunction();
2328   const Function &Fn = MF.getFunction();
2329   FunctionType *FType = MF.getFunction().getFunctionType();
2330   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2331 
2332   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2333     DiagnosticInfoUnsupported NoGraphicsHSA(
2334         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2335     DAG.getContext()->diagnose(NoGraphicsHSA);
2336     return DAG.getEntryNode();
2337   }
2338 
2339   Info->allocateModuleLDSGlobal(Fn.getParent());
2340 
2341   SmallVector<ISD::InputArg, 16> Splits;
2342   SmallVector<CCValAssign, 16> ArgLocs;
2343   BitVector Skipped(Ins.size());
2344   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2345                  *DAG.getContext());
2346 
2347   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2348   bool IsKernel = AMDGPU::isKernel(CallConv);
2349   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2350 
2351   if (IsGraphics) {
2352     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2353            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2354            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2355            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2356            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2357            !Info->hasWorkItemIDZ());
2358   }
2359 
2360   if (CallConv == CallingConv::AMDGPU_PS) {
2361     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2362 
2363     // At least one interpolation mode must be enabled or else the GPU will
2364     // hang.
2365     //
2366     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2367     // set PSInputAddr, the user wants to enable some bits after the compilation
2368     // based on run-time states. Since we can't know what the final PSInputEna
2369     // will look like, so we shouldn't do anything here and the user should take
2370     // responsibility for the correct programming.
2371     //
2372     // Otherwise, the following restrictions apply:
2373     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2374     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2375     //   enabled too.
2376     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2377         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2378       CCInfo.AllocateReg(AMDGPU::VGPR0);
2379       CCInfo.AllocateReg(AMDGPU::VGPR1);
2380       Info->markPSInputAllocated(0);
2381       Info->markPSInputEnabled(0);
2382     }
2383     if (Subtarget->isAmdPalOS()) {
2384       // For isAmdPalOS, the user does not enable some bits after compilation
2385       // based on run-time states; the register values being generated here are
2386       // the final ones set in hardware. Therefore we need to apply the
2387       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2388       // a bit is set in PSInputAddr but not PSInputEnable is where the
2389       // frontend set up an input arg for a particular interpolation mode, but
2390       // nothing uses that input arg. Really we should have an earlier pass
2391       // that removes such an arg.)
2392       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2393       if ((PsInputBits & 0x7F) == 0 ||
2394           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2395         Info->markPSInputEnabled(
2396             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2397     }
2398   } else if (IsKernel) {
2399     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2400   } else {
2401     Splits.append(Ins.begin(), Ins.end());
2402   }
2403 
2404   if (IsEntryFunc) {
2405     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2406     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2407   } else {
2408     // For the fixed ABI, pass workitem IDs in the last argument register.
2409     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2410       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2411   }
2412 
2413   if (IsKernel) {
2414     analyzeFormalArgumentsCompute(CCInfo, Ins);
2415   } else {
2416     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2417     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2418   }
2419 
2420   SmallVector<SDValue, 16> Chains;
2421 
2422   // FIXME: This is the minimum kernel argument alignment. We should improve
2423   // this to the maximum alignment of the arguments.
2424   //
2425   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2426   // kern arg offset.
2427   const Align KernelArgBaseAlign = Align(16);
2428 
2429   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2430     const ISD::InputArg &Arg = Ins[i];
2431     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2432       InVals.push_back(DAG.getUNDEF(Arg.VT));
2433       continue;
2434     }
2435 
2436     CCValAssign &VA = ArgLocs[ArgIdx++];
2437     MVT VT = VA.getLocVT();
2438 
2439     if (IsEntryFunc && VA.isMemLoc()) {
2440       VT = Ins[i].VT;
2441       EVT MemVT = VA.getLocVT();
2442 
2443       const uint64_t Offset = VA.getLocMemOffset();
2444       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2445 
2446       if (Arg.Flags.isByRef()) {
2447         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2448 
2449         const GCNTargetMachine &TM =
2450             static_cast<const GCNTargetMachine &>(getTargetMachine());
2451         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2452                                     Arg.Flags.getPointerAddrSpace())) {
2453           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2454                                      Arg.Flags.getPointerAddrSpace());
2455         }
2456 
2457         InVals.push_back(Ptr);
2458         continue;
2459       }
2460 
2461       SDValue Arg = lowerKernargMemParameter(
2462         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2463       Chains.push_back(Arg.getValue(1));
2464 
2465       auto *ParamTy =
2466         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2467       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2468           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2469                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2470         // On SI local pointers are just offsets into LDS, so they are always
2471         // less than 16-bits.  On CI and newer they could potentially be
2472         // real pointers, so we can't guarantee their size.
2473         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2474                           DAG.getValueType(MVT::i16));
2475       }
2476 
2477       InVals.push_back(Arg);
2478       continue;
2479     } else if (!IsEntryFunc && VA.isMemLoc()) {
2480       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2481       InVals.push_back(Val);
2482       if (!Arg.Flags.isByVal())
2483         Chains.push_back(Val.getValue(1));
2484       continue;
2485     }
2486 
2487     assert(VA.isRegLoc() && "Parameter must be in a register!");
2488 
2489     Register Reg = VA.getLocReg();
2490     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2491     EVT ValVT = VA.getValVT();
2492 
2493     Reg = MF.addLiveIn(Reg, RC);
2494     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2495 
2496     if (Arg.Flags.isSRet()) {
2497       // The return object should be reasonably addressable.
2498 
2499       // FIXME: This helps when the return is a real sret. If it is a
2500       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2501       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2502       unsigned NumBits
2503         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2504       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2505         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2506     }
2507 
2508     // If this is an 8 or 16-bit value, it is really passed promoted
2509     // to 32 bits. Insert an assert[sz]ext to capture this, then
2510     // truncate to the right size.
2511     switch (VA.getLocInfo()) {
2512     case CCValAssign::Full:
2513       break;
2514     case CCValAssign::BCvt:
2515       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2516       break;
2517     case CCValAssign::SExt:
2518       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2519                         DAG.getValueType(ValVT));
2520       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2521       break;
2522     case CCValAssign::ZExt:
2523       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2524                         DAG.getValueType(ValVT));
2525       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2526       break;
2527     case CCValAssign::AExt:
2528       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2529       break;
2530     default:
2531       llvm_unreachable("Unknown loc info!");
2532     }
2533 
2534     InVals.push_back(Val);
2535   }
2536 
2537   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2538     // Special inputs come after user arguments.
2539     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2540   }
2541 
2542   // Start adding system SGPRs.
2543   if (IsEntryFunc) {
2544     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2545   } else {
2546     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2547     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2548   }
2549 
2550   auto &ArgUsageInfo =
2551     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2552   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2553 
2554   unsigned StackArgSize = CCInfo.getNextStackOffset();
2555   Info->setBytesInStackArgArea(StackArgSize);
2556 
2557   return Chains.empty() ? Chain :
2558     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2559 }
2560 
2561 // TODO: If return values can't fit in registers, we should return as many as
2562 // possible in registers before passing on stack.
2563 bool SITargetLowering::CanLowerReturn(
2564   CallingConv::ID CallConv,
2565   MachineFunction &MF, bool IsVarArg,
2566   const SmallVectorImpl<ISD::OutputArg> &Outs,
2567   LLVMContext &Context) const {
2568   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2569   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2570   // for shaders. Vector types should be explicitly handled by CC.
2571   if (AMDGPU::isEntryFunctionCC(CallConv))
2572     return true;
2573 
2574   SmallVector<CCValAssign, 16> RVLocs;
2575   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2576   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2577 }
2578 
2579 SDValue
2580 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2581                               bool isVarArg,
2582                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2583                               const SmallVectorImpl<SDValue> &OutVals,
2584                               const SDLoc &DL, SelectionDAG &DAG) const {
2585   MachineFunction &MF = DAG.getMachineFunction();
2586   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2587 
2588   if (AMDGPU::isKernel(CallConv)) {
2589     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2590                                              OutVals, DL, DAG);
2591   }
2592 
2593   bool IsShader = AMDGPU::isShader(CallConv);
2594 
2595   Info->setIfReturnsVoid(Outs.empty());
2596   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2597 
2598   // CCValAssign - represent the assignment of the return value to a location.
2599   SmallVector<CCValAssign, 48> RVLocs;
2600   SmallVector<ISD::OutputArg, 48> Splits;
2601 
2602   // CCState - Info about the registers and stack slots.
2603   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2604                  *DAG.getContext());
2605 
2606   // Analyze outgoing return values.
2607   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2608 
2609   SDValue Flag;
2610   SmallVector<SDValue, 48> RetOps;
2611   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2612 
2613   // Add return address for callable functions.
2614   if (!Info->isEntryFunction()) {
2615     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2616     SDValue ReturnAddrReg = CreateLiveInRegister(
2617       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2618 
2619     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2620         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2621         MVT::i64);
2622     Chain =
2623         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2624     Flag = Chain.getValue(1);
2625     RetOps.push_back(ReturnAddrVirtualReg);
2626   }
2627 
2628   // Copy the result values into the output registers.
2629   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2630        ++I, ++RealRVLocIdx) {
2631     CCValAssign &VA = RVLocs[I];
2632     assert(VA.isRegLoc() && "Can only return in registers!");
2633     // TODO: Partially return in registers if return values don't fit.
2634     SDValue Arg = OutVals[RealRVLocIdx];
2635 
2636     // Copied from other backends.
2637     switch (VA.getLocInfo()) {
2638     case CCValAssign::Full:
2639       break;
2640     case CCValAssign::BCvt:
2641       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2642       break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2651       break;
2652     default:
2653       llvm_unreachable("Unknown loc info!");
2654     }
2655 
2656     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2657     Flag = Chain.getValue(1);
2658     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2659   }
2660 
2661   // FIXME: Does sret work properly?
2662   if (!Info->isEntryFunction()) {
2663     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2664     const MCPhysReg *I =
2665       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2666     if (I) {
2667       for (; *I; ++I) {
2668         if (AMDGPU::SReg_64RegClass.contains(*I))
2669           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2670         else if (AMDGPU::SReg_32RegClass.contains(*I))
2671           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2672         else
2673           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2674       }
2675     }
2676   }
2677 
2678   // Update chain and glue.
2679   RetOps[0] = Chain;
2680   if (Flag.getNode())
2681     RetOps.push_back(Flag);
2682 
2683   unsigned Opc = AMDGPUISD::ENDPGM;
2684   if (!IsWaveEnd)
2685     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2686   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2687 }
2688 
2689 SDValue SITargetLowering::LowerCallResult(
2690     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2691     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2692     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2693     SDValue ThisVal) const {
2694   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2695 
2696   // Assign locations to each value returned by this call.
2697   SmallVector<CCValAssign, 16> RVLocs;
2698   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2699                  *DAG.getContext());
2700   CCInfo.AnalyzeCallResult(Ins, RetCC);
2701 
2702   // Copy all of the result registers out of their specified physreg.
2703   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2704     CCValAssign VA = RVLocs[i];
2705     SDValue Val;
2706 
2707     if (VA.isRegLoc()) {
2708       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2709       Chain = Val.getValue(1);
2710       InFlag = Val.getValue(2);
2711     } else if (VA.isMemLoc()) {
2712       report_fatal_error("TODO: return values in memory");
2713     } else
2714       llvm_unreachable("unknown argument location type");
2715 
2716     switch (VA.getLocInfo()) {
2717     case CCValAssign::Full:
2718       break;
2719     case CCValAssign::BCvt:
2720       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2721       break;
2722     case CCValAssign::ZExt:
2723       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2724                         DAG.getValueType(VA.getValVT()));
2725       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2726       break;
2727     case CCValAssign::SExt:
2728       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2729                         DAG.getValueType(VA.getValVT()));
2730       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2731       break;
2732     case CCValAssign::AExt:
2733       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2734       break;
2735     default:
2736       llvm_unreachable("Unknown loc info!");
2737     }
2738 
2739     InVals.push_back(Val);
2740   }
2741 
2742   return Chain;
2743 }
2744 
2745 // Add code to pass special inputs required depending on used features separate
2746 // from the explicit user arguments present in the IR.
2747 void SITargetLowering::passSpecialInputs(
2748     CallLoweringInfo &CLI,
2749     CCState &CCInfo,
2750     const SIMachineFunctionInfo &Info,
2751     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2752     SmallVectorImpl<SDValue> &MemOpChains,
2753     SDValue Chain) const {
2754   // If we don't have a call site, this was a call inserted by
2755   // legalization. These can never use special inputs.
2756   if (!CLI.CB)
2757     return;
2758 
2759   SelectionDAG &DAG = CLI.DAG;
2760   const SDLoc &DL = CLI.DL;
2761 
2762   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2763   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2764 
2765   const AMDGPUFunctionArgInfo *CalleeArgInfo
2766     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2767   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2768     auto &ArgUsageInfo =
2769       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2770     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2771   }
2772 
2773   // TODO: Unify with private memory register handling. This is complicated by
2774   // the fact that at least in kernels, the input argument is not necessarily
2775   // in the same location as the input.
2776   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2777                              StringLiteral> ImplicitAttrs[] = {
2778     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2779     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2780     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2781     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2782     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2783     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2784     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2785   };
2786 
2787   for (auto Attr : ImplicitAttrs) {
2788     const ArgDescriptor *OutgoingArg;
2789     const TargetRegisterClass *ArgRC;
2790     LLT ArgTy;
2791 
2792     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2793 
2794     // If the callee does not use the attribute value, skip copying the value.
2795     if (CLI.CB->hasFnAttr(Attr.second))
2796       continue;
2797 
2798     std::tie(OutgoingArg, ArgRC, ArgTy) =
2799         CalleeArgInfo->getPreloadedValue(InputID);
2800     if (!OutgoingArg)
2801       continue;
2802 
2803     const ArgDescriptor *IncomingArg;
2804     const TargetRegisterClass *IncomingArgRC;
2805     LLT Ty;
2806     std::tie(IncomingArg, IncomingArgRC, Ty) =
2807         CallerArgInfo.getPreloadedValue(InputID);
2808     assert(IncomingArgRC == ArgRC);
2809 
2810     // All special arguments are ints for now.
2811     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2812     SDValue InputReg;
2813 
2814     if (IncomingArg) {
2815       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2816     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2817       // The implicit arg ptr is special because it doesn't have a corresponding
2818       // input for kernels, and is computed from the kernarg segment pointer.
2819       InputReg = getImplicitArgPtr(DAG, DL);
2820     } else {
2821       // We may have proven the input wasn't needed, although the ABI is
2822       // requiring it. We just need to allocate the register appropriately.
2823       InputReg = DAG.getUNDEF(ArgVT);
2824     }
2825 
2826     if (OutgoingArg->isRegister()) {
2827       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2828       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2829         report_fatal_error("failed to allocate implicit input argument");
2830     } else {
2831       unsigned SpecialArgOffset =
2832           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2833       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2834                                               SpecialArgOffset);
2835       MemOpChains.push_back(ArgStore);
2836     }
2837   }
2838 
2839   // Pack workitem IDs into a single register or pass it as is if already
2840   // packed.
2841   const ArgDescriptor *OutgoingArg;
2842   const TargetRegisterClass *ArgRC;
2843   LLT Ty;
2844 
2845   std::tie(OutgoingArg, ArgRC, Ty) =
2846       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2847   if (!OutgoingArg)
2848     std::tie(OutgoingArg, ArgRC, Ty) =
2849         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2850   if (!OutgoingArg)
2851     std::tie(OutgoingArg, ArgRC, Ty) =
2852         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2853   if (!OutgoingArg)
2854     return;
2855 
2856   const ArgDescriptor *IncomingArgX = std::get<0>(
2857       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2858   const ArgDescriptor *IncomingArgY = std::get<0>(
2859       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2860   const ArgDescriptor *IncomingArgZ = std::get<0>(
2861       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2862 
2863   SDValue InputReg;
2864   SDLoc SL;
2865 
2866   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2867   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2868   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2869 
2870   // If incoming ids are not packed we need to pack them.
2871   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2872       NeedWorkItemIDX)
2873     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2874 
2875   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2876       NeedWorkItemIDY) {
2877     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2878     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2879                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2880     InputReg = InputReg.getNode() ?
2881                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2882   }
2883 
2884   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2885       NeedWorkItemIDZ) {
2886     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2887     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2888                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2889     InputReg = InputReg.getNode() ?
2890                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2891   }
2892 
2893   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2894     // Workitem ids are already packed, any of present incoming arguments
2895     // will carry all required fields.
2896     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2897       IncomingArgX ? *IncomingArgX :
2898       IncomingArgY ? *IncomingArgY :
2899                      *IncomingArgZ, ~0u);
2900     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2901   }
2902 
2903   if (OutgoingArg->isRegister()) {
2904     if (InputReg)
2905       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2906 
2907     CCInfo.AllocateReg(OutgoingArg->getRegister());
2908   } else {
2909     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2910     if (InputReg) {
2911       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2912                                               SpecialArgOffset);
2913       MemOpChains.push_back(ArgStore);
2914     }
2915   }
2916 }
2917 
2918 static bool canGuaranteeTCO(CallingConv::ID CC) {
2919   return CC == CallingConv::Fast;
2920 }
2921 
2922 /// Return true if we might ever do TCO for calls with this calling convention.
2923 static bool mayTailCallThisCC(CallingConv::ID CC) {
2924   switch (CC) {
2925   case CallingConv::C:
2926   case CallingConv::AMDGPU_Gfx:
2927     return true;
2928   default:
2929     return canGuaranteeTCO(CC);
2930   }
2931 }
2932 
2933 bool SITargetLowering::isEligibleForTailCallOptimization(
2934     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2935     const SmallVectorImpl<ISD::OutputArg> &Outs,
2936     const SmallVectorImpl<SDValue> &OutVals,
2937     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2938   if (!mayTailCallThisCC(CalleeCC))
2939     return false;
2940 
2941   // For a divergent call target, we need to do a waterfall loop over the
2942   // possible callees which precludes us from using a simple jump.
2943   if (Callee->isDivergent())
2944     return false;
2945 
2946   MachineFunction &MF = DAG.getMachineFunction();
2947   const Function &CallerF = MF.getFunction();
2948   CallingConv::ID CallerCC = CallerF.getCallingConv();
2949   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2950   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2951 
2952   // Kernels aren't callable, and don't have a live in return address so it
2953   // doesn't make sense to do a tail call with entry functions.
2954   if (!CallerPreserved)
2955     return false;
2956 
2957   bool CCMatch = CallerCC == CalleeCC;
2958 
2959   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2960     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2961       return true;
2962     return false;
2963   }
2964 
2965   // TODO: Can we handle var args?
2966   if (IsVarArg)
2967     return false;
2968 
2969   for (const Argument &Arg : CallerF.args()) {
2970     if (Arg.hasByValAttr())
2971       return false;
2972   }
2973 
2974   LLVMContext &Ctx = *DAG.getContext();
2975 
2976   // Check that the call results are passed in the same way.
2977   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2978                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2979                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2980     return false;
2981 
2982   // The callee has to preserve all registers the caller needs to preserve.
2983   if (!CCMatch) {
2984     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2985     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2986       return false;
2987   }
2988 
2989   // Nothing more to check if the callee is taking no arguments.
2990   if (Outs.empty())
2991     return true;
2992 
2993   SmallVector<CCValAssign, 16> ArgLocs;
2994   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2995 
2996   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2997 
2998   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2999   // If the stack arguments for this call do not fit into our own save area then
3000   // the call cannot be made tail.
3001   // TODO: Is this really necessary?
3002   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3003     return false;
3004 
3005   const MachineRegisterInfo &MRI = MF.getRegInfo();
3006   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3007 }
3008 
3009 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3010   if (!CI->isTailCall())
3011     return false;
3012 
3013   const Function *ParentFn = CI->getParent()->getParent();
3014   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3015     return false;
3016   return true;
3017 }
3018 
3019 // The wave scratch offset register is used as the global base pointer.
3020 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3021                                     SmallVectorImpl<SDValue> &InVals) const {
3022   SelectionDAG &DAG = CLI.DAG;
3023   const SDLoc &DL = CLI.DL;
3024   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3025   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3026   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3027   SDValue Chain = CLI.Chain;
3028   SDValue Callee = CLI.Callee;
3029   bool &IsTailCall = CLI.IsTailCall;
3030   CallingConv::ID CallConv = CLI.CallConv;
3031   bool IsVarArg = CLI.IsVarArg;
3032   bool IsSibCall = false;
3033   bool IsThisReturn = false;
3034   MachineFunction &MF = DAG.getMachineFunction();
3035 
3036   if (Callee.isUndef() || isNullConstant(Callee)) {
3037     if (!CLI.IsTailCall) {
3038       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3039         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3040     }
3041 
3042     return Chain;
3043   }
3044 
3045   if (IsVarArg) {
3046     return lowerUnhandledCall(CLI, InVals,
3047                               "unsupported call to variadic function ");
3048   }
3049 
3050   if (!CLI.CB)
3051     report_fatal_error("unsupported libcall legalization");
3052 
3053   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3054     return lowerUnhandledCall(CLI, InVals,
3055                               "unsupported required tail call to function ");
3056   }
3057 
3058   if (AMDGPU::isShader(CallConv)) {
3059     // Note the issue is with the CC of the called function, not of the call
3060     // itself.
3061     return lowerUnhandledCall(CLI, InVals,
3062                               "unsupported call to a shader function ");
3063   }
3064 
3065   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3066       CallConv != CallingConv::AMDGPU_Gfx) {
3067     // Only allow calls with specific calling conventions.
3068     return lowerUnhandledCall(CLI, InVals,
3069                               "unsupported calling convention for call from "
3070                               "graphics shader of function ");
3071   }
3072 
3073   if (IsTailCall) {
3074     IsTailCall = isEligibleForTailCallOptimization(
3075       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3076     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3077       report_fatal_error("failed to perform tail call elimination on a call "
3078                          "site marked musttail");
3079     }
3080 
3081     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3082 
3083     // A sibling call is one where we're under the usual C ABI and not planning
3084     // to change that but can still do a tail call:
3085     if (!TailCallOpt && IsTailCall)
3086       IsSibCall = true;
3087 
3088     if (IsTailCall)
3089       ++NumTailCalls;
3090   }
3091 
3092   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3093   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3094   SmallVector<SDValue, 8> MemOpChains;
3095 
3096   // Analyze operands of the call, assigning locations to each operand.
3097   SmallVector<CCValAssign, 16> ArgLocs;
3098   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3099   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3100 
3101   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3102       CallConv != CallingConv::AMDGPU_Gfx) {
3103     // With a fixed ABI, allocate fixed registers before user arguments.
3104     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3105   }
3106 
3107   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3108 
3109   // Get a count of how many bytes are to be pushed on the stack.
3110   unsigned NumBytes = CCInfo.getNextStackOffset();
3111 
3112   if (IsSibCall) {
3113     // Since we're not changing the ABI to make this a tail call, the memory
3114     // operands are already available in the caller's incoming argument space.
3115     NumBytes = 0;
3116   }
3117 
3118   // FPDiff is the byte offset of the call's argument area from the callee's.
3119   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3120   // by this amount for a tail call. In a sibling call it must be 0 because the
3121   // caller will deallocate the entire stack and the callee still expects its
3122   // arguments to begin at SP+0. Completely unused for non-tail calls.
3123   int32_t FPDiff = 0;
3124   MachineFrameInfo &MFI = MF.getFrameInfo();
3125 
3126   // Adjust the stack pointer for the new arguments...
3127   // These operations are automatically eliminated by the prolog/epilog pass
3128   if (!IsSibCall) {
3129     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3130 
3131     if (!Subtarget->enableFlatScratch()) {
3132       SmallVector<SDValue, 4> CopyFromChains;
3133 
3134       // In the HSA case, this should be an identity copy.
3135       SDValue ScratchRSrcReg
3136         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3137       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3138       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3139       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3140     }
3141   }
3142 
3143   MVT PtrVT = MVT::i32;
3144 
3145   // Walk the register/memloc assignments, inserting copies/loads.
3146   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3147     CCValAssign &VA = ArgLocs[i];
3148     SDValue Arg = OutVals[i];
3149 
3150     // Promote the value if needed.
3151     switch (VA.getLocInfo()) {
3152     case CCValAssign::Full:
3153       break;
3154     case CCValAssign::BCvt:
3155       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3156       break;
3157     case CCValAssign::ZExt:
3158       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3159       break;
3160     case CCValAssign::SExt:
3161       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3162       break;
3163     case CCValAssign::AExt:
3164       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3165       break;
3166     case CCValAssign::FPExt:
3167       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3168       break;
3169     default:
3170       llvm_unreachable("Unknown loc info!");
3171     }
3172 
3173     if (VA.isRegLoc()) {
3174       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3175     } else {
3176       assert(VA.isMemLoc());
3177 
3178       SDValue DstAddr;
3179       MachinePointerInfo DstInfo;
3180 
3181       unsigned LocMemOffset = VA.getLocMemOffset();
3182       int32_t Offset = LocMemOffset;
3183 
3184       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3185       MaybeAlign Alignment;
3186 
3187       if (IsTailCall) {
3188         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3189         unsigned OpSize = Flags.isByVal() ?
3190           Flags.getByValSize() : VA.getValVT().getStoreSize();
3191 
3192         // FIXME: We can have better than the minimum byval required alignment.
3193         Alignment =
3194             Flags.isByVal()
3195                 ? Flags.getNonZeroByValAlign()
3196                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3197 
3198         Offset = Offset + FPDiff;
3199         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3200 
3201         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3202         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3203 
3204         // Make sure any stack arguments overlapping with where we're storing
3205         // are loaded before this eventual operation. Otherwise they'll be
3206         // clobbered.
3207 
3208         // FIXME: Why is this really necessary? This seems to just result in a
3209         // lot of code to copy the stack and write them back to the same
3210         // locations, which are supposed to be immutable?
3211         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3212       } else {
3213         // Stores to the argument stack area are relative to the stack pointer.
3214         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3215                                         MVT::i32);
3216         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3217         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3218         Alignment =
3219             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3220       }
3221 
3222       if (Outs[i].Flags.isByVal()) {
3223         SDValue SizeNode =
3224             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3225         SDValue Cpy =
3226             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3227                           Outs[i].Flags.getNonZeroByValAlign(),
3228                           /*isVol = */ false, /*AlwaysInline = */ true,
3229                           /*isTailCall = */ false, DstInfo,
3230                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3231 
3232         MemOpChains.push_back(Cpy);
3233       } else {
3234         SDValue Store =
3235             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3236         MemOpChains.push_back(Store);
3237       }
3238     }
3239   }
3240 
3241   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3242       CallConv != CallingConv::AMDGPU_Gfx) {
3243     // Copy special input registers after user input arguments.
3244     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3245   }
3246 
3247   if (!MemOpChains.empty())
3248     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3249 
3250   // Build a sequence of copy-to-reg nodes chained together with token chain
3251   // and flag operands which copy the outgoing args into the appropriate regs.
3252   SDValue InFlag;
3253   for (auto &RegToPass : RegsToPass) {
3254     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3255                              RegToPass.second, InFlag);
3256     InFlag = Chain.getValue(1);
3257   }
3258 
3259 
3260   SDValue PhysReturnAddrReg;
3261   if (IsTailCall) {
3262     // Since the return is being combined with the call, we need to pass on the
3263     // return address.
3264 
3265     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3266     SDValue ReturnAddrReg = CreateLiveInRegister(
3267       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3268 
3269     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3270                                         MVT::i64);
3271     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3272     InFlag = Chain.getValue(1);
3273   }
3274 
3275   // We don't usually want to end the call-sequence here because we would tidy
3276   // the frame up *after* the call, however in the ABI-changing tail-call case
3277   // we've carefully laid out the parameters so that when sp is reset they'll be
3278   // in the correct location.
3279   if (IsTailCall && !IsSibCall) {
3280     Chain = DAG.getCALLSEQ_END(Chain,
3281                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3282                                DAG.getTargetConstant(0, DL, MVT::i32),
3283                                InFlag, DL);
3284     InFlag = Chain.getValue(1);
3285   }
3286 
3287   std::vector<SDValue> Ops;
3288   Ops.push_back(Chain);
3289   Ops.push_back(Callee);
3290   // Add a redundant copy of the callee global which will not be legalized, as
3291   // we need direct access to the callee later.
3292   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3293     const GlobalValue *GV = GSD->getGlobal();
3294     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3295   } else {
3296     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3297   }
3298 
3299   if (IsTailCall) {
3300     // Each tail call may have to adjust the stack by a different amount, so
3301     // this information must travel along with the operation for eventual
3302     // consumption by emitEpilogue.
3303     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3304 
3305     Ops.push_back(PhysReturnAddrReg);
3306   }
3307 
3308   // Add argument registers to the end of the list so that they are known live
3309   // into the call.
3310   for (auto &RegToPass : RegsToPass) {
3311     Ops.push_back(DAG.getRegister(RegToPass.first,
3312                                   RegToPass.second.getValueType()));
3313   }
3314 
3315   // Add a register mask operand representing the call-preserved registers.
3316 
3317   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3318   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3319   assert(Mask && "Missing call preserved mask for calling convention");
3320   Ops.push_back(DAG.getRegisterMask(Mask));
3321 
3322   if (InFlag.getNode())
3323     Ops.push_back(InFlag);
3324 
3325   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3326 
3327   // If we're doing a tall call, use a TC_RETURN here rather than an
3328   // actual call instruction.
3329   if (IsTailCall) {
3330     MFI.setHasTailCall();
3331     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3332   }
3333 
3334   // Returns a chain and a flag for retval copy to use.
3335   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3336   Chain = Call.getValue(0);
3337   InFlag = Call.getValue(1);
3338 
3339   uint64_t CalleePopBytes = NumBytes;
3340   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3341                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3342                              InFlag, DL);
3343   if (!Ins.empty())
3344     InFlag = Chain.getValue(1);
3345 
3346   // Handle result values, copying them out of physregs into vregs that we
3347   // return.
3348   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3349                          InVals, IsThisReturn,
3350                          IsThisReturn ? OutVals[0] : SDValue());
3351 }
3352 
3353 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3354 // except for applying the wave size scale to the increment amount.
3355 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3356     SDValue Op, SelectionDAG &DAG) const {
3357   const MachineFunction &MF = DAG.getMachineFunction();
3358   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3359 
3360   SDLoc dl(Op);
3361   EVT VT = Op.getValueType();
3362   SDValue Tmp1 = Op;
3363   SDValue Tmp2 = Op.getValue(1);
3364   SDValue Tmp3 = Op.getOperand(2);
3365   SDValue Chain = Tmp1.getOperand(0);
3366 
3367   Register SPReg = Info->getStackPtrOffsetReg();
3368 
3369   // Chain the dynamic stack allocation so that it doesn't modify the stack
3370   // pointer when other instructions are using the stack.
3371   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3372 
3373   SDValue Size  = Tmp2.getOperand(1);
3374   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3375   Chain = SP.getValue(1);
3376   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3377   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3378   const TargetFrameLowering *TFL = ST.getFrameLowering();
3379   unsigned Opc =
3380     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3381     ISD::ADD : ISD::SUB;
3382 
3383   SDValue ScaledSize = DAG.getNode(
3384       ISD::SHL, dl, VT, Size,
3385       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3386 
3387   Align StackAlign = TFL->getStackAlign();
3388   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3389   if (Alignment && *Alignment > StackAlign) {
3390     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3391                        DAG.getConstant(-(uint64_t)Alignment->value()
3392                                            << ST.getWavefrontSizeLog2(),
3393                                        dl, VT));
3394   }
3395 
3396   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3397   Tmp2 = DAG.getCALLSEQ_END(
3398       Chain, DAG.getIntPtrConstant(0, dl, true),
3399       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3400 
3401   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3402 }
3403 
3404 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3405                                                   SelectionDAG &DAG) const {
3406   // We only handle constant sizes here to allow non-entry block, static sized
3407   // allocas. A truly dynamic value is more difficult to support because we
3408   // don't know if the size value is uniform or not. If the size isn't uniform,
3409   // we would need to do a wave reduction to get the maximum size to know how
3410   // much to increment the uniform stack pointer.
3411   SDValue Size = Op.getOperand(1);
3412   if (isa<ConstantSDNode>(Size))
3413       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3414 
3415   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3416 }
3417 
3418 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3419                                              const MachineFunction &MF) const {
3420   Register Reg = StringSwitch<Register>(RegName)
3421     .Case("m0", AMDGPU::M0)
3422     .Case("exec", AMDGPU::EXEC)
3423     .Case("exec_lo", AMDGPU::EXEC_LO)
3424     .Case("exec_hi", AMDGPU::EXEC_HI)
3425     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3426     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3427     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3428     .Default(Register());
3429 
3430   if (Reg == AMDGPU::NoRegister) {
3431     report_fatal_error(Twine("invalid register name \""
3432                              + StringRef(RegName)  + "\"."));
3433 
3434   }
3435 
3436   if (!Subtarget->hasFlatScrRegister() &&
3437        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3438     report_fatal_error(Twine("invalid register \""
3439                              + StringRef(RegName)  + "\" for subtarget."));
3440   }
3441 
3442   switch (Reg) {
3443   case AMDGPU::M0:
3444   case AMDGPU::EXEC_LO:
3445   case AMDGPU::EXEC_HI:
3446   case AMDGPU::FLAT_SCR_LO:
3447   case AMDGPU::FLAT_SCR_HI:
3448     if (VT.getSizeInBits() == 32)
3449       return Reg;
3450     break;
3451   case AMDGPU::EXEC:
3452   case AMDGPU::FLAT_SCR:
3453     if (VT.getSizeInBits() == 64)
3454       return Reg;
3455     break;
3456   default:
3457     llvm_unreachable("missing register type checking");
3458   }
3459 
3460   report_fatal_error(Twine("invalid type for register \""
3461                            + StringRef(RegName) + "\"."));
3462 }
3463 
3464 // If kill is not the last instruction, split the block so kill is always a
3465 // proper terminator.
3466 MachineBasicBlock *
3467 SITargetLowering::splitKillBlock(MachineInstr &MI,
3468                                  MachineBasicBlock *BB) const {
3469   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3470   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3471   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3472   return SplitBB;
3473 }
3474 
3475 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3476 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3477 // be the first instruction in the remainder block.
3478 //
3479 /// \returns { LoopBody, Remainder }
3480 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3481 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3482   MachineFunction *MF = MBB.getParent();
3483   MachineBasicBlock::iterator I(&MI);
3484 
3485   // To insert the loop we need to split the block. Move everything after this
3486   // point to a new block, and insert a new empty block between the two.
3487   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3488   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3489   MachineFunction::iterator MBBI(MBB);
3490   ++MBBI;
3491 
3492   MF->insert(MBBI, LoopBB);
3493   MF->insert(MBBI, RemainderBB);
3494 
3495   LoopBB->addSuccessor(LoopBB);
3496   LoopBB->addSuccessor(RemainderBB);
3497 
3498   // Move the rest of the block into a new block.
3499   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3500 
3501   if (InstInLoop) {
3502     auto Next = std::next(I);
3503 
3504     // Move instruction to loop body.
3505     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3506 
3507     // Move the rest of the block.
3508     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3509   } else {
3510     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3511   }
3512 
3513   MBB.addSuccessor(LoopBB);
3514 
3515   return std::make_pair(LoopBB, RemainderBB);
3516 }
3517 
3518 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3519 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3520   MachineBasicBlock *MBB = MI.getParent();
3521   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3522   auto I = MI.getIterator();
3523   auto E = std::next(I);
3524 
3525   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3526     .addImm(0);
3527 
3528   MIBundleBuilder Bundler(*MBB, I, E);
3529   finalizeBundle(*MBB, Bundler.begin());
3530 }
3531 
3532 MachineBasicBlock *
3533 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3534                                          MachineBasicBlock *BB) const {
3535   const DebugLoc &DL = MI.getDebugLoc();
3536 
3537   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3538 
3539   MachineBasicBlock *LoopBB;
3540   MachineBasicBlock *RemainderBB;
3541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3542 
3543   // Apparently kill flags are only valid if the def is in the same block?
3544   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3545     Src->setIsKill(false);
3546 
3547   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3548 
3549   MachineBasicBlock::iterator I = LoopBB->end();
3550 
3551   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3552     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3553 
3554   // Clear TRAP_STS.MEM_VIOL
3555   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3556     .addImm(0)
3557     .addImm(EncodedReg);
3558 
3559   bundleInstWithWaitcnt(MI);
3560 
3561   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3562 
3563   // Load and check TRAP_STS.MEM_VIOL
3564   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3565     .addImm(EncodedReg);
3566 
3567   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3568   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3569     .addReg(Reg, RegState::Kill)
3570     .addImm(0);
3571   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3572     .addMBB(LoopBB);
3573 
3574   return RemainderBB;
3575 }
3576 
3577 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3578 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3579 // will only do one iteration. In the worst case, this will loop 64 times.
3580 //
3581 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3582 static MachineBasicBlock::iterator
3583 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3584                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3585                        const DebugLoc &DL, const MachineOperand &Idx,
3586                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3587                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3588                        Register &SGPRIdxReg) {
3589 
3590   MachineFunction *MF = OrigBB.getParent();
3591   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3592   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3593   MachineBasicBlock::iterator I = LoopBB.begin();
3594 
3595   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3596   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3597   Register NewExec = MRI.createVirtualRegister(BoolRC);
3598   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3599   Register CondReg = MRI.createVirtualRegister(BoolRC);
3600 
3601   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3602     .addReg(InitReg)
3603     .addMBB(&OrigBB)
3604     .addReg(ResultReg)
3605     .addMBB(&LoopBB);
3606 
3607   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3608     .addReg(InitSaveExecReg)
3609     .addMBB(&OrigBB)
3610     .addReg(NewExec)
3611     .addMBB(&LoopBB);
3612 
3613   // Read the next variant <- also loop target.
3614   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3615       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3616 
3617   // Compare the just read M0 value to all possible Idx values.
3618   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3619       .addReg(CurrentIdxReg)
3620       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3621 
3622   // Update EXEC, save the original EXEC value to VCC.
3623   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3624                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3625           NewExec)
3626     .addReg(CondReg, RegState::Kill);
3627 
3628   MRI.setSimpleHint(NewExec, CondReg);
3629 
3630   if (UseGPRIdxMode) {
3631     if (Offset == 0) {
3632       SGPRIdxReg = CurrentIdxReg;
3633     } else {
3634       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3635       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3636           .addReg(CurrentIdxReg, RegState::Kill)
3637           .addImm(Offset);
3638     }
3639   } else {
3640     // Move index from VCC into M0
3641     if (Offset == 0) {
3642       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3643         .addReg(CurrentIdxReg, RegState::Kill);
3644     } else {
3645       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3646         .addReg(CurrentIdxReg, RegState::Kill)
3647         .addImm(Offset);
3648     }
3649   }
3650 
3651   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3652   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3653   MachineInstr *InsertPt =
3654     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3655                                                   : AMDGPU::S_XOR_B64_term), Exec)
3656       .addReg(Exec)
3657       .addReg(NewExec);
3658 
3659   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3660   // s_cbranch_scc0?
3661 
3662   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3663   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3664     .addMBB(&LoopBB);
3665 
3666   return InsertPt->getIterator();
3667 }
3668 
3669 // This has slightly sub-optimal regalloc when the source vector is killed by
3670 // the read. The register allocator does not understand that the kill is
3671 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3672 // subregister from it, using 1 more VGPR than necessary. This was saved when
3673 // this was expanded after register allocation.
3674 static MachineBasicBlock::iterator
3675 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3676                unsigned InitResultReg, unsigned PhiReg, int Offset,
3677                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3678   MachineFunction *MF = MBB.getParent();
3679   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3680   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3681   MachineRegisterInfo &MRI = MF->getRegInfo();
3682   const DebugLoc &DL = MI.getDebugLoc();
3683   MachineBasicBlock::iterator I(&MI);
3684 
3685   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3686   Register DstReg = MI.getOperand(0).getReg();
3687   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3688   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3689   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3690   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3691 
3692   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3693 
3694   // Save the EXEC mask
3695   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3696     .addReg(Exec);
3697 
3698   MachineBasicBlock *LoopBB;
3699   MachineBasicBlock *RemainderBB;
3700   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3701 
3702   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3703 
3704   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3705                                       InitResultReg, DstReg, PhiReg, TmpExec,
3706                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3707 
3708   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3709   MachineFunction::iterator MBBI(LoopBB);
3710   ++MBBI;
3711   MF->insert(MBBI, LandingPad);
3712   LoopBB->removeSuccessor(RemainderBB);
3713   LandingPad->addSuccessor(RemainderBB);
3714   LoopBB->addSuccessor(LandingPad);
3715   MachineBasicBlock::iterator First = LandingPad->begin();
3716   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3717     .addReg(SaveExec);
3718 
3719   return InsPt;
3720 }
3721 
3722 // Returns subreg index, offset
3723 static std::pair<unsigned, int>
3724 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3725                             const TargetRegisterClass *SuperRC,
3726                             unsigned VecReg,
3727                             int Offset) {
3728   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3729 
3730   // Skip out of bounds offsets, or else we would end up using an undefined
3731   // register.
3732   if (Offset >= NumElts || Offset < 0)
3733     return std::make_pair(AMDGPU::sub0, Offset);
3734 
3735   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3736 }
3737 
3738 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3739                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3740                                  int Offset) {
3741   MachineBasicBlock *MBB = MI.getParent();
3742   const DebugLoc &DL = MI.getDebugLoc();
3743   MachineBasicBlock::iterator I(&MI);
3744 
3745   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3746 
3747   assert(Idx->getReg() != AMDGPU::NoRegister);
3748 
3749   if (Offset == 0) {
3750     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3751   } else {
3752     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3753         .add(*Idx)
3754         .addImm(Offset);
3755   }
3756 }
3757 
3758 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3759                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3760                                    int Offset) {
3761   MachineBasicBlock *MBB = MI.getParent();
3762   const DebugLoc &DL = MI.getDebugLoc();
3763   MachineBasicBlock::iterator I(&MI);
3764 
3765   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3766 
3767   if (Offset == 0)
3768     return Idx->getReg();
3769 
3770   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3771   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3772       .add(*Idx)
3773       .addImm(Offset);
3774   return Tmp;
3775 }
3776 
3777 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3778                                           MachineBasicBlock &MBB,
3779                                           const GCNSubtarget &ST) {
3780   const SIInstrInfo *TII = ST.getInstrInfo();
3781   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3782   MachineFunction *MF = MBB.getParent();
3783   MachineRegisterInfo &MRI = MF->getRegInfo();
3784 
3785   Register Dst = MI.getOperand(0).getReg();
3786   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3787   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3788   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3789 
3790   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3791   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3792 
3793   unsigned SubReg;
3794   std::tie(SubReg, Offset)
3795     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3796 
3797   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3798 
3799   // Check for a SGPR index.
3800   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3801     MachineBasicBlock::iterator I(&MI);
3802     const DebugLoc &DL = MI.getDebugLoc();
3803 
3804     if (UseGPRIdxMode) {
3805       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3806       // to avoid interfering with other uses, so probably requires a new
3807       // optimization pass.
3808       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3809 
3810       const MCInstrDesc &GPRIDXDesc =
3811           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3812       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3813           .addReg(SrcReg)
3814           .addReg(Idx)
3815           .addImm(SubReg);
3816     } else {
3817       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3818 
3819       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3820         .addReg(SrcReg, 0, SubReg)
3821         .addReg(SrcReg, RegState::Implicit);
3822     }
3823 
3824     MI.eraseFromParent();
3825 
3826     return &MBB;
3827   }
3828 
3829   // Control flow needs to be inserted if indexing with a VGPR.
3830   const DebugLoc &DL = MI.getDebugLoc();
3831   MachineBasicBlock::iterator I(&MI);
3832 
3833   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3834   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3835 
3836   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3837 
3838   Register SGPRIdxReg;
3839   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3840                               UseGPRIdxMode, SGPRIdxReg);
3841 
3842   MachineBasicBlock *LoopBB = InsPt->getParent();
3843 
3844   if (UseGPRIdxMode) {
3845     const MCInstrDesc &GPRIDXDesc =
3846         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3847 
3848     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3849         .addReg(SrcReg)
3850         .addReg(SGPRIdxReg)
3851         .addImm(SubReg);
3852   } else {
3853     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3854       .addReg(SrcReg, 0, SubReg)
3855       .addReg(SrcReg, RegState::Implicit);
3856   }
3857 
3858   MI.eraseFromParent();
3859 
3860   return LoopBB;
3861 }
3862 
3863 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3864                                           MachineBasicBlock &MBB,
3865                                           const GCNSubtarget &ST) {
3866   const SIInstrInfo *TII = ST.getInstrInfo();
3867   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3868   MachineFunction *MF = MBB.getParent();
3869   MachineRegisterInfo &MRI = MF->getRegInfo();
3870 
3871   Register Dst = MI.getOperand(0).getReg();
3872   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3873   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3874   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3875   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3876   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3877   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3878 
3879   // This can be an immediate, but will be folded later.
3880   assert(Val->getReg());
3881 
3882   unsigned SubReg;
3883   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3884                                                          SrcVec->getReg(),
3885                                                          Offset);
3886   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3887 
3888   if (Idx->getReg() == AMDGPU::NoRegister) {
3889     MachineBasicBlock::iterator I(&MI);
3890     const DebugLoc &DL = MI.getDebugLoc();
3891 
3892     assert(Offset == 0);
3893 
3894     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3895         .add(*SrcVec)
3896         .add(*Val)
3897         .addImm(SubReg);
3898 
3899     MI.eraseFromParent();
3900     return &MBB;
3901   }
3902 
3903   // Check for a SGPR index.
3904   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3905     MachineBasicBlock::iterator I(&MI);
3906     const DebugLoc &DL = MI.getDebugLoc();
3907 
3908     if (UseGPRIdxMode) {
3909       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3910 
3911       const MCInstrDesc &GPRIDXDesc =
3912           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3913       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3914           .addReg(SrcVec->getReg())
3915           .add(*Val)
3916           .addReg(Idx)
3917           .addImm(SubReg);
3918     } else {
3919       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3920 
3921       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3922           TRI.getRegSizeInBits(*VecRC), 32, false);
3923       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3924           .addReg(SrcVec->getReg())
3925           .add(*Val)
3926           .addImm(SubReg);
3927     }
3928     MI.eraseFromParent();
3929     return &MBB;
3930   }
3931 
3932   // Control flow needs to be inserted if indexing with a VGPR.
3933   if (Val->isReg())
3934     MRI.clearKillFlags(Val->getReg());
3935 
3936   const DebugLoc &DL = MI.getDebugLoc();
3937 
3938   Register PhiReg = MRI.createVirtualRegister(VecRC);
3939 
3940   Register SGPRIdxReg;
3941   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3942                               UseGPRIdxMode, SGPRIdxReg);
3943   MachineBasicBlock *LoopBB = InsPt->getParent();
3944 
3945   if (UseGPRIdxMode) {
3946     const MCInstrDesc &GPRIDXDesc =
3947         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3948 
3949     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3950         .addReg(PhiReg)
3951         .add(*Val)
3952         .addReg(SGPRIdxReg)
3953         .addImm(AMDGPU::sub0);
3954   } else {
3955     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3956         TRI.getRegSizeInBits(*VecRC), 32, false);
3957     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3958         .addReg(PhiReg)
3959         .add(*Val)
3960         .addImm(AMDGPU::sub0);
3961   }
3962 
3963   MI.eraseFromParent();
3964   return LoopBB;
3965 }
3966 
3967 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3968   MachineInstr &MI, MachineBasicBlock *BB) const {
3969 
3970   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3971   MachineFunction *MF = BB->getParent();
3972   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3973 
3974   switch (MI.getOpcode()) {
3975   case AMDGPU::S_UADDO_PSEUDO:
3976   case AMDGPU::S_USUBO_PSEUDO: {
3977     const DebugLoc &DL = MI.getDebugLoc();
3978     MachineOperand &Dest0 = MI.getOperand(0);
3979     MachineOperand &Dest1 = MI.getOperand(1);
3980     MachineOperand &Src0 = MI.getOperand(2);
3981     MachineOperand &Src1 = MI.getOperand(3);
3982 
3983     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3984                        ? AMDGPU::S_ADD_I32
3985                        : AMDGPU::S_SUB_I32;
3986     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3987 
3988     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3989         .addImm(1)
3990         .addImm(0);
3991 
3992     MI.eraseFromParent();
3993     return BB;
3994   }
3995   case AMDGPU::S_ADD_U64_PSEUDO:
3996   case AMDGPU::S_SUB_U64_PSEUDO: {
3997     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3998     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3999     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4000     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4001     const DebugLoc &DL = MI.getDebugLoc();
4002 
4003     MachineOperand &Dest = MI.getOperand(0);
4004     MachineOperand &Src0 = MI.getOperand(1);
4005     MachineOperand &Src1 = MI.getOperand(2);
4006 
4007     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4008     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4009 
4010     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4011         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4012     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4013         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4014 
4015     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4016         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4017     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4018         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4019 
4020     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4021 
4022     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4023     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4024     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4025     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4026     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4027         .addReg(DestSub0)
4028         .addImm(AMDGPU::sub0)
4029         .addReg(DestSub1)
4030         .addImm(AMDGPU::sub1);
4031     MI.eraseFromParent();
4032     return BB;
4033   }
4034   case AMDGPU::V_ADD_U64_PSEUDO:
4035   case AMDGPU::V_SUB_U64_PSEUDO: {
4036     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4037     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4038     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4039     const DebugLoc &DL = MI.getDebugLoc();
4040 
4041     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4042 
4043     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4044 
4045     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4046     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4047 
4048     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4049     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4050 
4051     MachineOperand &Dest = MI.getOperand(0);
4052     MachineOperand &Src0 = MI.getOperand(1);
4053     MachineOperand &Src1 = MI.getOperand(2);
4054 
4055     const TargetRegisterClass *Src0RC = Src0.isReg()
4056                                             ? MRI.getRegClass(Src0.getReg())
4057                                             : &AMDGPU::VReg_64RegClass;
4058     const TargetRegisterClass *Src1RC = Src1.isReg()
4059                                             ? MRI.getRegClass(Src1.getReg())
4060                                             : &AMDGPU::VReg_64RegClass;
4061 
4062     const TargetRegisterClass *Src0SubRC =
4063         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4064     const TargetRegisterClass *Src1SubRC =
4065         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4066 
4067     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4068         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4069     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4070         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4071 
4072     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4073         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4074     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4075         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4076 
4077     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4078     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4079                                .addReg(CarryReg, RegState::Define)
4080                                .add(SrcReg0Sub0)
4081                                .add(SrcReg1Sub0)
4082                                .addImm(0); // clamp bit
4083 
4084     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4085     MachineInstr *HiHalf =
4086         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4087             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4088             .add(SrcReg0Sub1)
4089             .add(SrcReg1Sub1)
4090             .addReg(CarryReg, RegState::Kill)
4091             .addImm(0); // clamp bit
4092 
4093     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4094         .addReg(DestSub0)
4095         .addImm(AMDGPU::sub0)
4096         .addReg(DestSub1)
4097         .addImm(AMDGPU::sub1);
4098     TII->legalizeOperands(*LoHalf);
4099     TII->legalizeOperands(*HiHalf);
4100     MI.eraseFromParent();
4101     return BB;
4102   }
4103   case AMDGPU::S_ADD_CO_PSEUDO:
4104   case AMDGPU::S_SUB_CO_PSEUDO: {
4105     // This pseudo has a chance to be selected
4106     // only from uniform add/subcarry node. All the VGPR operands
4107     // therefore assumed to be splat vectors.
4108     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4109     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4110     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4111     MachineBasicBlock::iterator MII = MI;
4112     const DebugLoc &DL = MI.getDebugLoc();
4113     MachineOperand &Dest = MI.getOperand(0);
4114     MachineOperand &CarryDest = MI.getOperand(1);
4115     MachineOperand &Src0 = MI.getOperand(2);
4116     MachineOperand &Src1 = MI.getOperand(3);
4117     MachineOperand &Src2 = MI.getOperand(4);
4118     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4119                        ? AMDGPU::S_ADDC_U32
4120                        : AMDGPU::S_SUBB_U32;
4121     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4122       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4123       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4124           .addReg(Src0.getReg());
4125       Src0.setReg(RegOp0);
4126     }
4127     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4128       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4129       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4130           .addReg(Src1.getReg());
4131       Src1.setReg(RegOp1);
4132     }
4133     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4134     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4135       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4136           .addReg(Src2.getReg());
4137       Src2.setReg(RegOp2);
4138     }
4139 
4140     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4141     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4142       if (ST.hasScalarCompareEq64()) {
4143         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4144             .addReg(Src2.getReg())
4145             .addImm(0);
4146       } else {
4147         const TargetRegisterClass *SubRC =
4148             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4149         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4150             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4151         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4152             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4153         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4154 
4155         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4156             .add(Src2Sub0)
4157             .add(Src2Sub1);
4158 
4159         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4160             .addReg(Src2_32, RegState::Kill)
4161             .addImm(0);
4162       }
4163     } else {
4164       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4165           .addReg(Src2.getReg())
4166           .addImm(0);
4167     }
4168 
4169     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4170 
4171     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4172       .addReg(AMDGPU::SCC);
4173     MI.eraseFromParent();
4174     return BB;
4175   }
4176   case AMDGPU::SI_INIT_M0: {
4177     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4178             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4179         .add(MI.getOperand(0));
4180     MI.eraseFromParent();
4181     return BB;
4182   }
4183   case AMDGPU::GET_GROUPSTATICSIZE: {
4184     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4185            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4186     DebugLoc DL = MI.getDebugLoc();
4187     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4188         .add(MI.getOperand(0))
4189         .addImm(MFI->getLDSSize());
4190     MI.eraseFromParent();
4191     return BB;
4192   }
4193   case AMDGPU::SI_INDIRECT_SRC_V1:
4194   case AMDGPU::SI_INDIRECT_SRC_V2:
4195   case AMDGPU::SI_INDIRECT_SRC_V4:
4196   case AMDGPU::SI_INDIRECT_SRC_V8:
4197   case AMDGPU::SI_INDIRECT_SRC_V16:
4198   case AMDGPU::SI_INDIRECT_SRC_V32:
4199     return emitIndirectSrc(MI, *BB, *getSubtarget());
4200   case AMDGPU::SI_INDIRECT_DST_V1:
4201   case AMDGPU::SI_INDIRECT_DST_V2:
4202   case AMDGPU::SI_INDIRECT_DST_V4:
4203   case AMDGPU::SI_INDIRECT_DST_V8:
4204   case AMDGPU::SI_INDIRECT_DST_V16:
4205   case AMDGPU::SI_INDIRECT_DST_V32:
4206     return emitIndirectDst(MI, *BB, *getSubtarget());
4207   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4208   case AMDGPU::SI_KILL_I1_PSEUDO:
4209     return splitKillBlock(MI, BB);
4210   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4211     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4212     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4213     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4214 
4215     Register Dst = MI.getOperand(0).getReg();
4216     Register Src0 = MI.getOperand(1).getReg();
4217     Register Src1 = MI.getOperand(2).getReg();
4218     const DebugLoc &DL = MI.getDebugLoc();
4219     Register SrcCond = MI.getOperand(3).getReg();
4220 
4221     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4222     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4223     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4224     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4225 
4226     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4227       .addReg(SrcCond);
4228     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4229       .addImm(0)
4230       .addReg(Src0, 0, AMDGPU::sub0)
4231       .addImm(0)
4232       .addReg(Src1, 0, AMDGPU::sub0)
4233       .addReg(SrcCondCopy);
4234     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4235       .addImm(0)
4236       .addReg(Src0, 0, AMDGPU::sub1)
4237       .addImm(0)
4238       .addReg(Src1, 0, AMDGPU::sub1)
4239       .addReg(SrcCondCopy);
4240 
4241     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4242       .addReg(DstLo)
4243       .addImm(AMDGPU::sub0)
4244       .addReg(DstHi)
4245       .addImm(AMDGPU::sub1);
4246     MI.eraseFromParent();
4247     return BB;
4248   }
4249   case AMDGPU::SI_BR_UNDEF: {
4250     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4251     const DebugLoc &DL = MI.getDebugLoc();
4252     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4253                            .add(MI.getOperand(0));
4254     Br->getOperand(1).setIsUndef(true); // read undef SCC
4255     MI.eraseFromParent();
4256     return BB;
4257   }
4258   case AMDGPU::ADJCALLSTACKUP:
4259   case AMDGPU::ADJCALLSTACKDOWN: {
4260     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4261     MachineInstrBuilder MIB(*MF, &MI);
4262     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4263        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4264     return BB;
4265   }
4266   case AMDGPU::SI_CALL_ISEL: {
4267     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4268     const DebugLoc &DL = MI.getDebugLoc();
4269 
4270     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4271 
4272     MachineInstrBuilder MIB;
4273     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4274 
4275     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4276       MIB.add(MI.getOperand(I));
4277 
4278     MIB.cloneMemRefs(MI);
4279     MI.eraseFromParent();
4280     return BB;
4281   }
4282   case AMDGPU::V_ADD_CO_U32_e32:
4283   case AMDGPU::V_SUB_CO_U32_e32:
4284   case AMDGPU::V_SUBREV_CO_U32_e32: {
4285     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4286     const DebugLoc &DL = MI.getDebugLoc();
4287     unsigned Opc = MI.getOpcode();
4288 
4289     bool NeedClampOperand = false;
4290     if (TII->pseudoToMCOpcode(Opc) == -1) {
4291       Opc = AMDGPU::getVOPe64(Opc);
4292       NeedClampOperand = true;
4293     }
4294 
4295     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4296     if (TII->isVOP3(*I)) {
4297       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4298       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4299       I.addReg(TRI->getVCC(), RegState::Define);
4300     }
4301     I.add(MI.getOperand(1))
4302      .add(MI.getOperand(2));
4303     if (NeedClampOperand)
4304       I.addImm(0); // clamp bit for e64 encoding
4305 
4306     TII->legalizeOperands(*I);
4307 
4308     MI.eraseFromParent();
4309     return BB;
4310   }
4311   case AMDGPU::V_ADDC_U32_e32:
4312   case AMDGPU::V_SUBB_U32_e32:
4313   case AMDGPU::V_SUBBREV_U32_e32:
4314     // These instructions have an implicit use of vcc which counts towards the
4315     // constant bus limit.
4316     TII->legalizeOperands(MI);
4317     return BB;
4318   case AMDGPU::DS_GWS_INIT:
4319   case AMDGPU::DS_GWS_SEMA_BR:
4320   case AMDGPU::DS_GWS_BARRIER:
4321     if (Subtarget->needsAlignedVGPRs()) {
4322       // Add implicit aligned super-reg to force alignment on the data operand.
4323       const DebugLoc &DL = MI.getDebugLoc();
4324       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4325       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4326       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4327       Register DataReg = Op->getReg();
4328       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4329       Register Undef = MRI.createVirtualRegister(
4330           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4331       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4332       Register NewVR =
4333           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4334                                            : &AMDGPU::VReg_64_Align2RegClass);
4335       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4336           .addReg(DataReg, 0, Op->getSubReg())
4337           .addImm(AMDGPU::sub0)
4338           .addReg(Undef)
4339           .addImm(AMDGPU::sub1);
4340       Op->setReg(NewVR);
4341       Op->setSubReg(AMDGPU::sub0);
4342       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4343     }
4344     LLVM_FALLTHROUGH;
4345   case AMDGPU::DS_GWS_SEMA_V:
4346   case AMDGPU::DS_GWS_SEMA_P:
4347   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4348     // A s_waitcnt 0 is required to be the instruction immediately following.
4349     if (getSubtarget()->hasGWSAutoReplay()) {
4350       bundleInstWithWaitcnt(MI);
4351       return BB;
4352     }
4353 
4354     return emitGWSMemViolTestLoop(MI, BB);
4355   case AMDGPU::S_SETREG_B32: {
4356     // Try to optimize cases that only set the denormal mode or rounding mode.
4357     //
4358     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4359     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4360     // instead.
4361     //
4362     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4363     // allow you to have a no side effect instruction in the output of a
4364     // sideeffecting pattern.
4365     unsigned ID, Offset, Width;
4366     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4367     if (ID != AMDGPU::Hwreg::ID_MODE)
4368       return BB;
4369 
4370     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4371     const unsigned SetMask = WidthMask << Offset;
4372 
4373     if (getSubtarget()->hasDenormModeInst()) {
4374       unsigned SetDenormOp = 0;
4375       unsigned SetRoundOp = 0;
4376 
4377       // The dedicated instructions can only set the whole denorm or round mode
4378       // at once, not a subset of bits in either.
4379       if (SetMask ==
4380           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4381         // If this fully sets both the round and denorm mode, emit the two
4382         // dedicated instructions for these.
4383         SetRoundOp = AMDGPU::S_ROUND_MODE;
4384         SetDenormOp = AMDGPU::S_DENORM_MODE;
4385       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4386         SetRoundOp = AMDGPU::S_ROUND_MODE;
4387       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4388         SetDenormOp = AMDGPU::S_DENORM_MODE;
4389       }
4390 
4391       if (SetRoundOp || SetDenormOp) {
4392         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4393         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4394         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4395           unsigned ImmVal = Def->getOperand(1).getImm();
4396           if (SetRoundOp) {
4397             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4398                 .addImm(ImmVal & 0xf);
4399 
4400             // If we also have the denorm mode, get just the denorm mode bits.
4401             ImmVal >>= 4;
4402           }
4403 
4404           if (SetDenormOp) {
4405             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4406                 .addImm(ImmVal & 0xf);
4407           }
4408 
4409           MI.eraseFromParent();
4410           return BB;
4411         }
4412       }
4413     }
4414 
4415     // If only FP bits are touched, used the no side effects pseudo.
4416     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4417                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4418       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4419 
4420     return BB;
4421   }
4422   default:
4423     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4424   }
4425 }
4426 
4427 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4428   return isTypeLegal(VT.getScalarType());
4429 }
4430 
4431 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4432   // This currently forces unfolding various combinations of fsub into fma with
4433   // free fneg'd operands. As long as we have fast FMA (controlled by
4434   // isFMAFasterThanFMulAndFAdd), we should perform these.
4435 
4436   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4437   // most of these combines appear to be cycle neutral but save on instruction
4438   // count / code size.
4439   return true;
4440 }
4441 
4442 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4443                                          EVT VT) const {
4444   if (!VT.isVector()) {
4445     return MVT::i1;
4446   }
4447   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4448 }
4449 
4450 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4451   // TODO: Should i16 be used always if legal? For now it would force VALU
4452   // shifts.
4453   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4454 }
4455 
4456 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4457   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4458              ? Ty.changeElementSize(16)
4459              : Ty.changeElementSize(32);
4460 }
4461 
4462 // Answering this is somewhat tricky and depends on the specific device which
4463 // have different rates for fma or all f64 operations.
4464 //
4465 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4466 // regardless of which device (although the number of cycles differs between
4467 // devices), so it is always profitable for f64.
4468 //
4469 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4470 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4471 // which we can always do even without fused FP ops since it returns the same
4472 // result as the separate operations and since it is always full
4473 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4474 // however does not support denormals, so we do report fma as faster if we have
4475 // a fast fma device and require denormals.
4476 //
4477 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4478                                                   EVT VT) const {
4479   VT = VT.getScalarType();
4480 
4481   switch (VT.getSimpleVT().SimpleTy) {
4482   case MVT::f32: {
4483     // If mad is not available this depends only on if f32 fma is full rate.
4484     if (!Subtarget->hasMadMacF32Insts())
4485       return Subtarget->hasFastFMAF32();
4486 
4487     // Otherwise f32 mad is always full rate and returns the same result as
4488     // the separate operations so should be preferred over fma.
4489     // However does not support denomals.
4490     if (hasFP32Denormals(MF))
4491       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4492 
4493     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4494     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4495   }
4496   case MVT::f64:
4497     return true;
4498   case MVT::f16:
4499     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4500   default:
4501     break;
4502   }
4503 
4504   return false;
4505 }
4506 
4507 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4508                                    const SDNode *N) const {
4509   // TODO: Check future ftz flag
4510   // v_mad_f32/v_mac_f32 do not support denormals.
4511   EVT VT = N->getValueType(0);
4512   if (VT == MVT::f32)
4513     return Subtarget->hasMadMacF32Insts() &&
4514            !hasFP32Denormals(DAG.getMachineFunction());
4515   if (VT == MVT::f16) {
4516     return Subtarget->hasMadF16() &&
4517            !hasFP64FP16Denormals(DAG.getMachineFunction());
4518   }
4519 
4520   return false;
4521 }
4522 
4523 //===----------------------------------------------------------------------===//
4524 // Custom DAG Lowering Operations
4525 //===----------------------------------------------------------------------===//
4526 
4527 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4528 // wider vector type is legal.
4529 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4530                                              SelectionDAG &DAG) const {
4531   unsigned Opc = Op.getOpcode();
4532   EVT VT = Op.getValueType();
4533   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4534 
4535   SDValue Lo, Hi;
4536   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4537 
4538   SDLoc SL(Op);
4539   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4540                              Op->getFlags());
4541   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4542                              Op->getFlags());
4543 
4544   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4545 }
4546 
4547 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4548 // wider vector type is legal.
4549 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4550                                               SelectionDAG &DAG) const {
4551   unsigned Opc = Op.getOpcode();
4552   EVT VT = Op.getValueType();
4553   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4554          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4555 
4556   SDValue Lo0, Hi0;
4557   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4558   SDValue Lo1, Hi1;
4559   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4560 
4561   SDLoc SL(Op);
4562 
4563   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4564                              Op->getFlags());
4565   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4566                              Op->getFlags());
4567 
4568   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4569 }
4570 
4571 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4572                                               SelectionDAG &DAG) const {
4573   unsigned Opc = Op.getOpcode();
4574   EVT VT = Op.getValueType();
4575   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4576          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4577 
4578   SDValue Lo0, Hi0;
4579   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4580   SDValue Lo1, Hi1;
4581   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4582   SDValue Lo2, Hi2;
4583   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4584 
4585   SDLoc SL(Op);
4586 
4587   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4588                              Op->getFlags());
4589   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4590                              Op->getFlags());
4591 
4592   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4593 }
4594 
4595 
4596 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4597   switch (Op.getOpcode()) {
4598   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4599   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4600   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4601   case ISD::LOAD: {
4602     SDValue Result = LowerLOAD(Op, DAG);
4603     assert((!Result.getNode() ||
4604             Result.getNode()->getNumValues() == 2) &&
4605            "Load should return a value and a chain");
4606     return Result;
4607   }
4608 
4609   case ISD::FSIN:
4610   case ISD::FCOS:
4611     return LowerTrig(Op, DAG);
4612   case ISD::SELECT: return LowerSELECT(Op, DAG);
4613   case ISD::FDIV: return LowerFDIV(Op, DAG);
4614   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4615   case ISD::STORE: return LowerSTORE(Op, DAG);
4616   case ISD::GlobalAddress: {
4617     MachineFunction &MF = DAG.getMachineFunction();
4618     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4619     return LowerGlobalAddress(MFI, Op, DAG);
4620   }
4621   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4622   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4623   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4624   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4625   case ISD::INSERT_SUBVECTOR:
4626     return lowerINSERT_SUBVECTOR(Op, DAG);
4627   case ISD::INSERT_VECTOR_ELT:
4628     return lowerINSERT_VECTOR_ELT(Op, DAG);
4629   case ISD::EXTRACT_VECTOR_ELT:
4630     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4631   case ISD::VECTOR_SHUFFLE:
4632     return lowerVECTOR_SHUFFLE(Op, DAG);
4633   case ISD::BUILD_VECTOR:
4634     return lowerBUILD_VECTOR(Op, DAG);
4635   case ISD::FP_ROUND:
4636     return lowerFP_ROUND(Op, DAG);
4637   case ISD::TRAP:
4638     return lowerTRAP(Op, DAG);
4639   case ISD::DEBUGTRAP:
4640     return lowerDEBUGTRAP(Op, DAG);
4641   case ISD::FABS:
4642   case ISD::FNEG:
4643   case ISD::FCANONICALIZE:
4644   case ISD::BSWAP:
4645     return splitUnaryVectorOp(Op, DAG);
4646   case ISD::FMINNUM:
4647   case ISD::FMAXNUM:
4648     return lowerFMINNUM_FMAXNUM(Op, DAG);
4649   case ISD::FMA:
4650     return splitTernaryVectorOp(Op, DAG);
4651   case ISD::FP_TO_SINT:
4652   case ISD::FP_TO_UINT:
4653     return LowerFP_TO_INT(Op, DAG);
4654   case ISD::SHL:
4655   case ISD::SRA:
4656   case ISD::SRL:
4657   case ISD::ADD:
4658   case ISD::SUB:
4659   case ISD::MUL:
4660   case ISD::SMIN:
4661   case ISD::SMAX:
4662   case ISD::UMIN:
4663   case ISD::UMAX:
4664   case ISD::FADD:
4665   case ISD::FMUL:
4666   case ISD::FMINNUM_IEEE:
4667   case ISD::FMAXNUM_IEEE:
4668   case ISD::UADDSAT:
4669   case ISD::USUBSAT:
4670   case ISD::SADDSAT:
4671   case ISD::SSUBSAT:
4672     return splitBinaryVectorOp(Op, DAG);
4673   case ISD::SMULO:
4674   case ISD::UMULO:
4675     return lowerXMULO(Op, DAG);
4676   case ISD::DYNAMIC_STACKALLOC:
4677     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4678   }
4679   return SDValue();
4680 }
4681 
4682 // Used for D16: Casts the result of an instruction into the right vector,
4683 // packs values if loads return unpacked values.
4684 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4685                                        const SDLoc &DL,
4686                                        SelectionDAG &DAG, bool Unpacked) {
4687   if (!LoadVT.isVector())
4688     return Result;
4689 
4690   // Cast back to the original packed type or to a larger type that is a
4691   // multiple of 32 bit for D16. Widening the return type is a required for
4692   // legalization.
4693   EVT FittingLoadVT = LoadVT;
4694   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4695     FittingLoadVT =
4696         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4697                          LoadVT.getVectorNumElements() + 1);
4698   }
4699 
4700   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4701     // Truncate to v2i16/v4i16.
4702     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4703 
4704     // Workaround legalizer not scalarizing truncate after vector op
4705     // legalization but not creating intermediate vector trunc.
4706     SmallVector<SDValue, 4> Elts;
4707     DAG.ExtractVectorElements(Result, Elts);
4708     for (SDValue &Elt : Elts)
4709       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4710 
4711     // Pad illegal v1i16/v3fi6 to v4i16
4712     if ((LoadVT.getVectorNumElements() % 2) == 1)
4713       Elts.push_back(DAG.getUNDEF(MVT::i16));
4714 
4715     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4716 
4717     // Bitcast to original type (v2f16/v4f16).
4718     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4719   }
4720 
4721   // Cast back to the original packed type.
4722   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4723 }
4724 
4725 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4726                                               MemSDNode *M,
4727                                               SelectionDAG &DAG,
4728                                               ArrayRef<SDValue> Ops,
4729                                               bool IsIntrinsic) const {
4730   SDLoc DL(M);
4731 
4732   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4733   EVT LoadVT = M->getValueType(0);
4734 
4735   EVT EquivLoadVT = LoadVT;
4736   if (LoadVT.isVector()) {
4737     if (Unpacked) {
4738       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4739                                      LoadVT.getVectorNumElements());
4740     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4741       // Widen v3f16 to legal type
4742       EquivLoadVT =
4743           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4744                            LoadVT.getVectorNumElements() + 1);
4745     }
4746   }
4747 
4748   // Change from v4f16/v2f16 to EquivLoadVT.
4749   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4750 
4751   SDValue Load
4752     = DAG.getMemIntrinsicNode(
4753       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4754       VTList, Ops, M->getMemoryVT(),
4755       M->getMemOperand());
4756 
4757   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4758 
4759   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4760 }
4761 
4762 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4763                                              SelectionDAG &DAG,
4764                                              ArrayRef<SDValue> Ops) const {
4765   SDLoc DL(M);
4766   EVT LoadVT = M->getValueType(0);
4767   EVT EltType = LoadVT.getScalarType();
4768   EVT IntVT = LoadVT.changeTypeToInteger();
4769 
4770   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4771 
4772   unsigned Opc =
4773       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4774 
4775   if (IsD16) {
4776     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4777   }
4778 
4779   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4780   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4781     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4782 
4783   if (isTypeLegal(LoadVT)) {
4784     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4785                                M->getMemOperand(), DAG);
4786   }
4787 
4788   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4789   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4790   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4791                                         M->getMemOperand(), DAG);
4792   return DAG.getMergeValues(
4793       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4794       DL);
4795 }
4796 
4797 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4798                                   SDNode *N, SelectionDAG &DAG) {
4799   EVT VT = N->getValueType(0);
4800   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4801   unsigned CondCode = CD->getZExtValue();
4802   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4803     return DAG.getUNDEF(VT);
4804 
4805   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4806 
4807   SDValue LHS = N->getOperand(1);
4808   SDValue RHS = N->getOperand(2);
4809 
4810   SDLoc DL(N);
4811 
4812   EVT CmpVT = LHS.getValueType();
4813   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4814     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4815       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4816     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4817     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4818   }
4819 
4820   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4821 
4822   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4823   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4824 
4825   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4826                               DAG.getCondCode(CCOpcode));
4827   if (VT.bitsEq(CCVT))
4828     return SetCC;
4829   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4830 }
4831 
4832 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4833                                   SDNode *N, SelectionDAG &DAG) {
4834   EVT VT = N->getValueType(0);
4835   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4836 
4837   unsigned CondCode = CD->getZExtValue();
4838   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4839     return DAG.getUNDEF(VT);
4840 
4841   SDValue Src0 = N->getOperand(1);
4842   SDValue Src1 = N->getOperand(2);
4843   EVT CmpVT = Src0.getValueType();
4844   SDLoc SL(N);
4845 
4846   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4847     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4848     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4849   }
4850 
4851   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4852   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4853   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4854   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4855   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4856                               Src1, DAG.getCondCode(CCOpcode));
4857   if (VT.bitsEq(CCVT))
4858     return SetCC;
4859   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4860 }
4861 
4862 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4863                                     SelectionDAG &DAG) {
4864   EVT VT = N->getValueType(0);
4865   SDValue Src = N->getOperand(1);
4866   SDLoc SL(N);
4867 
4868   if (Src.getOpcode() == ISD::SETCC) {
4869     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4870     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4871                        Src.getOperand(1), Src.getOperand(2));
4872   }
4873   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4874     // (ballot 0) -> 0
4875     if (Arg->isZero())
4876       return DAG.getConstant(0, SL, VT);
4877 
4878     // (ballot 1) -> EXEC/EXEC_LO
4879     if (Arg->isOne()) {
4880       Register Exec;
4881       if (VT.getScalarSizeInBits() == 32)
4882         Exec = AMDGPU::EXEC_LO;
4883       else if (VT.getScalarSizeInBits() == 64)
4884         Exec = AMDGPU::EXEC;
4885       else
4886         return SDValue();
4887 
4888       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4889     }
4890   }
4891 
4892   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4893   // ISD::SETNE)
4894   return DAG.getNode(
4895       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4896       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4897 }
4898 
4899 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4900                                           SmallVectorImpl<SDValue> &Results,
4901                                           SelectionDAG &DAG) const {
4902   switch (N->getOpcode()) {
4903   case ISD::INSERT_VECTOR_ELT: {
4904     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4905       Results.push_back(Res);
4906     return;
4907   }
4908   case ISD::EXTRACT_VECTOR_ELT: {
4909     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4910       Results.push_back(Res);
4911     return;
4912   }
4913   case ISD::INTRINSIC_WO_CHAIN: {
4914     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4915     switch (IID) {
4916     case Intrinsic::amdgcn_cvt_pkrtz: {
4917       SDValue Src0 = N->getOperand(1);
4918       SDValue Src1 = N->getOperand(2);
4919       SDLoc SL(N);
4920       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4921                                 Src0, Src1);
4922       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4923       return;
4924     }
4925     case Intrinsic::amdgcn_cvt_pknorm_i16:
4926     case Intrinsic::amdgcn_cvt_pknorm_u16:
4927     case Intrinsic::amdgcn_cvt_pk_i16:
4928     case Intrinsic::amdgcn_cvt_pk_u16: {
4929       SDValue Src0 = N->getOperand(1);
4930       SDValue Src1 = N->getOperand(2);
4931       SDLoc SL(N);
4932       unsigned Opcode;
4933 
4934       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4935         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4936       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4937         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4938       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4939         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4940       else
4941         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4942 
4943       EVT VT = N->getValueType(0);
4944       if (isTypeLegal(VT))
4945         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4946       else {
4947         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4948         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4949       }
4950       return;
4951     }
4952     }
4953     break;
4954   }
4955   case ISD::INTRINSIC_W_CHAIN: {
4956     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4957       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4958         // FIXME: Hacky
4959         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4960           Results.push_back(Res.getOperand(I));
4961         }
4962       } else {
4963         Results.push_back(Res);
4964         Results.push_back(Res.getValue(1));
4965       }
4966       return;
4967     }
4968 
4969     break;
4970   }
4971   case ISD::SELECT: {
4972     SDLoc SL(N);
4973     EVT VT = N->getValueType(0);
4974     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4975     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4976     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4977 
4978     EVT SelectVT = NewVT;
4979     if (NewVT.bitsLT(MVT::i32)) {
4980       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4981       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4982       SelectVT = MVT::i32;
4983     }
4984 
4985     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4986                                     N->getOperand(0), LHS, RHS);
4987 
4988     if (NewVT != SelectVT)
4989       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4990     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4991     return;
4992   }
4993   case ISD::FNEG: {
4994     if (N->getValueType(0) != MVT::v2f16)
4995       break;
4996 
4997     SDLoc SL(N);
4998     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4999 
5000     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5001                              BC,
5002                              DAG.getConstant(0x80008000, SL, MVT::i32));
5003     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5004     return;
5005   }
5006   case ISD::FABS: {
5007     if (N->getValueType(0) != MVT::v2f16)
5008       break;
5009 
5010     SDLoc SL(N);
5011     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5012 
5013     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5014                              BC,
5015                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5016     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5017     return;
5018   }
5019   default:
5020     break;
5021   }
5022 }
5023 
5024 /// Helper function for LowerBRCOND
5025 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5026 
5027   SDNode *Parent = Value.getNode();
5028   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5029        I != E; ++I) {
5030 
5031     if (I.getUse().get() != Value)
5032       continue;
5033 
5034     if (I->getOpcode() == Opcode)
5035       return *I;
5036   }
5037   return nullptr;
5038 }
5039 
5040 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5041   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5042     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5043     case Intrinsic::amdgcn_if:
5044       return AMDGPUISD::IF;
5045     case Intrinsic::amdgcn_else:
5046       return AMDGPUISD::ELSE;
5047     case Intrinsic::amdgcn_loop:
5048       return AMDGPUISD::LOOP;
5049     case Intrinsic::amdgcn_end_cf:
5050       llvm_unreachable("should not occur");
5051     default:
5052       return 0;
5053     }
5054   }
5055 
5056   // break, if_break, else_break are all only used as inputs to loop, not
5057   // directly as branch conditions.
5058   return 0;
5059 }
5060 
5061 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5062   const Triple &TT = getTargetMachine().getTargetTriple();
5063   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5064           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5065          AMDGPU::shouldEmitConstantsToTextSection(TT);
5066 }
5067 
5068 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5069   // FIXME: Either avoid relying on address space here or change the default
5070   // address space for functions to avoid the explicit check.
5071   return (GV->getValueType()->isFunctionTy() ||
5072           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5073          !shouldEmitFixup(GV) &&
5074          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5075 }
5076 
5077 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5078   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5079 }
5080 
5081 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5082   if (!GV->hasExternalLinkage())
5083     return true;
5084 
5085   const auto OS = getTargetMachine().getTargetTriple().getOS();
5086   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5087 }
5088 
5089 /// This transforms the control flow intrinsics to get the branch destination as
5090 /// last parameter, also switches branch target with BR if the need arise
5091 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5092                                       SelectionDAG &DAG) const {
5093   SDLoc DL(BRCOND);
5094 
5095   SDNode *Intr = BRCOND.getOperand(1).getNode();
5096   SDValue Target = BRCOND.getOperand(2);
5097   SDNode *BR = nullptr;
5098   SDNode *SetCC = nullptr;
5099 
5100   if (Intr->getOpcode() == ISD::SETCC) {
5101     // As long as we negate the condition everything is fine
5102     SetCC = Intr;
5103     Intr = SetCC->getOperand(0).getNode();
5104 
5105   } else {
5106     // Get the target from BR if we don't negate the condition
5107     BR = findUser(BRCOND, ISD::BR);
5108     assert(BR && "brcond missing unconditional branch user");
5109     Target = BR->getOperand(1);
5110   }
5111 
5112   unsigned CFNode = isCFIntrinsic(Intr);
5113   if (CFNode == 0) {
5114     // This is a uniform branch so we don't need to legalize.
5115     return BRCOND;
5116   }
5117 
5118   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5119                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5120 
5121   assert(!SetCC ||
5122         (SetCC->getConstantOperandVal(1) == 1 &&
5123          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5124                                                              ISD::SETNE));
5125 
5126   // operands of the new intrinsic call
5127   SmallVector<SDValue, 4> Ops;
5128   if (HaveChain)
5129     Ops.push_back(BRCOND.getOperand(0));
5130 
5131   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5132   Ops.push_back(Target);
5133 
5134   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5135 
5136   // build the new intrinsic call
5137   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5138 
5139   if (!HaveChain) {
5140     SDValue Ops[] =  {
5141       SDValue(Result, 0),
5142       BRCOND.getOperand(0)
5143     };
5144 
5145     Result = DAG.getMergeValues(Ops, DL).getNode();
5146   }
5147 
5148   if (BR) {
5149     // Give the branch instruction our target
5150     SDValue Ops[] = {
5151       BR->getOperand(0),
5152       BRCOND.getOperand(2)
5153     };
5154     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5155     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5156   }
5157 
5158   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5159 
5160   // Copy the intrinsic results to registers
5161   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5162     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5163     if (!CopyToReg)
5164       continue;
5165 
5166     Chain = DAG.getCopyToReg(
5167       Chain, DL,
5168       CopyToReg->getOperand(1),
5169       SDValue(Result, i - 1),
5170       SDValue());
5171 
5172     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5173   }
5174 
5175   // Remove the old intrinsic from the chain
5176   DAG.ReplaceAllUsesOfValueWith(
5177     SDValue(Intr, Intr->getNumValues() - 1),
5178     Intr->getOperand(0));
5179 
5180   return Chain;
5181 }
5182 
5183 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5184                                           SelectionDAG &DAG) const {
5185   MVT VT = Op.getSimpleValueType();
5186   SDLoc DL(Op);
5187   // Checking the depth
5188   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5189     return DAG.getConstant(0, DL, VT);
5190 
5191   MachineFunction &MF = DAG.getMachineFunction();
5192   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5193   // Check for kernel and shader functions
5194   if (Info->isEntryFunction())
5195     return DAG.getConstant(0, DL, VT);
5196 
5197   MachineFrameInfo &MFI = MF.getFrameInfo();
5198   // There is a call to @llvm.returnaddress in this function
5199   MFI.setReturnAddressIsTaken(true);
5200 
5201   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5202   // Get the return address reg and mark it as an implicit live-in
5203   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5204 
5205   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5206 }
5207 
5208 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5209                                             SDValue Op,
5210                                             const SDLoc &DL,
5211                                             EVT VT) const {
5212   return Op.getValueType().bitsLE(VT) ?
5213       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5214     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5215                 DAG.getTargetConstant(0, DL, MVT::i32));
5216 }
5217 
5218 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5219   assert(Op.getValueType() == MVT::f16 &&
5220          "Do not know how to custom lower FP_ROUND for non-f16 type");
5221 
5222   SDValue Src = Op.getOperand(0);
5223   EVT SrcVT = Src.getValueType();
5224   if (SrcVT != MVT::f64)
5225     return Op;
5226 
5227   SDLoc DL(Op);
5228 
5229   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5230   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5231   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5232 }
5233 
5234 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5235                                                SelectionDAG &DAG) const {
5236   EVT VT = Op.getValueType();
5237   const MachineFunction &MF = DAG.getMachineFunction();
5238   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5239   bool IsIEEEMode = Info->getMode().IEEE;
5240 
5241   // FIXME: Assert during selection that this is only selected for
5242   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5243   // mode functions, but this happens to be OK since it's only done in cases
5244   // where there is known no sNaN.
5245   if (IsIEEEMode)
5246     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5247 
5248   if (VT == MVT::v4f16)
5249     return splitBinaryVectorOp(Op, DAG);
5250   return Op;
5251 }
5252 
5253 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5254   EVT VT = Op.getValueType();
5255   SDLoc SL(Op);
5256   SDValue LHS = Op.getOperand(0);
5257   SDValue RHS = Op.getOperand(1);
5258   bool isSigned = Op.getOpcode() == ISD::SMULO;
5259 
5260   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5261     const APInt &C = RHSC->getAPIntValue();
5262     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5263     if (C.isPowerOf2()) {
5264       // smulo(x, signed_min) is same as umulo(x, signed_min).
5265       bool UseArithShift = isSigned && !C.isMinSignedValue();
5266       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5267       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5268       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5269           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5270                       SL, VT, Result, ShiftAmt),
5271           LHS, ISD::SETNE);
5272       return DAG.getMergeValues({ Result, Overflow }, SL);
5273     }
5274   }
5275 
5276   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5277   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5278                             SL, VT, LHS, RHS);
5279 
5280   SDValue Sign = isSigned
5281     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5282                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5283     : DAG.getConstant(0, SL, VT);
5284   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5285 
5286   return DAG.getMergeValues({ Result, Overflow }, SL);
5287 }
5288 
5289 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5290   if (!Subtarget->isTrapHandlerEnabled() ||
5291       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5292     return lowerTrapEndpgm(Op, DAG);
5293 
5294   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5295     switch (*HsaAbiVer) {
5296     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5297     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5298       return lowerTrapHsaQueuePtr(Op, DAG);
5299     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5300       return Subtarget->supportsGetDoorbellID() ?
5301           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5302     }
5303   }
5304 
5305   llvm_unreachable("Unknown trap handler");
5306 }
5307 
5308 SDValue SITargetLowering::lowerTrapEndpgm(
5309     SDValue Op, SelectionDAG &DAG) const {
5310   SDLoc SL(Op);
5311   SDValue Chain = Op.getOperand(0);
5312   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5313 }
5314 
5315 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5316     SDValue Op, SelectionDAG &DAG) const {
5317   SDLoc SL(Op);
5318   SDValue Chain = Op.getOperand(0);
5319 
5320   MachineFunction &MF = DAG.getMachineFunction();
5321   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5322   Register UserSGPR = Info->getQueuePtrUserSGPR();
5323 
5324   SDValue QueuePtr;
5325   if (UserSGPR == AMDGPU::NoRegister) {
5326     // We probably are in a function incorrectly marked with
5327     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5328     // so just use a null pointer.
5329     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5330   } else {
5331     QueuePtr = CreateLiveInRegister(
5332       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5333   }
5334 
5335   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5336   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5337                                    QueuePtr, SDValue());
5338 
5339   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5340   SDValue Ops[] = {
5341     ToReg,
5342     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5343     SGPR01,
5344     ToReg.getValue(1)
5345   };
5346   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5347 }
5348 
5349 SDValue SITargetLowering::lowerTrapHsa(
5350     SDValue Op, SelectionDAG &DAG) const {
5351   SDLoc SL(Op);
5352   SDValue Chain = Op.getOperand(0);
5353 
5354   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5355   SDValue Ops[] = {
5356     Chain,
5357     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5358   };
5359   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5360 }
5361 
5362 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5363   SDLoc SL(Op);
5364   SDValue Chain = Op.getOperand(0);
5365   MachineFunction &MF = DAG.getMachineFunction();
5366 
5367   if (!Subtarget->isTrapHandlerEnabled() ||
5368       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5369     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5370                                      "debugtrap handler not supported",
5371                                      Op.getDebugLoc(),
5372                                      DS_Warning);
5373     LLVMContext &Ctx = MF.getFunction().getContext();
5374     Ctx.diagnose(NoTrap);
5375     return Chain;
5376   }
5377 
5378   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5379   SDValue Ops[] = {
5380     Chain,
5381     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5382   };
5383   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5384 }
5385 
5386 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5387                                              SelectionDAG &DAG) const {
5388   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5389   if (Subtarget->hasApertureRegs()) {
5390     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5391         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5392         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5393     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5394         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5395         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5396     unsigned Encoding =
5397         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5398         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5399         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5400 
5401     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5402     SDValue ApertureReg = SDValue(
5403         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5404     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5405     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5406   }
5407 
5408   MachineFunction &MF = DAG.getMachineFunction();
5409   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5410   Register UserSGPR = Info->getQueuePtrUserSGPR();
5411   if (UserSGPR == AMDGPU::NoRegister) {
5412     // We probably are in a function incorrectly marked with
5413     // amdgpu-no-queue-ptr. This is undefined.
5414     return DAG.getUNDEF(MVT::i32);
5415   }
5416 
5417   SDValue QueuePtr = CreateLiveInRegister(
5418     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5419 
5420   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5421   // private_segment_aperture_base_hi.
5422   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5423 
5424   SDValue Ptr =
5425       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5426 
5427   // TODO: Use custom target PseudoSourceValue.
5428   // TODO: We should use the value from the IR intrinsic call, but it might not
5429   // be available and how do we get it?
5430   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5431   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5432                      commonAlignment(Align(64), StructOffset),
5433                      MachineMemOperand::MODereferenceable |
5434                          MachineMemOperand::MOInvariant);
5435 }
5436 
5437 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5438                                              SelectionDAG &DAG) const {
5439   SDLoc SL(Op);
5440   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5441 
5442   SDValue Src = ASC->getOperand(0);
5443   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5444 
5445   const AMDGPUTargetMachine &TM =
5446     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5447 
5448   // flat -> local/private
5449   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5450     unsigned DestAS = ASC->getDestAddressSpace();
5451 
5452     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5453         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5454       unsigned NullVal = TM.getNullPointerValue(DestAS);
5455       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5456       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5457       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5458 
5459       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5460                          NonNull, Ptr, SegmentNullPtr);
5461     }
5462   }
5463 
5464   // local/private -> flat
5465   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5466     unsigned SrcAS = ASC->getSrcAddressSpace();
5467 
5468     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5469         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5470       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5471       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5472 
5473       SDValue NonNull
5474         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5475 
5476       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5477       SDValue CvtPtr
5478         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5479 
5480       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5481                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5482                          FlatNullPtr);
5483     }
5484   }
5485 
5486   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5487       Src.getValueType() == MVT::i64)
5488     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5489 
5490   // global <-> flat are no-ops and never emitted.
5491 
5492   const MachineFunction &MF = DAG.getMachineFunction();
5493   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5494     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5495   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5496 
5497   return DAG.getUNDEF(ASC->getValueType(0));
5498 }
5499 
5500 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5501 // the small vector and inserting them into the big vector. That is better than
5502 // the default expansion of doing it via a stack slot. Even though the use of
5503 // the stack slot would be optimized away afterwards, the stack slot itself
5504 // remains.
5505 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5506                                                 SelectionDAG &DAG) const {
5507   SDValue Vec = Op.getOperand(0);
5508   SDValue Ins = Op.getOperand(1);
5509   SDValue Idx = Op.getOperand(2);
5510   EVT VecVT = Vec.getValueType();
5511   EVT InsVT = Ins.getValueType();
5512   EVT EltVT = VecVT.getVectorElementType();
5513   unsigned InsNumElts = InsVT.getVectorNumElements();
5514   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5515   SDLoc SL(Op);
5516 
5517   for (unsigned I = 0; I != InsNumElts; ++I) {
5518     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5519                               DAG.getConstant(I, SL, MVT::i32));
5520     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5521                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5522   }
5523   return Vec;
5524 }
5525 
5526 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5527                                                  SelectionDAG &DAG) const {
5528   SDValue Vec = Op.getOperand(0);
5529   SDValue InsVal = Op.getOperand(1);
5530   SDValue Idx = Op.getOperand(2);
5531   EVT VecVT = Vec.getValueType();
5532   EVT EltVT = VecVT.getVectorElementType();
5533   unsigned VecSize = VecVT.getSizeInBits();
5534   unsigned EltSize = EltVT.getSizeInBits();
5535 
5536 
5537   assert(VecSize <= 64);
5538 
5539   unsigned NumElts = VecVT.getVectorNumElements();
5540   SDLoc SL(Op);
5541   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5542 
5543   if (NumElts == 4 && EltSize == 16 && KIdx) {
5544     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5545 
5546     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5547                                  DAG.getConstant(0, SL, MVT::i32));
5548     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5549                                  DAG.getConstant(1, SL, MVT::i32));
5550 
5551     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5552     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5553 
5554     unsigned Idx = KIdx->getZExtValue();
5555     bool InsertLo = Idx < 2;
5556     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5557       InsertLo ? LoVec : HiVec,
5558       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5559       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5560 
5561     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5562 
5563     SDValue Concat = InsertLo ?
5564       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5565       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5566 
5567     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5568   }
5569 
5570   if (isa<ConstantSDNode>(Idx))
5571     return SDValue();
5572 
5573   MVT IntVT = MVT::getIntegerVT(VecSize);
5574 
5575   // Avoid stack access for dynamic indexing.
5576   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5577 
5578   // Create a congruent vector with the target value in each element so that
5579   // the required element can be masked and ORed into the target vector.
5580   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5581                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5582 
5583   assert(isPowerOf2_32(EltSize));
5584   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5585 
5586   // Convert vector index to bit-index.
5587   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5588 
5589   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5590   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5591                             DAG.getConstant(0xffff, SL, IntVT),
5592                             ScaledIdx);
5593 
5594   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5595   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5596                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5597 
5598   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5599   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5600 }
5601 
5602 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5603                                                   SelectionDAG &DAG) const {
5604   SDLoc SL(Op);
5605 
5606   EVT ResultVT = Op.getValueType();
5607   SDValue Vec = Op.getOperand(0);
5608   SDValue Idx = Op.getOperand(1);
5609   EVT VecVT = Vec.getValueType();
5610   unsigned VecSize = VecVT.getSizeInBits();
5611   EVT EltVT = VecVT.getVectorElementType();
5612   assert(VecSize <= 64);
5613 
5614   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5615 
5616   // Make sure we do any optimizations that will make it easier to fold
5617   // source modifiers before obscuring it with bit operations.
5618 
5619   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5620   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5621     return Combined;
5622 
5623   unsigned EltSize = EltVT.getSizeInBits();
5624   assert(isPowerOf2_32(EltSize));
5625 
5626   MVT IntVT = MVT::getIntegerVT(VecSize);
5627   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5628 
5629   // Convert vector index to bit-index (* EltSize)
5630   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5631 
5632   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5633   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5634 
5635   if (ResultVT == MVT::f16) {
5636     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5637     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5638   }
5639 
5640   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5641 }
5642 
5643 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5644   assert(Elt % 2 == 0);
5645   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5646 }
5647 
5648 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5649                                               SelectionDAG &DAG) const {
5650   SDLoc SL(Op);
5651   EVT ResultVT = Op.getValueType();
5652   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5653 
5654   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5655   EVT EltVT = PackVT.getVectorElementType();
5656   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5657 
5658   // vector_shuffle <0,1,6,7> lhs, rhs
5659   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5660   //
5661   // vector_shuffle <6,7,2,3> lhs, rhs
5662   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5663   //
5664   // vector_shuffle <6,7,0,1> lhs, rhs
5665   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5666 
5667   // Avoid scalarizing when both halves are reading from consecutive elements.
5668   SmallVector<SDValue, 4> Pieces;
5669   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5670     if (elementPairIsContiguous(SVN->getMask(), I)) {
5671       const int Idx = SVN->getMaskElt(I);
5672       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5673       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5674       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5675                                     PackVT, SVN->getOperand(VecIdx),
5676                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5677       Pieces.push_back(SubVec);
5678     } else {
5679       const int Idx0 = SVN->getMaskElt(I);
5680       const int Idx1 = SVN->getMaskElt(I + 1);
5681       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5682       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5683       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5684       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5685 
5686       SDValue Vec0 = SVN->getOperand(VecIdx0);
5687       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5688                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5689 
5690       SDValue Vec1 = SVN->getOperand(VecIdx1);
5691       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5692                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5693       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5694     }
5695   }
5696 
5697   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5698 }
5699 
5700 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5701                                             SelectionDAG &DAG) const {
5702   SDLoc SL(Op);
5703   EVT VT = Op.getValueType();
5704 
5705   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5706     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5707 
5708     // Turn into pair of packed build_vectors.
5709     // TODO: Special case for constants that can be materialized with s_mov_b64.
5710     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5711                                     { Op.getOperand(0), Op.getOperand(1) });
5712     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5713                                     { Op.getOperand(2), Op.getOperand(3) });
5714 
5715     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5716     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5717 
5718     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5719     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5720   }
5721 
5722   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5723   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5724 
5725   SDValue Lo = Op.getOperand(0);
5726   SDValue Hi = Op.getOperand(1);
5727 
5728   // Avoid adding defined bits with the zero_extend.
5729   if (Hi.isUndef()) {
5730     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5731     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5732     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5733   }
5734 
5735   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5736   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5737 
5738   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5739                               DAG.getConstant(16, SL, MVT::i32));
5740   if (Lo.isUndef())
5741     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5742 
5743   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5744   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5745 
5746   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5747   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5748 }
5749 
5750 bool
5751 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5752   // We can fold offsets for anything that doesn't require a GOT relocation.
5753   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5754           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5755           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5756          !shouldEmitGOTReloc(GA->getGlobal());
5757 }
5758 
5759 static SDValue
5760 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5761                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5762                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5763   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5764   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5765   // lowered to the following code sequence:
5766   //
5767   // For constant address space:
5768   //   s_getpc_b64 s[0:1]
5769   //   s_add_u32 s0, s0, $symbol
5770   //   s_addc_u32 s1, s1, 0
5771   //
5772   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5773   //   a fixup or relocation is emitted to replace $symbol with a literal
5774   //   constant, which is a pc-relative offset from the encoding of the $symbol
5775   //   operand to the global variable.
5776   //
5777   // For global address space:
5778   //   s_getpc_b64 s[0:1]
5779   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5780   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5781   //
5782   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5783   //   fixups or relocations are emitted to replace $symbol@*@lo and
5784   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5785   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5786   //   operand to the global variable.
5787   //
5788   // What we want here is an offset from the value returned by s_getpc
5789   // (which is the address of the s_add_u32 instruction) to the global
5790   // variable, but since the encoding of $symbol starts 4 bytes after the start
5791   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5792   // small. This requires us to add 4 to the global variable offset in order to
5793   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5794   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5795   // instruction.
5796   SDValue PtrLo =
5797       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5798   SDValue PtrHi;
5799   if (GAFlags == SIInstrInfo::MO_NONE) {
5800     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5801   } else {
5802     PtrHi =
5803         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5804   }
5805   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5806 }
5807 
5808 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5809                                              SDValue Op,
5810                                              SelectionDAG &DAG) const {
5811   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5812   SDLoc DL(GSD);
5813   EVT PtrVT = Op.getValueType();
5814 
5815   const GlobalValue *GV = GSD->getGlobal();
5816   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5817        shouldUseLDSConstAddress(GV)) ||
5818       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5819       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5820     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5821         GV->hasExternalLinkage()) {
5822       Type *Ty = GV->getValueType();
5823       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5824       // zero-sized type in other languages to declare the dynamic shared
5825       // memory which size is not known at the compile time. They will be
5826       // allocated by the runtime and placed directly after the static
5827       // allocated ones. They all share the same offset.
5828       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5829         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5830         // Adjust alignment for that dynamic shared memory array.
5831         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5832         return SDValue(
5833             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5834       }
5835     }
5836     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5837   }
5838 
5839   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5840     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5841                                             SIInstrInfo::MO_ABS32_LO);
5842     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5843   }
5844 
5845   if (shouldEmitFixup(GV))
5846     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5847   else if (shouldEmitPCReloc(GV))
5848     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5849                                    SIInstrInfo::MO_REL32);
5850 
5851   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5852                                             SIInstrInfo::MO_GOTPCREL32);
5853 
5854   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5855   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5856   const DataLayout &DataLayout = DAG.getDataLayout();
5857   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5858   MachinePointerInfo PtrInfo
5859     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5860 
5861   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5862                      MachineMemOperand::MODereferenceable |
5863                          MachineMemOperand::MOInvariant);
5864 }
5865 
5866 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5867                                    const SDLoc &DL, SDValue V) const {
5868   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5869   // the destination register.
5870   //
5871   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5872   // so we will end up with redundant moves to m0.
5873   //
5874   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5875 
5876   // A Null SDValue creates a glue result.
5877   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5878                                   V, Chain);
5879   return SDValue(M0, 0);
5880 }
5881 
5882 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5883                                                  SDValue Op,
5884                                                  MVT VT,
5885                                                  unsigned Offset) const {
5886   SDLoc SL(Op);
5887   SDValue Param = lowerKernargMemParameter(
5888       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5889   // The local size values will have the hi 16-bits as zero.
5890   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5891                      DAG.getValueType(VT));
5892 }
5893 
5894 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5895                                         EVT VT) {
5896   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5897                                       "non-hsa intrinsic with hsa target",
5898                                       DL.getDebugLoc());
5899   DAG.getContext()->diagnose(BadIntrin);
5900   return DAG.getUNDEF(VT);
5901 }
5902 
5903 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5904                                          EVT VT) {
5905   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5906                                       "intrinsic not supported on subtarget",
5907                                       DL.getDebugLoc());
5908   DAG.getContext()->diagnose(BadIntrin);
5909   return DAG.getUNDEF(VT);
5910 }
5911 
5912 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5913                                     ArrayRef<SDValue> Elts) {
5914   assert(!Elts.empty());
5915   MVT Type;
5916   unsigned NumElts = Elts.size();
5917 
5918   if (NumElts <= 8) {
5919     Type = MVT::getVectorVT(MVT::f32, NumElts);
5920   } else {
5921     assert(Elts.size() <= 16);
5922     Type = MVT::v16f32;
5923     NumElts = 16;
5924   }
5925 
5926   SmallVector<SDValue, 16> VecElts(NumElts);
5927   for (unsigned i = 0; i < Elts.size(); ++i) {
5928     SDValue Elt = Elts[i];
5929     if (Elt.getValueType() != MVT::f32)
5930       Elt = DAG.getBitcast(MVT::f32, Elt);
5931     VecElts[i] = Elt;
5932   }
5933   for (unsigned i = Elts.size(); i < NumElts; ++i)
5934     VecElts[i] = DAG.getUNDEF(MVT::f32);
5935 
5936   if (NumElts == 1)
5937     return VecElts[0];
5938   return DAG.getBuildVector(Type, DL, VecElts);
5939 }
5940 
5941 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5942                               SDValue Src, int ExtraElts) {
5943   EVT SrcVT = Src.getValueType();
5944 
5945   SmallVector<SDValue, 8> Elts;
5946 
5947   if (SrcVT.isVector())
5948     DAG.ExtractVectorElements(Src, Elts);
5949   else
5950     Elts.push_back(Src);
5951 
5952   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5953   while (ExtraElts--)
5954     Elts.push_back(Undef);
5955 
5956   return DAG.getBuildVector(CastVT, DL, Elts);
5957 }
5958 
5959 // Re-construct the required return value for a image load intrinsic.
5960 // This is more complicated due to the optional use TexFailCtrl which means the required
5961 // return type is an aggregate
5962 static SDValue constructRetValue(SelectionDAG &DAG,
5963                                  MachineSDNode *Result,
5964                                  ArrayRef<EVT> ResultTypes,
5965                                  bool IsTexFail, bool Unpacked, bool IsD16,
5966                                  int DMaskPop, int NumVDataDwords,
5967                                  const SDLoc &DL) {
5968   // Determine the required return type. This is the same regardless of IsTexFail flag
5969   EVT ReqRetVT = ResultTypes[0];
5970   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5971   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5972     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5973 
5974   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5975     DMaskPop : (DMaskPop + 1) / 2;
5976 
5977   MVT DataDwordVT = NumDataDwords == 1 ?
5978     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5979 
5980   MVT MaskPopVT = MaskPopDwords == 1 ?
5981     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5982 
5983   SDValue Data(Result, 0);
5984   SDValue TexFail;
5985 
5986   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5987     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5988     if (MaskPopVT.isVector()) {
5989       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5990                          SDValue(Result, 0), ZeroIdx);
5991     } else {
5992       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5993                          SDValue(Result, 0), ZeroIdx);
5994     }
5995   }
5996 
5997   if (DataDwordVT.isVector())
5998     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5999                           NumDataDwords - MaskPopDwords);
6000 
6001   if (IsD16)
6002     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6003 
6004   EVT LegalReqRetVT = ReqRetVT;
6005   if (!ReqRetVT.isVector()) {
6006     if (!Data.getValueType().isInteger())
6007       Data = DAG.getNode(ISD::BITCAST, DL,
6008                          Data.getValueType().changeTypeToInteger(), Data);
6009     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6010   } else {
6011     // We need to widen the return vector to a legal type
6012     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6013         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6014       LegalReqRetVT =
6015           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6016                            ReqRetVT.getVectorNumElements() + 1);
6017     }
6018   }
6019   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6020 
6021   if (IsTexFail) {
6022     TexFail =
6023         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6024                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6025 
6026     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6027   }
6028 
6029   if (Result->getNumValues() == 1)
6030     return Data;
6031 
6032   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6033 }
6034 
6035 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6036                          SDValue *LWE, bool &IsTexFail) {
6037   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6038 
6039   uint64_t Value = TexFailCtrlConst->getZExtValue();
6040   if (Value) {
6041     IsTexFail = true;
6042   }
6043 
6044   SDLoc DL(TexFailCtrlConst);
6045   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6046   Value &= ~(uint64_t)0x1;
6047   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6048   Value &= ~(uint64_t)0x2;
6049 
6050   return Value == 0;
6051 }
6052 
6053 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6054                                       MVT PackVectorVT,
6055                                       SmallVectorImpl<SDValue> &PackedAddrs,
6056                                       unsigned DimIdx, unsigned EndIdx,
6057                                       unsigned NumGradients) {
6058   SDLoc DL(Op);
6059   for (unsigned I = DimIdx; I < EndIdx; I++) {
6060     SDValue Addr = Op.getOperand(I);
6061 
6062     // Gradients are packed with undef for each coordinate.
6063     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6064     // 1D: undef,dx/dh; undef,dx/dv
6065     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6066     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6067     if (((I + 1) >= EndIdx) ||
6068         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6069                                          I == DimIdx + NumGradients - 1))) {
6070       if (Addr.getValueType() != MVT::i16)
6071         Addr = DAG.getBitcast(MVT::i16, Addr);
6072       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6073     } else {
6074       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6075       I++;
6076     }
6077     Addr = DAG.getBitcast(MVT::f32, Addr);
6078     PackedAddrs.push_back(Addr);
6079   }
6080 }
6081 
6082 SDValue SITargetLowering::lowerImage(SDValue Op,
6083                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6084                                      SelectionDAG &DAG, bool WithChain) const {
6085   SDLoc DL(Op);
6086   MachineFunction &MF = DAG.getMachineFunction();
6087   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6088   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6089       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6090   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6091   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6092       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6093   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6094       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6095   unsigned IntrOpcode = Intr->BaseOpcode;
6096   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6097 
6098   SmallVector<EVT, 3> ResultTypes(Op->values());
6099   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6100   bool IsD16 = false;
6101   bool IsG16 = false;
6102   bool IsA16 = false;
6103   SDValue VData;
6104   int NumVDataDwords;
6105   bool AdjustRetType = false;
6106 
6107   // Offset of intrinsic arguments
6108   const unsigned ArgOffset = WithChain ? 2 : 1;
6109 
6110   unsigned DMask;
6111   unsigned DMaskLanes = 0;
6112 
6113   if (BaseOpcode->Atomic) {
6114     VData = Op.getOperand(2);
6115 
6116     bool Is64Bit = VData.getValueType() == MVT::i64;
6117     if (BaseOpcode->AtomicX2) {
6118       SDValue VData2 = Op.getOperand(3);
6119       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6120                                  {VData, VData2});
6121       if (Is64Bit)
6122         VData = DAG.getBitcast(MVT::v4i32, VData);
6123 
6124       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6125       DMask = Is64Bit ? 0xf : 0x3;
6126       NumVDataDwords = Is64Bit ? 4 : 2;
6127     } else {
6128       DMask = Is64Bit ? 0x3 : 0x1;
6129       NumVDataDwords = Is64Bit ? 2 : 1;
6130     }
6131   } else {
6132     auto *DMaskConst =
6133         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6134     DMask = DMaskConst->getZExtValue();
6135     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6136 
6137     if (BaseOpcode->Store) {
6138       VData = Op.getOperand(2);
6139 
6140       MVT StoreVT = VData.getSimpleValueType();
6141       if (StoreVT.getScalarType() == MVT::f16) {
6142         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6143           return Op; // D16 is unsupported for this instruction
6144 
6145         IsD16 = true;
6146         VData = handleD16VData(VData, DAG, true);
6147       }
6148 
6149       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6150     } else {
6151       // Work out the num dwords based on the dmask popcount and underlying type
6152       // and whether packing is supported.
6153       MVT LoadVT = ResultTypes[0].getSimpleVT();
6154       if (LoadVT.getScalarType() == MVT::f16) {
6155         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6156           return Op; // D16 is unsupported for this instruction
6157 
6158         IsD16 = true;
6159       }
6160 
6161       // Confirm that the return type is large enough for the dmask specified
6162       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6163           (!LoadVT.isVector() && DMaskLanes > 1))
6164           return Op;
6165 
6166       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6167       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6168       // instructions.
6169       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6170           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6171         NumVDataDwords = (DMaskLanes + 1) / 2;
6172       else
6173         NumVDataDwords = DMaskLanes;
6174 
6175       AdjustRetType = true;
6176     }
6177   }
6178 
6179   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6180   SmallVector<SDValue, 4> VAddrs;
6181 
6182   // Optimize _L to _LZ when _L is zero
6183   if (LZMappingInfo) {
6184     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6185             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6186       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6187         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6188         VAddrEnd--;                      // remove 'lod'
6189       }
6190     }
6191   }
6192 
6193   // Optimize _mip away, when 'lod' is zero
6194   if (MIPMappingInfo) {
6195     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6196             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6197       if (ConstantLod->isZero()) {
6198         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6199         VAddrEnd--;                           // remove 'mip'
6200       }
6201     }
6202   }
6203 
6204   // Push back extra arguments.
6205   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6206     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6207 
6208   // Check for 16 bit addresses or derivatives and pack if true.
6209   MVT VAddrVT =
6210       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6211   MVT VAddrScalarVT = VAddrVT.getScalarType();
6212   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6213   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6214 
6215   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6216   VAddrScalarVT = VAddrVT.getScalarType();
6217   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6218   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6219 
6220   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6221     // 16 bit gradients are supported, but are tied to the A16 control
6222     // so both gradients and addresses must be 16 bit
6223     LLVM_DEBUG(
6224         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6225                   "require 16 bit args for both gradients and addresses");
6226     return Op;
6227   }
6228 
6229   if (IsA16) {
6230     if (!ST->hasA16()) {
6231       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6232                            "support 16 bit addresses\n");
6233       return Op;
6234     }
6235   }
6236 
6237   // We've dealt with incorrect input so we know that if IsA16, IsG16
6238   // are set then we have to compress/pack operands (either address,
6239   // gradient or both)
6240   // In the case where a16 and gradients are tied (no G16 support) then we
6241   // have already verified that both IsA16 and IsG16 are true
6242   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6243     // Activate g16
6244     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6245         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6246     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6247   }
6248 
6249   // Add gradients (packed or unpacked)
6250   if (IsG16) {
6251     // Pack the gradients
6252     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6253     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6254                               ArgOffset + Intr->GradientStart,
6255                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6256   } else {
6257     for (unsigned I = ArgOffset + Intr->GradientStart;
6258          I < ArgOffset + Intr->CoordStart; I++)
6259       VAddrs.push_back(Op.getOperand(I));
6260   }
6261 
6262   // Add addresses (packed or unpacked)
6263   if (IsA16) {
6264     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6265                               ArgOffset + Intr->CoordStart, VAddrEnd,
6266                               0 /* No gradients */);
6267   } else {
6268     // Add uncompressed address
6269     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6270       VAddrs.push_back(Op.getOperand(I));
6271   }
6272 
6273   // If the register allocator cannot place the address registers contiguously
6274   // without introducing moves, then using the non-sequential address encoding
6275   // is always preferable, since it saves VALU instructions and is usually a
6276   // wash in terms of code size or even better.
6277   //
6278   // However, we currently have no way of hinting to the register allocator that
6279   // MIMG addresses should be placed contiguously when it is possible to do so,
6280   // so force non-NSA for the common 2-address case as a heuristic.
6281   //
6282   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6283   // allocation when possible.
6284   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6285                 VAddrs.size() >= 3 &&
6286                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6287   SDValue VAddr;
6288   if (!UseNSA)
6289     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6290 
6291   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6292   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6293   SDValue Unorm;
6294   if (!BaseOpcode->Sampler) {
6295     Unorm = True;
6296   } else {
6297     auto UnormConst =
6298         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6299 
6300     Unorm = UnormConst->getZExtValue() ? True : False;
6301   }
6302 
6303   SDValue TFE;
6304   SDValue LWE;
6305   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6306   bool IsTexFail = false;
6307   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6308     return Op;
6309 
6310   if (IsTexFail) {
6311     if (!DMaskLanes) {
6312       // Expecting to get an error flag since TFC is on - and dmask is 0
6313       // Force dmask to be at least 1 otherwise the instruction will fail
6314       DMask = 0x1;
6315       DMaskLanes = 1;
6316       NumVDataDwords = 1;
6317     }
6318     NumVDataDwords += 1;
6319     AdjustRetType = true;
6320   }
6321 
6322   // Has something earlier tagged that the return type needs adjusting
6323   // This happens if the instruction is a load or has set TexFailCtrl flags
6324   if (AdjustRetType) {
6325     // NumVDataDwords reflects the true number of dwords required in the return type
6326     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6327       // This is a no-op load. This can be eliminated
6328       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6329       if (isa<MemSDNode>(Op))
6330         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6331       return Undef;
6332     }
6333 
6334     EVT NewVT = NumVDataDwords > 1 ?
6335                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6336                 : MVT::i32;
6337 
6338     ResultTypes[0] = NewVT;
6339     if (ResultTypes.size() == 3) {
6340       // Original result was aggregate type used for TexFailCtrl results
6341       // The actual instruction returns as a vector type which has now been
6342       // created. Remove the aggregate result.
6343       ResultTypes.erase(&ResultTypes[1]);
6344     }
6345   }
6346 
6347   unsigned CPol = cast<ConstantSDNode>(
6348       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6349   if (BaseOpcode->Atomic)
6350     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6351   if (CPol & ~AMDGPU::CPol::ALL)
6352     return Op;
6353 
6354   SmallVector<SDValue, 26> Ops;
6355   if (BaseOpcode->Store || BaseOpcode->Atomic)
6356     Ops.push_back(VData); // vdata
6357   if (UseNSA)
6358     append_range(Ops, VAddrs);
6359   else
6360     Ops.push_back(VAddr);
6361   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6362   if (BaseOpcode->Sampler)
6363     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6364   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6365   if (IsGFX10Plus)
6366     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6367   Ops.push_back(Unorm);
6368   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6369   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6370                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6371   if (IsGFX10Plus)
6372     Ops.push_back(IsA16 ? True : False);
6373   if (!Subtarget->hasGFX90AInsts()) {
6374     Ops.push_back(TFE); //tfe
6375   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6376     report_fatal_error("TFE is not supported on this GPU");
6377   }
6378   Ops.push_back(LWE); // lwe
6379   if (!IsGFX10Plus)
6380     Ops.push_back(DimInfo->DA ? True : False);
6381   if (BaseOpcode->HasD16)
6382     Ops.push_back(IsD16 ? True : False);
6383   if (isa<MemSDNode>(Op))
6384     Ops.push_back(Op.getOperand(0)); // chain
6385 
6386   int NumVAddrDwords =
6387       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6388   int Opcode = -1;
6389 
6390   if (IsGFX10Plus) {
6391     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6392                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6393                                           : AMDGPU::MIMGEncGfx10Default,
6394                                    NumVDataDwords, NumVAddrDwords);
6395   } else {
6396     if (Subtarget->hasGFX90AInsts()) {
6397       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6398                                      NumVDataDwords, NumVAddrDwords);
6399       if (Opcode == -1)
6400         report_fatal_error(
6401             "requested image instruction is not supported on this GPU");
6402     }
6403     if (Opcode == -1 &&
6404         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6405       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6406                                      NumVDataDwords, NumVAddrDwords);
6407     if (Opcode == -1)
6408       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6409                                      NumVDataDwords, NumVAddrDwords);
6410   }
6411   assert(Opcode != -1);
6412 
6413   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6414   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6415     MachineMemOperand *MemRef = MemOp->getMemOperand();
6416     DAG.setNodeMemRefs(NewNode, {MemRef});
6417   }
6418 
6419   if (BaseOpcode->AtomicX2) {
6420     SmallVector<SDValue, 1> Elt;
6421     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6422     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6423   }
6424   if (BaseOpcode->Store)
6425     return SDValue(NewNode, 0);
6426   return constructRetValue(DAG, NewNode,
6427                            OrigResultTypes, IsTexFail,
6428                            Subtarget->hasUnpackedD16VMem(), IsD16,
6429                            DMaskLanes, NumVDataDwords, DL);
6430 }
6431 
6432 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6433                                        SDValue Offset, SDValue CachePolicy,
6434                                        SelectionDAG &DAG) const {
6435   MachineFunction &MF = DAG.getMachineFunction();
6436 
6437   const DataLayout &DataLayout = DAG.getDataLayout();
6438   Align Alignment =
6439       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6440 
6441   MachineMemOperand *MMO = MF.getMachineMemOperand(
6442       MachinePointerInfo(),
6443       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6444           MachineMemOperand::MOInvariant,
6445       VT.getStoreSize(), Alignment);
6446 
6447   if (!Offset->isDivergent()) {
6448     SDValue Ops[] = {
6449         Rsrc,
6450         Offset, // Offset
6451         CachePolicy
6452     };
6453 
6454     // Widen vec3 load to vec4.
6455     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6456       EVT WidenedVT =
6457           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6458       auto WidenedOp = DAG.getMemIntrinsicNode(
6459           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6460           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6461       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6462                                    DAG.getVectorIdxConstant(0, DL));
6463       return Subvector;
6464     }
6465 
6466     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6467                                    DAG.getVTList(VT), Ops, VT, MMO);
6468   }
6469 
6470   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6471   // assume that the buffer is unswizzled.
6472   SmallVector<SDValue, 4> Loads;
6473   unsigned NumLoads = 1;
6474   MVT LoadVT = VT.getSimpleVT();
6475   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6476   assert((LoadVT.getScalarType() == MVT::i32 ||
6477           LoadVT.getScalarType() == MVT::f32));
6478 
6479   if (NumElts == 8 || NumElts == 16) {
6480     NumLoads = NumElts / 4;
6481     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6482   }
6483 
6484   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6485   SDValue Ops[] = {
6486       DAG.getEntryNode(),                               // Chain
6487       Rsrc,                                             // rsrc
6488       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6489       {},                                               // voffset
6490       {},                                               // soffset
6491       {},                                               // offset
6492       CachePolicy,                                      // cachepolicy
6493       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6494   };
6495 
6496   // Use the alignment to ensure that the required offsets will fit into the
6497   // immediate offsets.
6498   setBufferOffsets(Offset, DAG, &Ops[3],
6499                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6500 
6501   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6502   for (unsigned i = 0; i < NumLoads; ++i) {
6503     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6504     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6505                                         LoadVT, MMO, DAG));
6506   }
6507 
6508   if (NumElts == 8 || NumElts == 16)
6509     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6510 
6511   return Loads[0];
6512 }
6513 
6514 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6515                                                   SelectionDAG &DAG) const {
6516   MachineFunction &MF = DAG.getMachineFunction();
6517   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6518 
6519   EVT VT = Op.getValueType();
6520   SDLoc DL(Op);
6521   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6522 
6523   // TODO: Should this propagate fast-math-flags?
6524 
6525   switch (IntrinsicID) {
6526   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6527     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6528       return emitNonHSAIntrinsicError(DAG, DL, VT);
6529     return getPreloadedValue(DAG, *MFI, VT,
6530                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6531   }
6532   case Intrinsic::amdgcn_dispatch_ptr:
6533   case Intrinsic::amdgcn_queue_ptr: {
6534     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6535       DiagnosticInfoUnsupported BadIntrin(
6536           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6537           DL.getDebugLoc());
6538       DAG.getContext()->diagnose(BadIntrin);
6539       return DAG.getUNDEF(VT);
6540     }
6541 
6542     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6543       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6544     return getPreloadedValue(DAG, *MFI, VT, RegID);
6545   }
6546   case Intrinsic::amdgcn_implicitarg_ptr: {
6547     if (MFI->isEntryFunction())
6548       return getImplicitArgPtr(DAG, DL);
6549     return getPreloadedValue(DAG, *MFI, VT,
6550                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6551   }
6552   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6553     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6554       // This only makes sense to call in a kernel, so just lower to null.
6555       return DAG.getConstant(0, DL, VT);
6556     }
6557 
6558     return getPreloadedValue(DAG, *MFI, VT,
6559                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6560   }
6561   case Intrinsic::amdgcn_dispatch_id: {
6562     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6563   }
6564   case Intrinsic::amdgcn_rcp:
6565     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6566   case Intrinsic::amdgcn_rsq:
6567     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6568   case Intrinsic::amdgcn_rsq_legacy:
6569     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6570       return emitRemovedIntrinsicError(DAG, DL, VT);
6571     return SDValue();
6572   case Intrinsic::amdgcn_rcp_legacy:
6573     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6574       return emitRemovedIntrinsicError(DAG, DL, VT);
6575     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6576   case Intrinsic::amdgcn_rsq_clamp: {
6577     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6578       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6579 
6580     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6581     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6582     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6583 
6584     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6585     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6586                               DAG.getConstantFP(Max, DL, VT));
6587     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6588                        DAG.getConstantFP(Min, DL, VT));
6589   }
6590   case Intrinsic::r600_read_ngroups_x:
6591     if (Subtarget->isAmdHsaOS())
6592       return emitNonHSAIntrinsicError(DAG, DL, VT);
6593 
6594     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6595                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6596                                     false);
6597   case Intrinsic::r600_read_ngroups_y:
6598     if (Subtarget->isAmdHsaOS())
6599       return emitNonHSAIntrinsicError(DAG, DL, VT);
6600 
6601     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6602                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6603                                     false);
6604   case Intrinsic::r600_read_ngroups_z:
6605     if (Subtarget->isAmdHsaOS())
6606       return emitNonHSAIntrinsicError(DAG, DL, VT);
6607 
6608     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6609                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6610                                     false);
6611   case Intrinsic::r600_read_global_size_x:
6612     if (Subtarget->isAmdHsaOS())
6613       return emitNonHSAIntrinsicError(DAG, DL, VT);
6614 
6615     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6616                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6617                                     Align(4), false);
6618   case Intrinsic::r600_read_global_size_y:
6619     if (Subtarget->isAmdHsaOS())
6620       return emitNonHSAIntrinsicError(DAG, DL, VT);
6621 
6622     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6623                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6624                                     Align(4), false);
6625   case Intrinsic::r600_read_global_size_z:
6626     if (Subtarget->isAmdHsaOS())
6627       return emitNonHSAIntrinsicError(DAG, DL, VT);
6628 
6629     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6630                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6631                                     Align(4), false);
6632   case Intrinsic::r600_read_local_size_x:
6633     if (Subtarget->isAmdHsaOS())
6634       return emitNonHSAIntrinsicError(DAG, DL, VT);
6635 
6636     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6637                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6638   case Intrinsic::r600_read_local_size_y:
6639     if (Subtarget->isAmdHsaOS())
6640       return emitNonHSAIntrinsicError(DAG, DL, VT);
6641 
6642     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6643                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6644   case Intrinsic::r600_read_local_size_z:
6645     if (Subtarget->isAmdHsaOS())
6646       return emitNonHSAIntrinsicError(DAG, DL, VT);
6647 
6648     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6649                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6650   case Intrinsic::amdgcn_workgroup_id_x:
6651     return getPreloadedValue(DAG, *MFI, VT,
6652                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6653   case Intrinsic::amdgcn_workgroup_id_y:
6654     return getPreloadedValue(DAG, *MFI, VT,
6655                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6656   case Intrinsic::amdgcn_workgroup_id_z:
6657     return getPreloadedValue(DAG, *MFI, VT,
6658                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6659   case Intrinsic::amdgcn_workitem_id_x:
6660     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6661                           SDLoc(DAG.getEntryNode()),
6662                           MFI->getArgInfo().WorkItemIDX);
6663   case Intrinsic::amdgcn_workitem_id_y:
6664     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6665                           SDLoc(DAG.getEntryNode()),
6666                           MFI->getArgInfo().WorkItemIDY);
6667   case Intrinsic::amdgcn_workitem_id_z:
6668     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6669                           SDLoc(DAG.getEntryNode()),
6670                           MFI->getArgInfo().WorkItemIDZ);
6671   case Intrinsic::amdgcn_wavefrontsize:
6672     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6673                            SDLoc(Op), MVT::i32);
6674   case Intrinsic::amdgcn_s_buffer_load: {
6675     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6676     if (CPol & ~AMDGPU::CPol::ALL)
6677       return Op;
6678     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6679                         DAG);
6680   }
6681   case Intrinsic::amdgcn_fdiv_fast:
6682     return lowerFDIV_FAST(Op, DAG);
6683   case Intrinsic::amdgcn_sin:
6684     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6685 
6686   case Intrinsic::amdgcn_cos:
6687     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6688 
6689   case Intrinsic::amdgcn_mul_u24:
6690     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6691   case Intrinsic::amdgcn_mul_i24:
6692     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6693 
6694   case Intrinsic::amdgcn_log_clamp: {
6695     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6696       return SDValue();
6697 
6698     return emitRemovedIntrinsicError(DAG, DL, VT);
6699   }
6700   case Intrinsic::amdgcn_ldexp:
6701     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6702                        Op.getOperand(1), Op.getOperand(2));
6703 
6704   case Intrinsic::amdgcn_fract:
6705     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6706 
6707   case Intrinsic::amdgcn_class:
6708     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6709                        Op.getOperand(1), Op.getOperand(2));
6710   case Intrinsic::amdgcn_div_fmas:
6711     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6712                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6713                        Op.getOperand(4));
6714 
6715   case Intrinsic::amdgcn_div_fixup:
6716     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6717                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6718 
6719   case Intrinsic::amdgcn_div_scale: {
6720     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6721 
6722     // Translate to the operands expected by the machine instruction. The
6723     // first parameter must be the same as the first instruction.
6724     SDValue Numerator = Op.getOperand(1);
6725     SDValue Denominator = Op.getOperand(2);
6726 
6727     // Note this order is opposite of the machine instruction's operations,
6728     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6729     // intrinsic has the numerator as the first operand to match a normal
6730     // division operation.
6731 
6732     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6733 
6734     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6735                        Denominator, Numerator);
6736   }
6737   case Intrinsic::amdgcn_icmp: {
6738     // There is a Pat that handles this variant, so return it as-is.
6739     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6740         Op.getConstantOperandVal(2) == 0 &&
6741         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6742       return Op;
6743     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6744   }
6745   case Intrinsic::amdgcn_fcmp: {
6746     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6747   }
6748   case Intrinsic::amdgcn_ballot:
6749     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6750   case Intrinsic::amdgcn_fmed3:
6751     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6752                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6753   case Intrinsic::amdgcn_fdot2:
6754     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6755                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6756                        Op.getOperand(4));
6757   case Intrinsic::amdgcn_fmul_legacy:
6758     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6759                        Op.getOperand(1), Op.getOperand(2));
6760   case Intrinsic::amdgcn_sffbh:
6761     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6762   case Intrinsic::amdgcn_sbfe:
6763     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6764                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6765   case Intrinsic::amdgcn_ubfe:
6766     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6767                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6768   case Intrinsic::amdgcn_cvt_pkrtz:
6769   case Intrinsic::amdgcn_cvt_pknorm_i16:
6770   case Intrinsic::amdgcn_cvt_pknorm_u16:
6771   case Intrinsic::amdgcn_cvt_pk_i16:
6772   case Intrinsic::amdgcn_cvt_pk_u16: {
6773     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6774     EVT VT = Op.getValueType();
6775     unsigned Opcode;
6776 
6777     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6778       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6779     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6780       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6781     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6782       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6783     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6784       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6785     else
6786       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6787 
6788     if (isTypeLegal(VT))
6789       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6790 
6791     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6792                                Op.getOperand(1), Op.getOperand(2));
6793     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6794   }
6795   case Intrinsic::amdgcn_fmad_ftz:
6796     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6797                        Op.getOperand(2), Op.getOperand(3));
6798 
6799   case Intrinsic::amdgcn_if_break:
6800     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6801                                       Op->getOperand(1), Op->getOperand(2)), 0);
6802 
6803   case Intrinsic::amdgcn_groupstaticsize: {
6804     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6805     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6806       return Op;
6807 
6808     const Module *M = MF.getFunction().getParent();
6809     const GlobalValue *GV =
6810         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6811     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6812                                             SIInstrInfo::MO_ABS32_LO);
6813     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6814   }
6815   case Intrinsic::amdgcn_is_shared:
6816   case Intrinsic::amdgcn_is_private: {
6817     SDLoc SL(Op);
6818     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6819       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6820     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6821     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6822                                  Op.getOperand(1));
6823 
6824     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6825                                 DAG.getConstant(1, SL, MVT::i32));
6826     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6827   }
6828   case Intrinsic::amdgcn_alignbit:
6829     return DAG.getNode(ISD::FSHR, DL, VT,
6830                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6831   case Intrinsic::amdgcn_perm:
6832     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6833                        Op.getOperand(2), Op.getOperand(3));
6834   case Intrinsic::amdgcn_reloc_constant: {
6835     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6836     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6837     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6838     auto RelocSymbol = cast<GlobalVariable>(
6839         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6840     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6841                                             SIInstrInfo::MO_ABS32_LO);
6842     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6843   }
6844   default:
6845     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6846             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6847       return lowerImage(Op, ImageDimIntr, DAG, false);
6848 
6849     return Op;
6850   }
6851 }
6852 
6853 /// Update \p MMO based on the offset inputs to an intrinsic.
6854 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6855                             SDValue SOffset, SDValue Offset,
6856                             SDValue VIndex = SDValue()) {
6857   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6858       !isa<ConstantSDNode>(Offset)) {
6859     // The combined offset is not known to be constant, so we cannot represent
6860     // it in the MMO. Give up.
6861     MMO->setValue((Value *)nullptr);
6862     return;
6863   }
6864 
6865   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6866                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6867     // The strided index component of the address is not known to be zero, so we
6868     // cannot represent it in the MMO. Give up.
6869     MMO->setValue((Value *)nullptr);
6870     return;
6871   }
6872 
6873   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6874                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6875                  cast<ConstantSDNode>(Offset)->getSExtValue());
6876 }
6877 
6878 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6879                                                      SelectionDAG &DAG,
6880                                                      unsigned NewOpcode) const {
6881   SDLoc DL(Op);
6882 
6883   SDValue VData = Op.getOperand(2);
6884   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6885   SDValue Ops[] = {
6886     Op.getOperand(0), // Chain
6887     VData,            // vdata
6888     Op.getOperand(3), // rsrc
6889     DAG.getConstant(0, DL, MVT::i32), // vindex
6890     Offsets.first,    // voffset
6891     Op.getOperand(5), // soffset
6892     Offsets.second,   // offset
6893     Op.getOperand(6), // cachepolicy
6894     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6895   };
6896 
6897   auto *M = cast<MemSDNode>(Op);
6898   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6899 
6900   EVT MemVT = VData.getValueType();
6901   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6902                                  M->getMemOperand());
6903 }
6904 
6905 // Return a value to use for the idxen operand by examining the vindex operand.
6906 static unsigned getIdxEn(SDValue VIndex) {
6907   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6908     // No need to set idxen if vindex is known to be zero.
6909     return VIndexC->getZExtValue() != 0;
6910   return 1;
6911 }
6912 
6913 SDValue
6914 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6915                                                 unsigned NewOpcode) const {
6916   SDLoc DL(Op);
6917 
6918   SDValue VData = Op.getOperand(2);
6919   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6920   SDValue Ops[] = {
6921     Op.getOperand(0), // Chain
6922     VData,            // vdata
6923     Op.getOperand(3), // rsrc
6924     Op.getOperand(4), // vindex
6925     Offsets.first,    // voffset
6926     Op.getOperand(6), // soffset
6927     Offsets.second,   // offset
6928     Op.getOperand(7), // cachepolicy
6929     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6930   };
6931 
6932   auto *M = cast<MemSDNode>(Op);
6933   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
6934 
6935   EVT MemVT = VData.getValueType();
6936   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6937                                  M->getMemOperand());
6938 }
6939 
6940 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6941                                                  SelectionDAG &DAG) const {
6942   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6943   SDLoc DL(Op);
6944 
6945   switch (IntrID) {
6946   case Intrinsic::amdgcn_ds_ordered_add:
6947   case Intrinsic::amdgcn_ds_ordered_swap: {
6948     MemSDNode *M = cast<MemSDNode>(Op);
6949     SDValue Chain = M->getOperand(0);
6950     SDValue M0 = M->getOperand(2);
6951     SDValue Value = M->getOperand(3);
6952     unsigned IndexOperand = M->getConstantOperandVal(7);
6953     unsigned WaveRelease = M->getConstantOperandVal(8);
6954     unsigned WaveDone = M->getConstantOperandVal(9);
6955 
6956     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6957     IndexOperand &= ~0x3f;
6958     unsigned CountDw = 0;
6959 
6960     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6961       CountDw = (IndexOperand >> 24) & 0xf;
6962       IndexOperand &= ~(0xf << 24);
6963 
6964       if (CountDw < 1 || CountDw > 4) {
6965         report_fatal_error(
6966             "ds_ordered_count: dword count must be between 1 and 4");
6967       }
6968     }
6969 
6970     if (IndexOperand)
6971       report_fatal_error("ds_ordered_count: bad index operand");
6972 
6973     if (WaveDone && !WaveRelease)
6974       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6975 
6976     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6977     unsigned ShaderType =
6978         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6979     unsigned Offset0 = OrderedCountIndex << 2;
6980     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6981                        (Instruction << 4);
6982 
6983     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6984       Offset1 |= (CountDw - 1) << 6;
6985 
6986     unsigned Offset = Offset0 | (Offset1 << 8);
6987 
6988     SDValue Ops[] = {
6989       Chain,
6990       Value,
6991       DAG.getTargetConstant(Offset, DL, MVT::i16),
6992       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6993     };
6994     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6995                                    M->getVTList(), Ops, M->getMemoryVT(),
6996                                    M->getMemOperand());
6997   }
6998   case Intrinsic::amdgcn_ds_fadd: {
6999     MemSDNode *M = cast<MemSDNode>(Op);
7000     unsigned Opc;
7001     switch (IntrID) {
7002     case Intrinsic::amdgcn_ds_fadd:
7003       Opc = ISD::ATOMIC_LOAD_FADD;
7004       break;
7005     }
7006 
7007     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7008                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7009                          M->getMemOperand());
7010   }
7011   case Intrinsic::amdgcn_atomic_inc:
7012   case Intrinsic::amdgcn_atomic_dec:
7013   case Intrinsic::amdgcn_ds_fmin:
7014   case Intrinsic::amdgcn_ds_fmax: {
7015     MemSDNode *M = cast<MemSDNode>(Op);
7016     unsigned Opc;
7017     switch (IntrID) {
7018     case Intrinsic::amdgcn_atomic_inc:
7019       Opc = AMDGPUISD::ATOMIC_INC;
7020       break;
7021     case Intrinsic::amdgcn_atomic_dec:
7022       Opc = AMDGPUISD::ATOMIC_DEC;
7023       break;
7024     case Intrinsic::amdgcn_ds_fmin:
7025       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7026       break;
7027     case Intrinsic::amdgcn_ds_fmax:
7028       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7029       break;
7030     default:
7031       llvm_unreachable("Unknown intrinsic!");
7032     }
7033     SDValue Ops[] = {
7034       M->getOperand(0), // Chain
7035       M->getOperand(2), // Ptr
7036       M->getOperand(3)  // Value
7037     };
7038 
7039     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7040                                    M->getMemoryVT(), M->getMemOperand());
7041   }
7042   case Intrinsic::amdgcn_buffer_load:
7043   case Intrinsic::amdgcn_buffer_load_format: {
7044     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7045     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7046     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7047     SDValue Ops[] = {
7048       Op.getOperand(0), // Chain
7049       Op.getOperand(2), // rsrc
7050       Op.getOperand(3), // vindex
7051       SDValue(),        // voffset -- will be set by setBufferOffsets
7052       SDValue(),        // soffset -- will be set by setBufferOffsets
7053       SDValue(),        // offset -- will be set by setBufferOffsets
7054       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7055       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7056     };
7057     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7058 
7059     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7060         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7061 
7062     EVT VT = Op.getValueType();
7063     EVT IntVT = VT.changeTypeToInteger();
7064     auto *M = cast<MemSDNode>(Op);
7065     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7066     EVT LoadVT = Op.getValueType();
7067 
7068     if (LoadVT.getScalarType() == MVT::f16)
7069       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7070                                  M, DAG, Ops);
7071 
7072     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7073     if (LoadVT.getScalarType() == MVT::i8 ||
7074         LoadVT.getScalarType() == MVT::i16)
7075       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7076 
7077     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7078                                M->getMemOperand(), DAG);
7079   }
7080   case Intrinsic::amdgcn_raw_buffer_load:
7081   case Intrinsic::amdgcn_raw_buffer_load_format: {
7082     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7083 
7084     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7085     SDValue Ops[] = {
7086       Op.getOperand(0), // Chain
7087       Op.getOperand(2), // rsrc
7088       DAG.getConstant(0, DL, MVT::i32), // vindex
7089       Offsets.first,    // voffset
7090       Op.getOperand(4), // soffset
7091       Offsets.second,   // offset
7092       Op.getOperand(5), // cachepolicy, swizzled buffer
7093       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7094     };
7095 
7096     auto *M = cast<MemSDNode>(Op);
7097     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7098     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7099   }
7100   case Intrinsic::amdgcn_struct_buffer_load:
7101   case Intrinsic::amdgcn_struct_buffer_load_format: {
7102     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7103 
7104     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7105     SDValue Ops[] = {
7106       Op.getOperand(0), // Chain
7107       Op.getOperand(2), // rsrc
7108       Op.getOperand(3), // vindex
7109       Offsets.first,    // voffset
7110       Op.getOperand(5), // soffset
7111       Offsets.second,   // offset
7112       Op.getOperand(6), // cachepolicy, swizzled buffer
7113       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7114     };
7115 
7116     auto *M = cast<MemSDNode>(Op);
7117     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7118     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7119   }
7120   case Intrinsic::amdgcn_tbuffer_load: {
7121     MemSDNode *M = cast<MemSDNode>(Op);
7122     EVT LoadVT = Op.getValueType();
7123 
7124     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7125     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7126     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7127     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7128     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7129     SDValue Ops[] = {
7130       Op.getOperand(0),  // Chain
7131       Op.getOperand(2),  // rsrc
7132       Op.getOperand(3),  // vindex
7133       Op.getOperand(4),  // voffset
7134       Op.getOperand(5),  // soffset
7135       Op.getOperand(6),  // offset
7136       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7137       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7138       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7139     };
7140 
7141     if (LoadVT.getScalarType() == MVT::f16)
7142       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7143                                  M, DAG, Ops);
7144     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7145                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7146                                DAG);
7147   }
7148   case Intrinsic::amdgcn_raw_tbuffer_load: {
7149     MemSDNode *M = cast<MemSDNode>(Op);
7150     EVT LoadVT = Op.getValueType();
7151     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7152 
7153     SDValue Ops[] = {
7154       Op.getOperand(0),  // Chain
7155       Op.getOperand(2),  // rsrc
7156       DAG.getConstant(0, DL, MVT::i32), // vindex
7157       Offsets.first,     // voffset
7158       Op.getOperand(4),  // soffset
7159       Offsets.second,    // offset
7160       Op.getOperand(5),  // format
7161       Op.getOperand(6),  // cachepolicy, swizzled buffer
7162       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7163     };
7164 
7165     if (LoadVT.getScalarType() == MVT::f16)
7166       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7167                                  M, DAG, Ops);
7168     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7169                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7170                                DAG);
7171   }
7172   case Intrinsic::amdgcn_struct_tbuffer_load: {
7173     MemSDNode *M = cast<MemSDNode>(Op);
7174     EVT LoadVT = Op.getValueType();
7175     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7176 
7177     SDValue Ops[] = {
7178       Op.getOperand(0),  // Chain
7179       Op.getOperand(2),  // rsrc
7180       Op.getOperand(3),  // vindex
7181       Offsets.first,     // voffset
7182       Op.getOperand(5),  // soffset
7183       Offsets.second,    // offset
7184       Op.getOperand(6),  // format
7185       Op.getOperand(7),  // cachepolicy, swizzled buffer
7186       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7187     };
7188 
7189     if (LoadVT.getScalarType() == MVT::f16)
7190       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7191                                  M, DAG, Ops);
7192     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7193                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7194                                DAG);
7195   }
7196   case Intrinsic::amdgcn_buffer_atomic_swap:
7197   case Intrinsic::amdgcn_buffer_atomic_add:
7198   case Intrinsic::amdgcn_buffer_atomic_sub:
7199   case Intrinsic::amdgcn_buffer_atomic_csub:
7200   case Intrinsic::amdgcn_buffer_atomic_smin:
7201   case Intrinsic::amdgcn_buffer_atomic_umin:
7202   case Intrinsic::amdgcn_buffer_atomic_smax:
7203   case Intrinsic::amdgcn_buffer_atomic_umax:
7204   case Intrinsic::amdgcn_buffer_atomic_and:
7205   case Intrinsic::amdgcn_buffer_atomic_or:
7206   case Intrinsic::amdgcn_buffer_atomic_xor:
7207   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7208     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7209     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7210     SDValue Ops[] = {
7211       Op.getOperand(0), // Chain
7212       Op.getOperand(2), // vdata
7213       Op.getOperand(3), // rsrc
7214       Op.getOperand(4), // vindex
7215       SDValue(),        // voffset -- will be set by setBufferOffsets
7216       SDValue(),        // soffset -- will be set by setBufferOffsets
7217       SDValue(),        // offset -- will be set by setBufferOffsets
7218       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7219       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7220     };
7221     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7222 
7223     EVT VT = Op.getValueType();
7224 
7225     auto *M = cast<MemSDNode>(Op);
7226     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7227     unsigned Opcode = 0;
7228 
7229     switch (IntrID) {
7230     case Intrinsic::amdgcn_buffer_atomic_swap:
7231       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7232       break;
7233     case Intrinsic::amdgcn_buffer_atomic_add:
7234       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7235       break;
7236     case Intrinsic::amdgcn_buffer_atomic_sub:
7237       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7238       break;
7239     case Intrinsic::amdgcn_buffer_atomic_csub:
7240       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7241       break;
7242     case Intrinsic::amdgcn_buffer_atomic_smin:
7243       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7244       break;
7245     case Intrinsic::amdgcn_buffer_atomic_umin:
7246       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7247       break;
7248     case Intrinsic::amdgcn_buffer_atomic_smax:
7249       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7250       break;
7251     case Intrinsic::amdgcn_buffer_atomic_umax:
7252       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7253       break;
7254     case Intrinsic::amdgcn_buffer_atomic_and:
7255       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7256       break;
7257     case Intrinsic::amdgcn_buffer_atomic_or:
7258       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7259       break;
7260     case Intrinsic::amdgcn_buffer_atomic_xor:
7261       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7262       break;
7263     case Intrinsic::amdgcn_buffer_atomic_fadd:
7264       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7265         DiagnosticInfoUnsupported
7266           NoFpRet(DAG.getMachineFunction().getFunction(),
7267                   "return versions of fp atomics not supported",
7268                   DL.getDebugLoc(), DS_Error);
7269         DAG.getContext()->diagnose(NoFpRet);
7270         return SDValue();
7271       }
7272       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7273       break;
7274     default:
7275       llvm_unreachable("unhandled atomic opcode");
7276     }
7277 
7278     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7279                                    M->getMemOperand());
7280   }
7281   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7282     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7283   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7284     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7285   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7286     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7287   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7288     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7289   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7290     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7291   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7292     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7293   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7294     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7295   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7296     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7297   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7298     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7299   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7300     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7301   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7302     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7303   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7304     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7305   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7306     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7307   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7308     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7309   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7310     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7311   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7312     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7313   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7314     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7315   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7316     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7317   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7318     return lowerStructBufferAtomicIntrin(Op, DAG,
7319                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7320   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7321     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7322   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7323     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7324   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7325     return lowerStructBufferAtomicIntrin(Op, DAG,
7326                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7327   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7328     return lowerStructBufferAtomicIntrin(Op, DAG,
7329                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7330   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7331     return lowerStructBufferAtomicIntrin(Op, DAG,
7332                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7333   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7334     return lowerStructBufferAtomicIntrin(Op, DAG,
7335                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7336   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7337     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7338   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7339     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7340   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7341     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7342   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7343     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7344   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7345     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7346 
7347   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7348     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7349     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7350     SDValue Ops[] = {
7351       Op.getOperand(0), // Chain
7352       Op.getOperand(2), // src
7353       Op.getOperand(3), // cmp
7354       Op.getOperand(4), // rsrc
7355       Op.getOperand(5), // vindex
7356       SDValue(),        // voffset -- will be set by setBufferOffsets
7357       SDValue(),        // soffset -- will be set by setBufferOffsets
7358       SDValue(),        // offset -- will be set by setBufferOffsets
7359       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7360       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7361     };
7362     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7363 
7364     EVT VT = Op.getValueType();
7365     auto *M = cast<MemSDNode>(Op);
7366     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7367 
7368     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7369                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7370   }
7371   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7372     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7373     SDValue Ops[] = {
7374       Op.getOperand(0), // Chain
7375       Op.getOperand(2), // src
7376       Op.getOperand(3), // cmp
7377       Op.getOperand(4), // rsrc
7378       DAG.getConstant(0, DL, MVT::i32), // vindex
7379       Offsets.first,    // voffset
7380       Op.getOperand(6), // soffset
7381       Offsets.second,   // offset
7382       Op.getOperand(7), // cachepolicy
7383       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7384     };
7385     EVT VT = Op.getValueType();
7386     auto *M = cast<MemSDNode>(Op);
7387     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7388 
7389     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7390                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7391   }
7392   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7393     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7394     SDValue Ops[] = {
7395       Op.getOperand(0), // Chain
7396       Op.getOperand(2), // src
7397       Op.getOperand(3), // cmp
7398       Op.getOperand(4), // rsrc
7399       Op.getOperand(5), // vindex
7400       Offsets.first,    // voffset
7401       Op.getOperand(7), // soffset
7402       Offsets.second,   // offset
7403       Op.getOperand(8), // cachepolicy
7404       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7405     };
7406     EVT VT = Op.getValueType();
7407     auto *M = cast<MemSDNode>(Op);
7408     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7409 
7410     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7411                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7412   }
7413   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7414     MemSDNode *M = cast<MemSDNode>(Op);
7415     SDValue NodePtr = M->getOperand(2);
7416     SDValue RayExtent = M->getOperand(3);
7417     SDValue RayOrigin = M->getOperand(4);
7418     SDValue RayDir = M->getOperand(5);
7419     SDValue RayInvDir = M->getOperand(6);
7420     SDValue TDescr = M->getOperand(7);
7421 
7422     assert(NodePtr.getValueType() == MVT::i32 ||
7423            NodePtr.getValueType() == MVT::i64);
7424     assert(RayDir.getValueType() == MVT::v4f16 ||
7425            RayDir.getValueType() == MVT::v4f32);
7426 
7427     if (!Subtarget->hasGFX10_AEncoding()) {
7428       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7429       return SDValue();
7430     }
7431 
7432     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7433     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7434     const unsigned NumVDataDwords = 4;
7435     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7436     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7437                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7438     const unsigned BaseOpcodes[2][2] = {
7439         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7440         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7441          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7442     int Opcode;
7443     if (UseNSA) {
7444       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7445                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7446                                      NumVAddrDwords);
7447     } else {
7448       Opcode = AMDGPU::getMIMGOpcode(
7449           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7450           PowerOf2Ceil(NumVAddrDwords));
7451     }
7452     assert(Opcode != -1);
7453 
7454     SmallVector<SDValue, 16> Ops;
7455 
7456     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7457       SmallVector<SDValue, 3> Lanes;
7458       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7459       if (Lanes[0].getValueSizeInBits() == 32) {
7460         for (unsigned I = 0; I < 3; ++I)
7461           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7462       } else {
7463         if (IsAligned) {
7464           Ops.push_back(
7465             DAG.getBitcast(MVT::i32,
7466                            DAG.getBuildVector(MVT::v2f16, DL,
7467                                               { Lanes[0], Lanes[1] })));
7468           Ops.push_back(Lanes[2]);
7469         } else {
7470           SDValue Elt0 = Ops.pop_back_val();
7471           Ops.push_back(
7472             DAG.getBitcast(MVT::i32,
7473                            DAG.getBuildVector(MVT::v2f16, DL,
7474                                               { Elt0, Lanes[0] })));
7475           Ops.push_back(
7476             DAG.getBitcast(MVT::i32,
7477                            DAG.getBuildVector(MVT::v2f16, DL,
7478                                               { Lanes[1], Lanes[2] })));
7479         }
7480       }
7481     };
7482 
7483     if (Is64)
7484       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7485     else
7486       Ops.push_back(NodePtr);
7487 
7488     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7489     packLanes(RayOrigin, true);
7490     packLanes(RayDir, true);
7491     packLanes(RayInvDir, false);
7492 
7493     if (!UseNSA) {
7494       // Build a single vector containing all the operands so far prepared.
7495       if (NumVAddrDwords > 8) {
7496         SDValue Undef = DAG.getUNDEF(MVT::i32);
7497         Ops.append(16 - Ops.size(), Undef);
7498       }
7499       assert(Ops.size() == 8 || Ops.size() == 16);
7500       SDValue MergedOps = DAG.getBuildVector(
7501           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7502       Ops.clear();
7503       Ops.push_back(MergedOps);
7504     }
7505 
7506     Ops.push_back(TDescr);
7507     if (IsA16)
7508       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7509     Ops.push_back(M->getChain());
7510 
7511     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7512     MachineMemOperand *MemRef = M->getMemOperand();
7513     DAG.setNodeMemRefs(NewNode, {MemRef});
7514     return SDValue(NewNode, 0);
7515   }
7516   case Intrinsic::amdgcn_global_atomic_fadd:
7517     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7518       DiagnosticInfoUnsupported
7519         NoFpRet(DAG.getMachineFunction().getFunction(),
7520                 "return versions of fp atomics not supported",
7521                 DL.getDebugLoc(), DS_Error);
7522       DAG.getContext()->diagnose(NoFpRet);
7523       return SDValue();
7524     }
7525     LLVM_FALLTHROUGH;
7526   case Intrinsic::amdgcn_global_atomic_fmin:
7527   case Intrinsic::amdgcn_global_atomic_fmax:
7528   case Intrinsic::amdgcn_flat_atomic_fadd:
7529   case Intrinsic::amdgcn_flat_atomic_fmin:
7530   case Intrinsic::amdgcn_flat_atomic_fmax: {
7531     MemSDNode *M = cast<MemSDNode>(Op);
7532     SDValue Ops[] = {
7533       M->getOperand(0), // Chain
7534       M->getOperand(2), // Ptr
7535       M->getOperand(3)  // Value
7536     };
7537     unsigned Opcode = 0;
7538     switch (IntrID) {
7539     case Intrinsic::amdgcn_global_atomic_fadd:
7540     case Intrinsic::amdgcn_flat_atomic_fadd: {
7541       EVT VT = Op.getOperand(3).getValueType();
7542       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7543                            DAG.getVTList(VT, MVT::Other), Ops,
7544                            M->getMemOperand());
7545     }
7546     case Intrinsic::amdgcn_global_atomic_fmin:
7547     case Intrinsic::amdgcn_flat_atomic_fmin: {
7548       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7549       break;
7550     }
7551     case Intrinsic::amdgcn_global_atomic_fmax:
7552     case Intrinsic::amdgcn_flat_atomic_fmax: {
7553       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7554       break;
7555     }
7556     default:
7557       llvm_unreachable("unhandled atomic opcode");
7558     }
7559     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7560                                    M->getVTList(), Ops, M->getMemoryVT(),
7561                                    M->getMemOperand());
7562   }
7563   default:
7564 
7565     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7566             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7567       return lowerImage(Op, ImageDimIntr, DAG, true);
7568 
7569     return SDValue();
7570   }
7571 }
7572 
7573 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7574 // dwordx4 if on SI.
7575 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7576                                               SDVTList VTList,
7577                                               ArrayRef<SDValue> Ops, EVT MemVT,
7578                                               MachineMemOperand *MMO,
7579                                               SelectionDAG &DAG) const {
7580   EVT VT = VTList.VTs[0];
7581   EVT WidenedVT = VT;
7582   EVT WidenedMemVT = MemVT;
7583   if (!Subtarget->hasDwordx3LoadStores() &&
7584       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7585     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7586                                  WidenedVT.getVectorElementType(), 4);
7587     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7588                                     WidenedMemVT.getVectorElementType(), 4);
7589     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7590   }
7591 
7592   assert(VTList.NumVTs == 2);
7593   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7594 
7595   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7596                                        WidenedMemVT, MMO);
7597   if (WidenedVT != VT) {
7598     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7599                                DAG.getVectorIdxConstant(0, DL));
7600     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7601   }
7602   return NewOp;
7603 }
7604 
7605 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7606                                          bool ImageStore) const {
7607   EVT StoreVT = VData.getValueType();
7608 
7609   // No change for f16 and legal vector D16 types.
7610   if (!StoreVT.isVector())
7611     return VData;
7612 
7613   SDLoc DL(VData);
7614   unsigned NumElements = StoreVT.getVectorNumElements();
7615 
7616   if (Subtarget->hasUnpackedD16VMem()) {
7617     // We need to unpack the packed data to store.
7618     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7619     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7620 
7621     EVT EquivStoreVT =
7622         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7623     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7624     return DAG.UnrollVectorOp(ZExt.getNode());
7625   }
7626 
7627   // The sq block of gfx8.1 does not estimate register use correctly for d16
7628   // image store instructions. The data operand is computed as if it were not a
7629   // d16 image instruction.
7630   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7631     // Bitcast to i16
7632     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7633     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7634 
7635     // Decompose into scalars
7636     SmallVector<SDValue, 4> Elts;
7637     DAG.ExtractVectorElements(IntVData, Elts);
7638 
7639     // Group pairs of i16 into v2i16 and bitcast to i32
7640     SmallVector<SDValue, 4> PackedElts;
7641     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7642       SDValue Pair =
7643           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7644       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7645       PackedElts.push_back(IntPair);
7646     }
7647     if ((NumElements % 2) == 1) {
7648       // Handle v3i16
7649       unsigned I = Elts.size() / 2;
7650       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7651                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7652       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7653       PackedElts.push_back(IntPair);
7654     }
7655 
7656     // Pad using UNDEF
7657     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7658 
7659     // Build final vector
7660     EVT VecVT =
7661         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7662     return DAG.getBuildVector(VecVT, DL, PackedElts);
7663   }
7664 
7665   if (NumElements == 3) {
7666     EVT IntStoreVT =
7667         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7668     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7669 
7670     EVT WidenedStoreVT = EVT::getVectorVT(
7671         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7672     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7673                                          WidenedStoreVT.getStoreSizeInBits());
7674     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7675     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7676   }
7677 
7678   assert(isTypeLegal(StoreVT));
7679   return VData;
7680 }
7681 
7682 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7683                                               SelectionDAG &DAG) const {
7684   SDLoc DL(Op);
7685   SDValue Chain = Op.getOperand(0);
7686   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7687   MachineFunction &MF = DAG.getMachineFunction();
7688 
7689   switch (IntrinsicID) {
7690   case Intrinsic::amdgcn_exp_compr: {
7691     SDValue Src0 = Op.getOperand(4);
7692     SDValue Src1 = Op.getOperand(5);
7693     // Hack around illegal type on SI by directly selecting it.
7694     if (isTypeLegal(Src0.getValueType()))
7695       return SDValue();
7696 
7697     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7698     SDValue Undef = DAG.getUNDEF(MVT::f32);
7699     const SDValue Ops[] = {
7700       Op.getOperand(2), // tgt
7701       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7702       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7703       Undef, // src2
7704       Undef, // src3
7705       Op.getOperand(7), // vm
7706       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7707       Op.getOperand(3), // en
7708       Op.getOperand(0) // Chain
7709     };
7710 
7711     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7712     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7713   }
7714   case Intrinsic::amdgcn_s_barrier: {
7715     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7716       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7717       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7718       if (WGSize <= ST.getWavefrontSize())
7719         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7720                                           Op.getOperand(0)), 0);
7721     }
7722     return SDValue();
7723   };
7724   case Intrinsic::amdgcn_tbuffer_store: {
7725     SDValue VData = Op.getOperand(2);
7726     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7727     if (IsD16)
7728       VData = handleD16VData(VData, DAG);
7729     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7730     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7731     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7732     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7733     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7734     SDValue Ops[] = {
7735       Chain,
7736       VData,             // vdata
7737       Op.getOperand(3),  // rsrc
7738       Op.getOperand(4),  // vindex
7739       Op.getOperand(5),  // voffset
7740       Op.getOperand(6),  // soffset
7741       Op.getOperand(7),  // offset
7742       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7743       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7744       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7745     };
7746     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7747                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7748     MemSDNode *M = cast<MemSDNode>(Op);
7749     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7750                                    M->getMemoryVT(), M->getMemOperand());
7751   }
7752 
7753   case Intrinsic::amdgcn_struct_tbuffer_store: {
7754     SDValue VData = Op.getOperand(2);
7755     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7756     if (IsD16)
7757       VData = handleD16VData(VData, DAG);
7758     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7759     SDValue Ops[] = {
7760       Chain,
7761       VData,             // vdata
7762       Op.getOperand(3),  // rsrc
7763       Op.getOperand(4),  // vindex
7764       Offsets.first,     // voffset
7765       Op.getOperand(6),  // soffset
7766       Offsets.second,    // offset
7767       Op.getOperand(7),  // format
7768       Op.getOperand(8),  // cachepolicy, swizzled buffer
7769       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7770     };
7771     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7772                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7773     MemSDNode *M = cast<MemSDNode>(Op);
7774     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7775                                    M->getMemoryVT(), M->getMemOperand());
7776   }
7777 
7778   case Intrinsic::amdgcn_raw_tbuffer_store: {
7779     SDValue VData = Op.getOperand(2);
7780     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7781     if (IsD16)
7782       VData = handleD16VData(VData, DAG);
7783     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7784     SDValue Ops[] = {
7785       Chain,
7786       VData,             // vdata
7787       Op.getOperand(3),  // rsrc
7788       DAG.getConstant(0, DL, MVT::i32), // vindex
7789       Offsets.first,     // voffset
7790       Op.getOperand(5),  // soffset
7791       Offsets.second,    // offset
7792       Op.getOperand(6),  // format
7793       Op.getOperand(7),  // cachepolicy, swizzled buffer
7794       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7795     };
7796     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7797                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7798     MemSDNode *M = cast<MemSDNode>(Op);
7799     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7800                                    M->getMemoryVT(), M->getMemOperand());
7801   }
7802 
7803   case Intrinsic::amdgcn_buffer_store:
7804   case Intrinsic::amdgcn_buffer_store_format: {
7805     SDValue VData = Op.getOperand(2);
7806     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7807     if (IsD16)
7808       VData = handleD16VData(VData, DAG);
7809     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7810     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7811     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7812     SDValue Ops[] = {
7813       Chain,
7814       VData,
7815       Op.getOperand(3), // rsrc
7816       Op.getOperand(4), // vindex
7817       SDValue(), // voffset -- will be set by setBufferOffsets
7818       SDValue(), // soffset -- will be set by setBufferOffsets
7819       SDValue(), // offset -- will be set by setBufferOffsets
7820       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7821       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7822     };
7823     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7824 
7825     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7826                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7827     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7828     MemSDNode *M = cast<MemSDNode>(Op);
7829     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7830 
7831     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7832     EVT VDataType = VData.getValueType().getScalarType();
7833     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7834       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7835 
7836     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7837                                    M->getMemoryVT(), M->getMemOperand());
7838   }
7839 
7840   case Intrinsic::amdgcn_raw_buffer_store:
7841   case Intrinsic::amdgcn_raw_buffer_store_format: {
7842     const bool IsFormat =
7843         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7844 
7845     SDValue VData = Op.getOperand(2);
7846     EVT VDataVT = VData.getValueType();
7847     EVT EltType = VDataVT.getScalarType();
7848     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7849     if (IsD16) {
7850       VData = handleD16VData(VData, DAG);
7851       VDataVT = VData.getValueType();
7852     }
7853 
7854     if (!isTypeLegal(VDataVT)) {
7855       VData =
7856           DAG.getNode(ISD::BITCAST, DL,
7857                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7858     }
7859 
7860     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7861     SDValue Ops[] = {
7862       Chain,
7863       VData,
7864       Op.getOperand(3), // rsrc
7865       DAG.getConstant(0, DL, MVT::i32), // vindex
7866       Offsets.first,    // voffset
7867       Op.getOperand(5), // soffset
7868       Offsets.second,   // offset
7869       Op.getOperand(6), // cachepolicy, swizzled buffer
7870       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7871     };
7872     unsigned Opc =
7873         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7874     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7875     MemSDNode *M = cast<MemSDNode>(Op);
7876     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7877 
7878     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7879     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7880       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7881 
7882     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7883                                    M->getMemoryVT(), M->getMemOperand());
7884   }
7885 
7886   case Intrinsic::amdgcn_struct_buffer_store:
7887   case Intrinsic::amdgcn_struct_buffer_store_format: {
7888     const bool IsFormat =
7889         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7890 
7891     SDValue VData = Op.getOperand(2);
7892     EVT VDataVT = VData.getValueType();
7893     EVT EltType = VDataVT.getScalarType();
7894     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7895 
7896     if (IsD16) {
7897       VData = handleD16VData(VData, DAG);
7898       VDataVT = VData.getValueType();
7899     }
7900 
7901     if (!isTypeLegal(VDataVT)) {
7902       VData =
7903           DAG.getNode(ISD::BITCAST, DL,
7904                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7905     }
7906 
7907     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7908     SDValue Ops[] = {
7909       Chain,
7910       VData,
7911       Op.getOperand(3), // rsrc
7912       Op.getOperand(4), // vindex
7913       Offsets.first,    // voffset
7914       Op.getOperand(6), // soffset
7915       Offsets.second,   // offset
7916       Op.getOperand(7), // cachepolicy, swizzled buffer
7917       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7918     };
7919     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7920                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7921     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7922     MemSDNode *M = cast<MemSDNode>(Op);
7923     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7924 
7925     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7926     EVT VDataType = VData.getValueType().getScalarType();
7927     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7928       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7929 
7930     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7931                                    M->getMemoryVT(), M->getMemOperand());
7932   }
7933   case Intrinsic::amdgcn_end_cf:
7934     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7935                                       Op->getOperand(2), Chain), 0);
7936 
7937   default: {
7938     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7939             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7940       return lowerImage(Op, ImageDimIntr, DAG, true);
7941 
7942     return Op;
7943   }
7944   }
7945 }
7946 
7947 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7948 // offset (the offset that is included in bounds checking and swizzling, to be
7949 // split between the instruction's voffset and immoffset fields) and soffset
7950 // (the offset that is excluded from bounds checking and swizzling, to go in
7951 // the instruction's soffset field).  This function takes the first kind of
7952 // offset and figures out how to split it between voffset and immoffset.
7953 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7954     SDValue Offset, SelectionDAG &DAG) const {
7955   SDLoc DL(Offset);
7956   const unsigned MaxImm = 4095;
7957   SDValue N0 = Offset;
7958   ConstantSDNode *C1 = nullptr;
7959 
7960   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7961     N0 = SDValue();
7962   else if (DAG.isBaseWithConstantOffset(N0)) {
7963     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7964     N0 = N0.getOperand(0);
7965   }
7966 
7967   if (C1) {
7968     unsigned ImmOffset = C1->getZExtValue();
7969     // If the immediate value is too big for the immoffset field, put the value
7970     // and -4096 into the immoffset field so that the value that is copied/added
7971     // for the voffset field is a multiple of 4096, and it stands more chance
7972     // of being CSEd with the copy/add for another similar load/store.
7973     // However, do not do that rounding down to a multiple of 4096 if that is a
7974     // negative number, as it appears to be illegal to have a negative offset
7975     // in the vgpr, even if adding the immediate offset makes it positive.
7976     unsigned Overflow = ImmOffset & ~MaxImm;
7977     ImmOffset -= Overflow;
7978     if ((int32_t)Overflow < 0) {
7979       Overflow += ImmOffset;
7980       ImmOffset = 0;
7981     }
7982     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7983     if (Overflow) {
7984       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7985       if (!N0)
7986         N0 = OverflowVal;
7987       else {
7988         SDValue Ops[] = { N0, OverflowVal };
7989         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7990       }
7991     }
7992   }
7993   if (!N0)
7994     N0 = DAG.getConstant(0, DL, MVT::i32);
7995   if (!C1)
7996     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7997   return {N0, SDValue(C1, 0)};
7998 }
7999 
8000 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8001 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8002 // pointed to by Offsets.
8003 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8004                                         SelectionDAG &DAG, SDValue *Offsets,
8005                                         Align Alignment) const {
8006   SDLoc DL(CombinedOffset);
8007   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8008     uint32_t Imm = C->getZExtValue();
8009     uint32_t SOffset, ImmOffset;
8010     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8011                                  Alignment)) {
8012       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8013       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8014       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8015       return;
8016     }
8017   }
8018   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8019     SDValue N0 = CombinedOffset.getOperand(0);
8020     SDValue N1 = CombinedOffset.getOperand(1);
8021     uint32_t SOffset, ImmOffset;
8022     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8023     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8024                                                 Subtarget, Alignment)) {
8025       Offsets[0] = N0;
8026       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8027       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8028       return;
8029     }
8030   }
8031   Offsets[0] = CombinedOffset;
8032   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8033   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8034 }
8035 
8036 // Handle 8 bit and 16 bit buffer loads
8037 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8038                                                      EVT LoadVT, SDLoc DL,
8039                                                      ArrayRef<SDValue> Ops,
8040                                                      MemSDNode *M) const {
8041   EVT IntVT = LoadVT.changeTypeToInteger();
8042   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8043          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8044 
8045   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8046   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8047                                                Ops, IntVT,
8048                                                M->getMemOperand());
8049   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8050   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8051 
8052   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8053 }
8054 
8055 // Handle 8 bit and 16 bit buffer stores
8056 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8057                                                       EVT VDataType, SDLoc DL,
8058                                                       SDValue Ops[],
8059                                                       MemSDNode *M) const {
8060   if (VDataType == MVT::f16)
8061     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8062 
8063   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8064   Ops[1] = BufferStoreExt;
8065   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8066                                  AMDGPUISD::BUFFER_STORE_SHORT;
8067   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8068   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8069                                      M->getMemOperand());
8070 }
8071 
8072 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8073                                  ISD::LoadExtType ExtType, SDValue Op,
8074                                  const SDLoc &SL, EVT VT) {
8075   if (VT.bitsLT(Op.getValueType()))
8076     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8077 
8078   switch (ExtType) {
8079   case ISD::SEXTLOAD:
8080     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8081   case ISD::ZEXTLOAD:
8082     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8083   case ISD::EXTLOAD:
8084     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8085   case ISD::NON_EXTLOAD:
8086     return Op;
8087   }
8088 
8089   llvm_unreachable("invalid ext type");
8090 }
8091 
8092 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8093   SelectionDAG &DAG = DCI.DAG;
8094   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8095     return SDValue();
8096 
8097   // FIXME: Constant loads should all be marked invariant.
8098   unsigned AS = Ld->getAddressSpace();
8099   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8100       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8101       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8102     return SDValue();
8103 
8104   // Don't do this early, since it may interfere with adjacent load merging for
8105   // illegal types. We can avoid losing alignment information for exotic types
8106   // pre-legalize.
8107   EVT MemVT = Ld->getMemoryVT();
8108   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8109       MemVT.getSizeInBits() >= 32)
8110     return SDValue();
8111 
8112   SDLoc SL(Ld);
8113 
8114   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8115          "unexpected vector extload");
8116 
8117   // TODO: Drop only high part of range.
8118   SDValue Ptr = Ld->getBasePtr();
8119   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8120                                 MVT::i32, SL, Ld->getChain(), Ptr,
8121                                 Ld->getOffset(),
8122                                 Ld->getPointerInfo(), MVT::i32,
8123                                 Ld->getAlignment(),
8124                                 Ld->getMemOperand()->getFlags(),
8125                                 Ld->getAAInfo(),
8126                                 nullptr); // Drop ranges
8127 
8128   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8129   if (MemVT.isFloatingPoint()) {
8130     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8131            "unexpected fp extload");
8132     TruncVT = MemVT.changeTypeToInteger();
8133   }
8134 
8135   SDValue Cvt = NewLoad;
8136   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8137     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8138                       DAG.getValueType(TruncVT));
8139   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8140              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8141     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8142   } else {
8143     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8144   }
8145 
8146   EVT VT = Ld->getValueType(0);
8147   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8148 
8149   DCI.AddToWorklist(Cvt.getNode());
8150 
8151   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8152   // the appropriate extension from the 32-bit load.
8153   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8154   DCI.AddToWorklist(Cvt.getNode());
8155 
8156   // Handle conversion back to floating point if necessary.
8157   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8158 
8159   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8160 }
8161 
8162 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8163   SDLoc DL(Op);
8164   LoadSDNode *Load = cast<LoadSDNode>(Op);
8165   ISD::LoadExtType ExtType = Load->getExtensionType();
8166   EVT MemVT = Load->getMemoryVT();
8167 
8168   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8169     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8170       return SDValue();
8171 
8172     // FIXME: Copied from PPC
8173     // First, load into 32 bits, then truncate to 1 bit.
8174 
8175     SDValue Chain = Load->getChain();
8176     SDValue BasePtr = Load->getBasePtr();
8177     MachineMemOperand *MMO = Load->getMemOperand();
8178 
8179     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8180 
8181     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8182                                    BasePtr, RealMemVT, MMO);
8183 
8184     if (!MemVT.isVector()) {
8185       SDValue Ops[] = {
8186         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8187         NewLD.getValue(1)
8188       };
8189 
8190       return DAG.getMergeValues(Ops, DL);
8191     }
8192 
8193     SmallVector<SDValue, 3> Elts;
8194     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8195       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8196                                 DAG.getConstant(I, DL, MVT::i32));
8197 
8198       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8199     }
8200 
8201     SDValue Ops[] = {
8202       DAG.getBuildVector(MemVT, DL, Elts),
8203       NewLD.getValue(1)
8204     };
8205 
8206     return DAG.getMergeValues(Ops, DL);
8207   }
8208 
8209   if (!MemVT.isVector())
8210     return SDValue();
8211 
8212   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8213          "Custom lowering for non-i32 vectors hasn't been implemented.");
8214 
8215   unsigned Alignment = Load->getAlignment();
8216   unsigned AS = Load->getAddressSpace();
8217   if (Subtarget->hasLDSMisalignedBug() &&
8218       AS == AMDGPUAS::FLAT_ADDRESS &&
8219       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8220     return SplitVectorLoad(Op, DAG);
8221   }
8222 
8223   MachineFunction &MF = DAG.getMachineFunction();
8224   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8225   // If there is a possibilty that flat instruction access scratch memory
8226   // then we need to use the same legalization rules we use for private.
8227   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8228       !Subtarget->hasMultiDwordFlatScratchAddressing())
8229     AS = MFI->hasFlatScratchInit() ?
8230          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8231 
8232   unsigned NumElements = MemVT.getVectorNumElements();
8233 
8234   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8235       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8236     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8237       if (MemVT.isPow2VectorType())
8238         return SDValue();
8239       return WidenOrSplitVectorLoad(Op, DAG);
8240     }
8241     // Non-uniform loads will be selected to MUBUF instructions, so they
8242     // have the same legalization requirements as global and private
8243     // loads.
8244     //
8245   }
8246 
8247   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8248       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8249       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8250     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8251         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8252         Alignment >= 4 && NumElements < 32) {
8253       if (MemVT.isPow2VectorType())
8254         return SDValue();
8255       return WidenOrSplitVectorLoad(Op, DAG);
8256     }
8257     // Non-uniform loads will be selected to MUBUF instructions, so they
8258     // have the same legalization requirements as global and private
8259     // loads.
8260     //
8261   }
8262   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8263       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8264       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8265       AS == AMDGPUAS::FLAT_ADDRESS) {
8266     if (NumElements > 4)
8267       return SplitVectorLoad(Op, DAG);
8268     // v3 loads not supported on SI.
8269     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8270       return WidenOrSplitVectorLoad(Op, DAG);
8271 
8272     // v3 and v4 loads are supported for private and global memory.
8273     return SDValue();
8274   }
8275   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8276     // Depending on the setting of the private_element_size field in the
8277     // resource descriptor, we can only make private accesses up to a certain
8278     // size.
8279     switch (Subtarget->getMaxPrivateElementSize()) {
8280     case 4: {
8281       SDValue Ops[2];
8282       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8283       return DAG.getMergeValues(Ops, DL);
8284     }
8285     case 8:
8286       if (NumElements > 2)
8287         return SplitVectorLoad(Op, DAG);
8288       return SDValue();
8289     case 16:
8290       // Same as global/flat
8291       if (NumElements > 4)
8292         return SplitVectorLoad(Op, DAG);
8293       // v3 loads not supported on SI.
8294       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8295         return WidenOrSplitVectorLoad(Op, DAG);
8296 
8297       return SDValue();
8298     default:
8299       llvm_unreachable("unsupported private_element_size");
8300     }
8301   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8302     // Use ds_read_b128 or ds_read_b96 when possible.
8303     if (Subtarget->hasDS96AndDS128() &&
8304         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8305          MemVT.getStoreSize() == 12) &&
8306         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8307                                            Load->getAlign()))
8308       return SDValue();
8309 
8310     if (NumElements > 2)
8311       return SplitVectorLoad(Op, DAG);
8312 
8313     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8314     // address is negative, then the instruction is incorrectly treated as
8315     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8316     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8317     // load later in the SILoadStoreOptimizer.
8318     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8319         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8320         Load->getAlignment() < 8) {
8321       return SplitVectorLoad(Op, DAG);
8322     }
8323   }
8324 
8325   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8326                                       MemVT, *Load->getMemOperand())) {
8327     SDValue Ops[2];
8328     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8329     return DAG.getMergeValues(Ops, DL);
8330   }
8331 
8332   return SDValue();
8333 }
8334 
8335 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8336   EVT VT = Op.getValueType();
8337   assert(VT.getSizeInBits() == 64);
8338 
8339   SDLoc DL(Op);
8340   SDValue Cond = Op.getOperand(0);
8341 
8342   if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() &&
8343       !Op->isDivergent()) {
8344     if (VT == MVT::i64)
8345       return Op;
8346     SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1));
8347     SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2));
8348     return DAG.getNode(ISD::BITCAST, DL, VT,
8349                        DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS));
8350   }
8351 
8352   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8353   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8354 
8355   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8356   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8357 
8358   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8359   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8360 
8361   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8362 
8363   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8364   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8365 
8366   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8367 
8368   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8369   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8370 }
8371 
8372 // Catch division cases where we can use shortcuts with rcp and rsq
8373 // instructions.
8374 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8375                                               SelectionDAG &DAG) const {
8376   SDLoc SL(Op);
8377   SDValue LHS = Op.getOperand(0);
8378   SDValue RHS = Op.getOperand(1);
8379   EVT VT = Op.getValueType();
8380   const SDNodeFlags Flags = Op->getFlags();
8381 
8382   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8383 
8384   // Without !fpmath accuracy information, we can't do more because we don't
8385   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8386   if (!AllowInaccurateRcp)
8387     return SDValue();
8388 
8389   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8390     if (CLHS->isExactlyValue(1.0)) {
8391       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8392       // the CI documentation has a worst case error of 1 ulp.
8393       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8394       // use it as long as we aren't trying to use denormals.
8395       //
8396       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8397 
8398       // 1.0 / sqrt(x) -> rsq(x)
8399 
8400       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8401       // error seems really high at 2^29 ULP.
8402       if (RHS.getOpcode() == ISD::FSQRT)
8403         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8404 
8405       // 1.0 / x -> rcp(x)
8406       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8407     }
8408 
8409     // Same as for 1.0, but expand the sign out of the constant.
8410     if (CLHS->isExactlyValue(-1.0)) {
8411       // -1.0 / x -> rcp (fneg x)
8412       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8413       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8414     }
8415   }
8416 
8417   // Turn into multiply by the reciprocal.
8418   // x / y -> x * (1.0 / y)
8419   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8420   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8421 }
8422 
8423 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8424                                                 SelectionDAG &DAG) const {
8425   SDLoc SL(Op);
8426   SDValue X = Op.getOperand(0);
8427   SDValue Y = Op.getOperand(1);
8428   EVT VT = Op.getValueType();
8429   const SDNodeFlags Flags = Op->getFlags();
8430 
8431   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8432                             DAG.getTarget().Options.UnsafeFPMath;
8433   if (!AllowInaccurateDiv)
8434     return SDValue();
8435 
8436   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8437   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8438 
8439   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8440   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8441 
8442   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8443   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8444   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8445   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8446   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8447   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8448 }
8449 
8450 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8451                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8452                           SDNodeFlags Flags) {
8453   if (GlueChain->getNumValues() <= 1) {
8454     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8455   }
8456 
8457   assert(GlueChain->getNumValues() == 3);
8458 
8459   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8460   switch (Opcode) {
8461   default: llvm_unreachable("no chain equivalent for opcode");
8462   case ISD::FMUL:
8463     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8464     break;
8465   }
8466 
8467   return DAG.getNode(Opcode, SL, VTList,
8468                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8469                      Flags);
8470 }
8471 
8472 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8473                            EVT VT, SDValue A, SDValue B, SDValue C,
8474                            SDValue GlueChain, SDNodeFlags Flags) {
8475   if (GlueChain->getNumValues() <= 1) {
8476     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8477   }
8478 
8479   assert(GlueChain->getNumValues() == 3);
8480 
8481   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8482   switch (Opcode) {
8483   default: llvm_unreachable("no chain equivalent for opcode");
8484   case ISD::FMA:
8485     Opcode = AMDGPUISD::FMA_W_CHAIN;
8486     break;
8487   }
8488 
8489   return DAG.getNode(Opcode, SL, VTList,
8490                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8491                      Flags);
8492 }
8493 
8494 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8495   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8496     return FastLowered;
8497 
8498   SDLoc SL(Op);
8499   SDValue Src0 = Op.getOperand(0);
8500   SDValue Src1 = Op.getOperand(1);
8501 
8502   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8503   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8504 
8505   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8506   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8507 
8508   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8509   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8510 
8511   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8512 }
8513 
8514 // Faster 2.5 ULP division that does not support denormals.
8515 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8516   SDLoc SL(Op);
8517   SDValue LHS = Op.getOperand(1);
8518   SDValue RHS = Op.getOperand(2);
8519 
8520   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8521 
8522   const APFloat K0Val(BitsToFloat(0x6f800000));
8523   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8524 
8525   const APFloat K1Val(BitsToFloat(0x2f800000));
8526   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8527 
8528   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8529 
8530   EVT SetCCVT =
8531     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8532 
8533   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8534 
8535   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8536 
8537   // TODO: Should this propagate fast-math-flags?
8538   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8539 
8540   // rcp does not support denormals.
8541   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8542 
8543   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8544 
8545   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8546 }
8547 
8548 // Returns immediate value for setting the F32 denorm mode when using the
8549 // S_DENORM_MODE instruction.
8550 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8551                                     const SDLoc &SL, const GCNSubtarget *ST) {
8552   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8553   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8554                                 ? FP_DENORM_FLUSH_NONE
8555                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8556 
8557   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8558   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8559 }
8560 
8561 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8562   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8563     return FastLowered;
8564 
8565   // The selection matcher assumes anything with a chain selecting to a
8566   // mayRaiseFPException machine instruction. Since we're introducing a chain
8567   // here, we need to explicitly report nofpexcept for the regular fdiv
8568   // lowering.
8569   SDNodeFlags Flags = Op->getFlags();
8570   Flags.setNoFPExcept(true);
8571 
8572   SDLoc SL(Op);
8573   SDValue LHS = Op.getOperand(0);
8574   SDValue RHS = Op.getOperand(1);
8575 
8576   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8577 
8578   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8579 
8580   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8581                                           {RHS, RHS, LHS}, Flags);
8582   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8583                                         {LHS, RHS, LHS}, Flags);
8584 
8585   // Denominator is scaled to not be denormal, so using rcp is ok.
8586   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8587                                   DenominatorScaled, Flags);
8588   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8589                                      DenominatorScaled, Flags);
8590 
8591   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8592                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8593                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8594   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8595 
8596   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8597 
8598   if (!HasFP32Denormals) {
8599     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8600     // lowering. The chain dependence is insufficient, and we need glue. We do
8601     // not need the glue variants in a strictfp function.
8602 
8603     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8604 
8605     SDNode *EnableDenorm;
8606     if (Subtarget->hasDenormModeInst()) {
8607       const SDValue EnableDenormValue =
8608           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8609 
8610       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8611                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8612     } else {
8613       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8614                                                         SL, MVT::i32);
8615       EnableDenorm =
8616           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8617                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8618     }
8619 
8620     SDValue Ops[3] = {
8621       NegDivScale0,
8622       SDValue(EnableDenorm, 0),
8623       SDValue(EnableDenorm, 1)
8624     };
8625 
8626     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8627   }
8628 
8629   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8630                              ApproxRcp, One, NegDivScale0, Flags);
8631 
8632   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8633                              ApproxRcp, Fma0, Flags);
8634 
8635   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8636                            Fma1, Fma1, Flags);
8637 
8638   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8639                              NumeratorScaled, Mul, Flags);
8640 
8641   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8642                              Fma2, Fma1, Mul, Fma2, Flags);
8643 
8644   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8645                              NumeratorScaled, Fma3, Flags);
8646 
8647   if (!HasFP32Denormals) {
8648     SDNode *DisableDenorm;
8649     if (Subtarget->hasDenormModeInst()) {
8650       const SDValue DisableDenormValue =
8651           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8652 
8653       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8654                                   Fma4.getValue(1), DisableDenormValue,
8655                                   Fma4.getValue(2)).getNode();
8656     } else {
8657       const SDValue DisableDenormValue =
8658           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8659 
8660       DisableDenorm = DAG.getMachineNode(
8661           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8662           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8663     }
8664 
8665     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8666                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8667     DAG.setRoot(OutputChain);
8668   }
8669 
8670   SDValue Scale = NumeratorScaled.getValue(1);
8671   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8672                              {Fma4, Fma1, Fma3, Scale}, Flags);
8673 
8674   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8675 }
8676 
8677 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8678   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8679     return FastLowered;
8680 
8681   SDLoc SL(Op);
8682   SDValue X = Op.getOperand(0);
8683   SDValue Y = Op.getOperand(1);
8684 
8685   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8686 
8687   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8688 
8689   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8690 
8691   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8692 
8693   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8694 
8695   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8696 
8697   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8698 
8699   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8700 
8701   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8702 
8703   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8704   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8705 
8706   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8707                              NegDivScale0, Mul, DivScale1);
8708 
8709   SDValue Scale;
8710 
8711   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8712     // Workaround a hardware bug on SI where the condition output from div_scale
8713     // is not usable.
8714 
8715     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8716 
8717     // Figure out if the scale to use for div_fmas.
8718     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8719     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8720     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8721     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8722 
8723     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8724     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8725 
8726     SDValue Scale0Hi
8727       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8728     SDValue Scale1Hi
8729       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8730 
8731     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8732     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8733     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8734   } else {
8735     Scale = DivScale1.getValue(1);
8736   }
8737 
8738   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8739                              Fma4, Fma3, Mul, Scale);
8740 
8741   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8742 }
8743 
8744 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8745   EVT VT = Op.getValueType();
8746 
8747   if (VT == MVT::f32)
8748     return LowerFDIV32(Op, DAG);
8749 
8750   if (VT == MVT::f64)
8751     return LowerFDIV64(Op, DAG);
8752 
8753   if (VT == MVT::f16)
8754     return LowerFDIV16(Op, DAG);
8755 
8756   llvm_unreachable("Unexpected type for fdiv");
8757 }
8758 
8759 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8760   SDLoc DL(Op);
8761   StoreSDNode *Store = cast<StoreSDNode>(Op);
8762   EVT VT = Store->getMemoryVT();
8763 
8764   if (VT == MVT::i1) {
8765     return DAG.getTruncStore(Store->getChain(), DL,
8766        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8767        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8768   }
8769 
8770   assert(VT.isVector() &&
8771          Store->getValue().getValueType().getScalarType() == MVT::i32);
8772 
8773   unsigned AS = Store->getAddressSpace();
8774   if (Subtarget->hasLDSMisalignedBug() &&
8775       AS == AMDGPUAS::FLAT_ADDRESS &&
8776       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8777     return SplitVectorStore(Op, DAG);
8778   }
8779 
8780   MachineFunction &MF = DAG.getMachineFunction();
8781   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8782   // If there is a possibilty that flat instruction access scratch memory
8783   // then we need to use the same legalization rules we use for private.
8784   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8785       !Subtarget->hasMultiDwordFlatScratchAddressing())
8786     AS = MFI->hasFlatScratchInit() ?
8787          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8788 
8789   unsigned NumElements = VT.getVectorNumElements();
8790   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8791       AS == AMDGPUAS::FLAT_ADDRESS) {
8792     if (NumElements > 4)
8793       return SplitVectorStore(Op, DAG);
8794     // v3 stores not supported on SI.
8795     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8796       return SplitVectorStore(Op, DAG);
8797 
8798     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8799                                         VT, *Store->getMemOperand()))
8800       return expandUnalignedStore(Store, DAG);
8801 
8802     return SDValue();
8803   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8804     switch (Subtarget->getMaxPrivateElementSize()) {
8805     case 4:
8806       return scalarizeVectorStore(Store, DAG);
8807     case 8:
8808       if (NumElements > 2)
8809         return SplitVectorStore(Op, DAG);
8810       return SDValue();
8811     case 16:
8812       if (NumElements > 4 ||
8813           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8814         return SplitVectorStore(Op, DAG);
8815       return SDValue();
8816     default:
8817       llvm_unreachable("unsupported private_element_size");
8818     }
8819   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8820     // Use ds_write_b128 or ds_write_b96 when possible.
8821     if (Subtarget->hasDS96AndDS128() &&
8822         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8823          (VT.getStoreSize() == 12)) &&
8824         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8825                                            Store->getAlign()))
8826       return SDValue();
8827 
8828     if (NumElements > 2)
8829       return SplitVectorStore(Op, DAG);
8830 
8831     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8832     // address is negative, then the instruction is incorrectly treated as
8833     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8834     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8835     // store later in the SILoadStoreOptimizer.
8836     if (!Subtarget->hasUsableDSOffset() &&
8837         NumElements == 2 && VT.getStoreSize() == 8 &&
8838         Store->getAlignment() < 8) {
8839       return SplitVectorStore(Op, DAG);
8840     }
8841 
8842     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8843                                         VT, *Store->getMemOperand())) {
8844       if (VT.isVector())
8845         return SplitVectorStore(Op, DAG);
8846       return expandUnalignedStore(Store, DAG);
8847     }
8848 
8849     return SDValue();
8850   } else {
8851     llvm_unreachable("unhandled address space");
8852   }
8853 }
8854 
8855 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8856   SDLoc DL(Op);
8857   EVT VT = Op.getValueType();
8858   SDValue Arg = Op.getOperand(0);
8859   SDValue TrigVal;
8860 
8861   // Propagate fast-math flags so that the multiply we introduce can be folded
8862   // if Arg is already the result of a multiply by constant.
8863   auto Flags = Op->getFlags();
8864 
8865   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8866 
8867   if (Subtarget->hasTrigReducedRange()) {
8868     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8869     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8870   } else {
8871     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8872   }
8873 
8874   switch (Op.getOpcode()) {
8875   case ISD::FCOS:
8876     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8877   case ISD::FSIN:
8878     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8879   default:
8880     llvm_unreachable("Wrong trig opcode");
8881   }
8882 }
8883 
8884 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8885   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8886   assert(AtomicNode->isCompareAndSwap());
8887   unsigned AS = AtomicNode->getAddressSpace();
8888 
8889   // No custom lowering required for local address space
8890   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8891     return Op;
8892 
8893   // Non-local address space requires custom lowering for atomic compare
8894   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8895   SDLoc DL(Op);
8896   SDValue ChainIn = Op.getOperand(0);
8897   SDValue Addr = Op.getOperand(1);
8898   SDValue Old = Op.getOperand(2);
8899   SDValue New = Op.getOperand(3);
8900   EVT VT = Op.getValueType();
8901   MVT SimpleVT = VT.getSimpleVT();
8902   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8903 
8904   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8905   SDValue Ops[] = { ChainIn, Addr, NewOld };
8906 
8907   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8908                                  Ops, VT, AtomicNode->getMemOperand());
8909 }
8910 
8911 //===----------------------------------------------------------------------===//
8912 // Custom DAG optimizations
8913 //===----------------------------------------------------------------------===//
8914 
8915 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8916                                                      DAGCombinerInfo &DCI) const {
8917   EVT VT = N->getValueType(0);
8918   EVT ScalarVT = VT.getScalarType();
8919   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8920     return SDValue();
8921 
8922   SelectionDAG &DAG = DCI.DAG;
8923   SDLoc DL(N);
8924 
8925   SDValue Src = N->getOperand(0);
8926   EVT SrcVT = Src.getValueType();
8927 
8928   // TODO: We could try to match extracting the higher bytes, which would be
8929   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8930   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8931   // about in practice.
8932   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8933     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8934       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8935       DCI.AddToWorklist(Cvt.getNode());
8936 
8937       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8938       if (ScalarVT != MVT::f32) {
8939         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8940                           DAG.getTargetConstant(0, DL, MVT::i32));
8941       }
8942       return Cvt;
8943     }
8944   }
8945 
8946   return SDValue();
8947 }
8948 
8949 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8950 
8951 // This is a variant of
8952 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8953 //
8954 // The normal DAG combiner will do this, but only if the add has one use since
8955 // that would increase the number of instructions.
8956 //
8957 // This prevents us from seeing a constant offset that can be folded into a
8958 // memory instruction's addressing mode. If we know the resulting add offset of
8959 // a pointer can be folded into an addressing offset, we can replace the pointer
8960 // operand with the add of new constant offset. This eliminates one of the uses,
8961 // and may allow the remaining use to also be simplified.
8962 //
8963 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8964                                                unsigned AddrSpace,
8965                                                EVT MemVT,
8966                                                DAGCombinerInfo &DCI) const {
8967   SDValue N0 = N->getOperand(0);
8968   SDValue N1 = N->getOperand(1);
8969 
8970   // We only do this to handle cases where it's profitable when there are
8971   // multiple uses of the add, so defer to the standard combine.
8972   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8973       N0->hasOneUse())
8974     return SDValue();
8975 
8976   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8977   if (!CN1)
8978     return SDValue();
8979 
8980   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8981   if (!CAdd)
8982     return SDValue();
8983 
8984   // If the resulting offset is too large, we can't fold it into the addressing
8985   // mode offset.
8986   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8987   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8988 
8989   AddrMode AM;
8990   AM.HasBaseReg = true;
8991   AM.BaseOffs = Offset.getSExtValue();
8992   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8993     return SDValue();
8994 
8995   SelectionDAG &DAG = DCI.DAG;
8996   SDLoc SL(N);
8997   EVT VT = N->getValueType(0);
8998 
8999   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9000   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9001 
9002   SDNodeFlags Flags;
9003   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9004                           (N0.getOpcode() == ISD::OR ||
9005                            N0->getFlags().hasNoUnsignedWrap()));
9006 
9007   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9008 }
9009 
9010 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9011 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9012 /// specific intrinsic, but they all place the pointer operand first.
9013 static unsigned getBasePtrIndex(const MemSDNode *N) {
9014   switch (N->getOpcode()) {
9015   case ISD::STORE:
9016   case ISD::INTRINSIC_W_CHAIN:
9017   case ISD::INTRINSIC_VOID:
9018     return 2;
9019   default:
9020     return 1;
9021   }
9022 }
9023 
9024 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9025                                                   DAGCombinerInfo &DCI) const {
9026   SelectionDAG &DAG = DCI.DAG;
9027   SDLoc SL(N);
9028 
9029   unsigned PtrIdx = getBasePtrIndex(N);
9030   SDValue Ptr = N->getOperand(PtrIdx);
9031 
9032   // TODO: We could also do this for multiplies.
9033   if (Ptr.getOpcode() == ISD::SHL) {
9034     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9035                                           N->getMemoryVT(), DCI);
9036     if (NewPtr) {
9037       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9038 
9039       NewOps[PtrIdx] = NewPtr;
9040       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9041     }
9042   }
9043 
9044   return SDValue();
9045 }
9046 
9047 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9048   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9049          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9050          (Opc == ISD::XOR && Val == 0);
9051 }
9052 
9053 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9054 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9055 // integer combine opportunities since most 64-bit operations are decomposed
9056 // this way.  TODO: We won't want this for SALU especially if it is an inline
9057 // immediate.
9058 SDValue SITargetLowering::splitBinaryBitConstantOp(
9059   DAGCombinerInfo &DCI,
9060   const SDLoc &SL,
9061   unsigned Opc, SDValue LHS,
9062   const ConstantSDNode *CRHS) const {
9063   uint64_t Val = CRHS->getZExtValue();
9064   uint32_t ValLo = Lo_32(Val);
9065   uint32_t ValHi = Hi_32(Val);
9066   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9067 
9068     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9069          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9070         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9071     // If we need to materialize a 64-bit immediate, it will be split up later
9072     // anyway. Avoid creating the harder to understand 64-bit immediate
9073     // materialization.
9074     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9075   }
9076 
9077   return SDValue();
9078 }
9079 
9080 // Returns true if argument is a boolean value which is not serialized into
9081 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9082 static bool isBoolSGPR(SDValue V) {
9083   if (V.getValueType() != MVT::i1)
9084     return false;
9085   switch (V.getOpcode()) {
9086   default:
9087     break;
9088   case ISD::SETCC:
9089   case AMDGPUISD::FP_CLASS:
9090     return true;
9091   case ISD::AND:
9092   case ISD::OR:
9093   case ISD::XOR:
9094     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9095   }
9096   return false;
9097 }
9098 
9099 // If a constant has all zeroes or all ones within each byte return it.
9100 // Otherwise return 0.
9101 static uint32_t getConstantPermuteMask(uint32_t C) {
9102   // 0xff for any zero byte in the mask
9103   uint32_t ZeroByteMask = 0;
9104   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9105   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9106   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9107   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9108   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9109   if ((NonZeroByteMask & C) != NonZeroByteMask)
9110     return 0; // Partial bytes selected.
9111   return C;
9112 }
9113 
9114 // Check if a node selects whole bytes from its operand 0 starting at a byte
9115 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9116 // or -1 if not succeeded.
9117 // Note byte select encoding:
9118 // value 0-3 selects corresponding source byte;
9119 // value 0xc selects zero;
9120 // value 0xff selects 0xff.
9121 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9122   assert(V.getValueSizeInBits() == 32);
9123 
9124   if (V.getNumOperands() != 2)
9125     return ~0;
9126 
9127   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9128   if (!N1)
9129     return ~0;
9130 
9131   uint32_t C = N1->getZExtValue();
9132 
9133   switch (V.getOpcode()) {
9134   default:
9135     break;
9136   case ISD::AND:
9137     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9138       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9139     }
9140     break;
9141 
9142   case ISD::OR:
9143     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9144       return (0x03020100 & ~ConstMask) | ConstMask;
9145     }
9146     break;
9147 
9148   case ISD::SHL:
9149     if (C % 8)
9150       return ~0;
9151 
9152     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9153 
9154   case ISD::SRL:
9155     if (C % 8)
9156       return ~0;
9157 
9158     return uint32_t(0x0c0c0c0c03020100ull >> C);
9159   }
9160 
9161   return ~0;
9162 }
9163 
9164 SDValue SITargetLowering::performAndCombine(SDNode *N,
9165                                             DAGCombinerInfo &DCI) const {
9166   if (DCI.isBeforeLegalize())
9167     return SDValue();
9168 
9169   SelectionDAG &DAG = DCI.DAG;
9170   EVT VT = N->getValueType(0);
9171   SDValue LHS = N->getOperand(0);
9172   SDValue RHS = N->getOperand(1);
9173 
9174 
9175   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9176   if (VT == MVT::i64 && CRHS) {
9177     if (SDValue Split
9178         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9179       return Split;
9180   }
9181 
9182   if (CRHS && VT == MVT::i32) {
9183     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9184     // nb = number of trailing zeroes in mask
9185     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9186     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9187     uint64_t Mask = CRHS->getZExtValue();
9188     unsigned Bits = countPopulation(Mask);
9189     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9190         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9191       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9192         unsigned Shift = CShift->getZExtValue();
9193         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9194         unsigned Offset = NB + Shift;
9195         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9196           SDLoc SL(N);
9197           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9198                                     LHS->getOperand(0),
9199                                     DAG.getConstant(Offset, SL, MVT::i32),
9200                                     DAG.getConstant(Bits, SL, MVT::i32));
9201           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9202           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9203                                     DAG.getValueType(NarrowVT));
9204           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9205                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9206           return Shl;
9207         }
9208       }
9209     }
9210 
9211     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9212     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9213         isa<ConstantSDNode>(LHS.getOperand(2))) {
9214       uint32_t Sel = getConstantPermuteMask(Mask);
9215       if (!Sel)
9216         return SDValue();
9217 
9218       // Select 0xc for all zero bytes
9219       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9220       SDLoc DL(N);
9221       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9222                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9223     }
9224   }
9225 
9226   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9227   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9228   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9229     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9230     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9231 
9232     SDValue X = LHS.getOperand(0);
9233     SDValue Y = RHS.getOperand(0);
9234     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9235       return SDValue();
9236 
9237     if (LCC == ISD::SETO) {
9238       if (X != LHS.getOperand(1))
9239         return SDValue();
9240 
9241       if (RCC == ISD::SETUNE) {
9242         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9243         if (!C1 || !C1->isInfinity() || C1->isNegative())
9244           return SDValue();
9245 
9246         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9247                               SIInstrFlags::N_SUBNORMAL |
9248                               SIInstrFlags::N_ZERO |
9249                               SIInstrFlags::P_ZERO |
9250                               SIInstrFlags::P_SUBNORMAL |
9251                               SIInstrFlags::P_NORMAL;
9252 
9253         static_assert(((~(SIInstrFlags::S_NAN |
9254                           SIInstrFlags::Q_NAN |
9255                           SIInstrFlags::N_INFINITY |
9256                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9257                       "mask not equal");
9258 
9259         SDLoc DL(N);
9260         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9261                            X, DAG.getConstant(Mask, DL, MVT::i32));
9262       }
9263     }
9264   }
9265 
9266   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9267     std::swap(LHS, RHS);
9268 
9269   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9270       RHS.hasOneUse()) {
9271     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9272     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9273     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9274     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9275     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9276         (RHS.getOperand(0) == LHS.getOperand(0) &&
9277          LHS.getOperand(0) == LHS.getOperand(1))) {
9278       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9279       unsigned NewMask = LCC == ISD::SETO ?
9280         Mask->getZExtValue() & ~OrdMask :
9281         Mask->getZExtValue() & OrdMask;
9282 
9283       SDLoc DL(N);
9284       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9285                          DAG.getConstant(NewMask, DL, MVT::i32));
9286     }
9287   }
9288 
9289   if (VT == MVT::i32 &&
9290       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9291     // and x, (sext cc from i1) => select cc, x, 0
9292     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9293       std::swap(LHS, RHS);
9294     if (isBoolSGPR(RHS.getOperand(0)))
9295       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9296                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9297   }
9298 
9299   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9300   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9301   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9302       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9303     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9304     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9305     if (LHSMask != ~0u && RHSMask != ~0u) {
9306       // Canonicalize the expression in an attempt to have fewer unique masks
9307       // and therefore fewer registers used to hold the masks.
9308       if (LHSMask > RHSMask) {
9309         std::swap(LHSMask, RHSMask);
9310         std::swap(LHS, RHS);
9311       }
9312 
9313       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9314       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9315       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9316       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9317 
9318       // Check of we need to combine values from two sources within a byte.
9319       if (!(LHSUsedLanes & RHSUsedLanes) &&
9320           // If we select high and lower word keep it for SDWA.
9321           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9322           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9323         // Each byte in each mask is either selector mask 0-3, or has higher
9324         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9325         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9326         // mask which is not 0xff wins. By anding both masks we have a correct
9327         // result except that 0x0c shall be corrected to give 0x0c only.
9328         uint32_t Mask = LHSMask & RHSMask;
9329         for (unsigned I = 0; I < 32; I += 8) {
9330           uint32_t ByteSel = 0xff << I;
9331           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9332             Mask &= (0x0c << I) & 0xffffffff;
9333         }
9334 
9335         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9336         // or 0x0c.
9337         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9338         SDLoc DL(N);
9339 
9340         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9341                            LHS.getOperand(0), RHS.getOperand(0),
9342                            DAG.getConstant(Sel, DL, MVT::i32));
9343       }
9344     }
9345   }
9346 
9347   return SDValue();
9348 }
9349 
9350 SDValue SITargetLowering::performOrCombine(SDNode *N,
9351                                            DAGCombinerInfo &DCI) const {
9352   SelectionDAG &DAG = DCI.DAG;
9353   SDValue LHS = N->getOperand(0);
9354   SDValue RHS = N->getOperand(1);
9355 
9356   EVT VT = N->getValueType(0);
9357   if (VT == MVT::i1) {
9358     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9359     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9360         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9361       SDValue Src = LHS.getOperand(0);
9362       if (Src != RHS.getOperand(0))
9363         return SDValue();
9364 
9365       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9366       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9367       if (!CLHS || !CRHS)
9368         return SDValue();
9369 
9370       // Only 10 bits are used.
9371       static const uint32_t MaxMask = 0x3ff;
9372 
9373       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9374       SDLoc DL(N);
9375       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9376                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9377     }
9378 
9379     return SDValue();
9380   }
9381 
9382   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9383   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9384       LHS.getOpcode() == AMDGPUISD::PERM &&
9385       isa<ConstantSDNode>(LHS.getOperand(2))) {
9386     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9387     if (!Sel)
9388       return SDValue();
9389 
9390     Sel |= LHS.getConstantOperandVal(2);
9391     SDLoc DL(N);
9392     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9393                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9394   }
9395 
9396   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9397   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9398   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9399       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9400     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9401     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9402     if (LHSMask != ~0u && RHSMask != ~0u) {
9403       // Canonicalize the expression in an attempt to have fewer unique masks
9404       // and therefore fewer registers used to hold the masks.
9405       if (LHSMask > RHSMask) {
9406         std::swap(LHSMask, RHSMask);
9407         std::swap(LHS, RHS);
9408       }
9409 
9410       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9411       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9412       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9413       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9414 
9415       // Check of we need to combine values from two sources within a byte.
9416       if (!(LHSUsedLanes & RHSUsedLanes) &&
9417           // If we select high and lower word keep it for SDWA.
9418           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9419           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9420         // Kill zero bytes selected by other mask. Zero value is 0xc.
9421         LHSMask &= ~RHSUsedLanes;
9422         RHSMask &= ~LHSUsedLanes;
9423         // Add 4 to each active LHS lane
9424         LHSMask |= LHSUsedLanes & 0x04040404;
9425         // Combine masks
9426         uint32_t Sel = LHSMask | RHSMask;
9427         SDLoc DL(N);
9428 
9429         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9430                            LHS.getOperand(0), RHS.getOperand(0),
9431                            DAG.getConstant(Sel, DL, MVT::i32));
9432       }
9433     }
9434   }
9435 
9436   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9437     return SDValue();
9438 
9439   // TODO: This could be a generic combine with a predicate for extracting the
9440   // high half of an integer being free.
9441 
9442   // (or i64:x, (zero_extend i32:y)) ->
9443   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9444   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9445       RHS.getOpcode() != ISD::ZERO_EXTEND)
9446     std::swap(LHS, RHS);
9447 
9448   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9449     SDValue ExtSrc = RHS.getOperand(0);
9450     EVT SrcVT = ExtSrc.getValueType();
9451     if (SrcVT == MVT::i32) {
9452       SDLoc SL(N);
9453       SDValue LowLHS, HiBits;
9454       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9455       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9456 
9457       DCI.AddToWorklist(LowOr.getNode());
9458       DCI.AddToWorklist(HiBits.getNode());
9459 
9460       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9461                                 LowOr, HiBits);
9462       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9463     }
9464   }
9465 
9466   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9467   if (CRHS) {
9468     if (SDValue Split
9469           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9470       return Split;
9471   }
9472 
9473   return SDValue();
9474 }
9475 
9476 SDValue SITargetLowering::performXorCombine(SDNode *N,
9477                                             DAGCombinerInfo &DCI) const {
9478   EVT VT = N->getValueType(0);
9479   if (VT != MVT::i64)
9480     return SDValue();
9481 
9482   SDValue LHS = N->getOperand(0);
9483   SDValue RHS = N->getOperand(1);
9484 
9485   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9486   if (CRHS) {
9487     if (SDValue Split
9488           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9489       return Split;
9490   }
9491 
9492   return SDValue();
9493 }
9494 
9495 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9496                                                    DAGCombinerInfo &DCI) const {
9497   if (!Subtarget->has16BitInsts() ||
9498       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9499     return SDValue();
9500 
9501   EVT VT = N->getValueType(0);
9502   if (VT != MVT::i32)
9503     return SDValue();
9504 
9505   SDValue Src = N->getOperand(0);
9506   if (Src.getValueType() != MVT::i16)
9507     return SDValue();
9508 
9509   return SDValue();
9510 }
9511 
9512 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9513                                                         DAGCombinerInfo &DCI)
9514                                                         const {
9515   SDValue Src = N->getOperand(0);
9516   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9517 
9518   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9519       VTSign->getVT() == MVT::i8) ||
9520       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9521       VTSign->getVT() == MVT::i16)) &&
9522       Src.hasOneUse()) {
9523     auto *M = cast<MemSDNode>(Src);
9524     SDValue Ops[] = {
9525       Src.getOperand(0), // Chain
9526       Src.getOperand(1), // rsrc
9527       Src.getOperand(2), // vindex
9528       Src.getOperand(3), // voffset
9529       Src.getOperand(4), // soffset
9530       Src.getOperand(5), // offset
9531       Src.getOperand(6),
9532       Src.getOperand(7)
9533     };
9534     // replace with BUFFER_LOAD_BYTE/SHORT
9535     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9536                                          Src.getOperand(0).getValueType());
9537     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9538                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9539     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9540                                                           ResList,
9541                                                           Ops, M->getMemoryVT(),
9542                                                           M->getMemOperand());
9543     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9544                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9545   }
9546   return SDValue();
9547 }
9548 
9549 SDValue SITargetLowering::performClassCombine(SDNode *N,
9550                                               DAGCombinerInfo &DCI) const {
9551   SelectionDAG &DAG = DCI.DAG;
9552   SDValue Mask = N->getOperand(1);
9553 
9554   // fp_class x, 0 -> false
9555   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9556     if (CMask->isZero())
9557       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9558   }
9559 
9560   if (N->getOperand(0).isUndef())
9561     return DAG.getUNDEF(MVT::i1);
9562 
9563   return SDValue();
9564 }
9565 
9566 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9567                                             DAGCombinerInfo &DCI) const {
9568   EVT VT = N->getValueType(0);
9569   SDValue N0 = N->getOperand(0);
9570 
9571   if (N0.isUndef())
9572     return N0;
9573 
9574   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9575                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9576     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9577                            N->getFlags());
9578   }
9579 
9580   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9581     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9582                            N0.getOperand(0), N->getFlags());
9583   }
9584 
9585   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9586 }
9587 
9588 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9589                                        unsigned MaxDepth) const {
9590   unsigned Opcode = Op.getOpcode();
9591   if (Opcode == ISD::FCANONICALIZE)
9592     return true;
9593 
9594   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9595     auto F = CFP->getValueAPF();
9596     if (F.isNaN() && F.isSignaling())
9597       return false;
9598     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9599   }
9600 
9601   // If source is a result of another standard FP operation it is already in
9602   // canonical form.
9603   if (MaxDepth == 0)
9604     return false;
9605 
9606   switch (Opcode) {
9607   // These will flush denorms if required.
9608   case ISD::FADD:
9609   case ISD::FSUB:
9610   case ISD::FMUL:
9611   case ISD::FCEIL:
9612   case ISD::FFLOOR:
9613   case ISD::FMA:
9614   case ISD::FMAD:
9615   case ISD::FSQRT:
9616   case ISD::FDIV:
9617   case ISD::FREM:
9618   case ISD::FP_ROUND:
9619   case ISD::FP_EXTEND:
9620   case AMDGPUISD::FMUL_LEGACY:
9621   case AMDGPUISD::FMAD_FTZ:
9622   case AMDGPUISD::RCP:
9623   case AMDGPUISD::RSQ:
9624   case AMDGPUISD::RSQ_CLAMP:
9625   case AMDGPUISD::RCP_LEGACY:
9626   case AMDGPUISD::RCP_IFLAG:
9627   case AMDGPUISD::DIV_SCALE:
9628   case AMDGPUISD::DIV_FMAS:
9629   case AMDGPUISD::DIV_FIXUP:
9630   case AMDGPUISD::FRACT:
9631   case AMDGPUISD::LDEXP:
9632   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9633   case AMDGPUISD::CVT_F32_UBYTE0:
9634   case AMDGPUISD::CVT_F32_UBYTE1:
9635   case AMDGPUISD::CVT_F32_UBYTE2:
9636   case AMDGPUISD::CVT_F32_UBYTE3:
9637     return true;
9638 
9639   // It can/will be lowered or combined as a bit operation.
9640   // Need to check their input recursively to handle.
9641   case ISD::FNEG:
9642   case ISD::FABS:
9643   case ISD::FCOPYSIGN:
9644     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9645 
9646   case ISD::FSIN:
9647   case ISD::FCOS:
9648   case ISD::FSINCOS:
9649     return Op.getValueType().getScalarType() != MVT::f16;
9650 
9651   case ISD::FMINNUM:
9652   case ISD::FMAXNUM:
9653   case ISD::FMINNUM_IEEE:
9654   case ISD::FMAXNUM_IEEE:
9655   case AMDGPUISD::CLAMP:
9656   case AMDGPUISD::FMED3:
9657   case AMDGPUISD::FMAX3:
9658   case AMDGPUISD::FMIN3: {
9659     // FIXME: Shouldn't treat the generic operations different based these.
9660     // However, we aren't really required to flush the result from
9661     // minnum/maxnum..
9662 
9663     // snans will be quieted, so we only need to worry about denormals.
9664     if (Subtarget->supportsMinMaxDenormModes() ||
9665         denormalsEnabledForType(DAG, Op.getValueType()))
9666       return true;
9667 
9668     // Flushing may be required.
9669     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9670     // targets need to check their input recursively.
9671 
9672     // FIXME: Does this apply with clamp? It's implemented with max.
9673     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9674       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9675         return false;
9676     }
9677 
9678     return true;
9679   }
9680   case ISD::SELECT: {
9681     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9682            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9683   }
9684   case ISD::BUILD_VECTOR: {
9685     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9686       SDValue SrcOp = Op.getOperand(i);
9687       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9688         return false;
9689     }
9690 
9691     return true;
9692   }
9693   case ISD::EXTRACT_VECTOR_ELT:
9694   case ISD::EXTRACT_SUBVECTOR: {
9695     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9696   }
9697   case ISD::INSERT_VECTOR_ELT: {
9698     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9699            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9700   }
9701   case ISD::UNDEF:
9702     // Could be anything.
9703     return false;
9704 
9705   case ISD::BITCAST:
9706     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9707   case ISD::TRUNCATE: {
9708     // Hack round the mess we make when legalizing extract_vector_elt
9709     if (Op.getValueType() == MVT::i16) {
9710       SDValue TruncSrc = Op.getOperand(0);
9711       if (TruncSrc.getValueType() == MVT::i32 &&
9712           TruncSrc.getOpcode() == ISD::BITCAST &&
9713           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9714         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9715       }
9716     }
9717     return false;
9718   }
9719   case ISD::INTRINSIC_WO_CHAIN: {
9720     unsigned IntrinsicID
9721       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9722     // TODO: Handle more intrinsics
9723     switch (IntrinsicID) {
9724     case Intrinsic::amdgcn_cvt_pkrtz:
9725     case Intrinsic::amdgcn_cubeid:
9726     case Intrinsic::amdgcn_frexp_mant:
9727     case Intrinsic::amdgcn_fdot2:
9728     case Intrinsic::amdgcn_rcp:
9729     case Intrinsic::amdgcn_rsq:
9730     case Intrinsic::amdgcn_rsq_clamp:
9731     case Intrinsic::amdgcn_rcp_legacy:
9732     case Intrinsic::amdgcn_rsq_legacy:
9733     case Intrinsic::amdgcn_trig_preop:
9734       return true;
9735     default:
9736       break;
9737     }
9738 
9739     LLVM_FALLTHROUGH;
9740   }
9741   default:
9742     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9743            DAG.isKnownNeverSNaN(Op);
9744   }
9745 
9746   llvm_unreachable("invalid operation");
9747 }
9748 
9749 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9750                                        unsigned MaxDepth) const {
9751   MachineRegisterInfo &MRI = MF.getRegInfo();
9752   MachineInstr *MI = MRI.getVRegDef(Reg);
9753   unsigned Opcode = MI->getOpcode();
9754 
9755   if (Opcode == AMDGPU::G_FCANONICALIZE)
9756     return true;
9757 
9758   if (Opcode == AMDGPU::G_FCONSTANT) {
9759     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9760     if (F.isNaN() && F.isSignaling())
9761       return false;
9762     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9763   }
9764 
9765   if (MaxDepth == 0)
9766     return false;
9767 
9768   switch (Opcode) {
9769   case AMDGPU::G_FMINNUM_IEEE:
9770   case AMDGPU::G_FMAXNUM_IEEE: {
9771     if (Subtarget->supportsMinMaxDenormModes() ||
9772         denormalsEnabledForType(MRI.getType(Reg), MF))
9773       return true;
9774     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9775       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9776         return false;
9777     }
9778     return true;
9779   }
9780   default:
9781     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9782            isKnownNeverSNaN(Reg, MRI);
9783   }
9784 
9785   llvm_unreachable("invalid operation");
9786 }
9787 
9788 // Constant fold canonicalize.
9789 SDValue SITargetLowering::getCanonicalConstantFP(
9790   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9791   // Flush denormals to 0 if not enabled.
9792   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9793     return DAG.getConstantFP(0.0, SL, VT);
9794 
9795   if (C.isNaN()) {
9796     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9797     if (C.isSignaling()) {
9798       // Quiet a signaling NaN.
9799       // FIXME: Is this supposed to preserve payload bits?
9800       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9801     }
9802 
9803     // Make sure it is the canonical NaN bitpattern.
9804     //
9805     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9806     // immediate?
9807     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9808       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9809   }
9810 
9811   // Already canonical.
9812   return DAG.getConstantFP(C, SL, VT);
9813 }
9814 
9815 static bool vectorEltWillFoldAway(SDValue Op) {
9816   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9817 }
9818 
9819 SDValue SITargetLowering::performFCanonicalizeCombine(
9820   SDNode *N,
9821   DAGCombinerInfo &DCI) const {
9822   SelectionDAG &DAG = DCI.DAG;
9823   SDValue N0 = N->getOperand(0);
9824   EVT VT = N->getValueType(0);
9825 
9826   // fcanonicalize undef -> qnan
9827   if (N0.isUndef()) {
9828     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9829     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9830   }
9831 
9832   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9833     EVT VT = N->getValueType(0);
9834     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9835   }
9836 
9837   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9838   //                                                   (fcanonicalize k)
9839   //
9840   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9841 
9842   // TODO: This could be better with wider vectors that will be split to v2f16,
9843   // and to consider uses since there aren't that many packed operations.
9844   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9845       isTypeLegal(MVT::v2f16)) {
9846     SDLoc SL(N);
9847     SDValue NewElts[2];
9848     SDValue Lo = N0.getOperand(0);
9849     SDValue Hi = N0.getOperand(1);
9850     EVT EltVT = Lo.getValueType();
9851 
9852     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9853       for (unsigned I = 0; I != 2; ++I) {
9854         SDValue Op = N0.getOperand(I);
9855         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9856           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9857                                               CFP->getValueAPF());
9858         } else if (Op.isUndef()) {
9859           // Handled below based on what the other operand is.
9860           NewElts[I] = Op;
9861         } else {
9862           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9863         }
9864       }
9865 
9866       // If one half is undef, and one is constant, perfer a splat vector rather
9867       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9868       // cheaper to use and may be free with a packed operation.
9869       if (NewElts[0].isUndef()) {
9870         if (isa<ConstantFPSDNode>(NewElts[1]))
9871           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9872             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9873       }
9874 
9875       if (NewElts[1].isUndef()) {
9876         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9877           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9878       }
9879 
9880       return DAG.getBuildVector(VT, SL, NewElts);
9881     }
9882   }
9883 
9884   unsigned SrcOpc = N0.getOpcode();
9885 
9886   // If it's free to do so, push canonicalizes further up the source, which may
9887   // find a canonical source.
9888   //
9889   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9890   // sNaNs.
9891   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9892     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9893     if (CRHS && N0.hasOneUse()) {
9894       SDLoc SL(N);
9895       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9896                                    N0.getOperand(0));
9897       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9898       DCI.AddToWorklist(Canon0.getNode());
9899 
9900       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9901     }
9902   }
9903 
9904   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9905 }
9906 
9907 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9908   switch (Opc) {
9909   case ISD::FMAXNUM:
9910   case ISD::FMAXNUM_IEEE:
9911     return AMDGPUISD::FMAX3;
9912   case ISD::SMAX:
9913     return AMDGPUISD::SMAX3;
9914   case ISD::UMAX:
9915     return AMDGPUISD::UMAX3;
9916   case ISD::FMINNUM:
9917   case ISD::FMINNUM_IEEE:
9918     return AMDGPUISD::FMIN3;
9919   case ISD::SMIN:
9920     return AMDGPUISD::SMIN3;
9921   case ISD::UMIN:
9922     return AMDGPUISD::UMIN3;
9923   default:
9924     llvm_unreachable("Not a min/max opcode");
9925   }
9926 }
9927 
9928 SDValue SITargetLowering::performIntMed3ImmCombine(
9929   SelectionDAG &DAG, const SDLoc &SL,
9930   SDValue Op0, SDValue Op1, bool Signed) const {
9931   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9932   if (!K1)
9933     return SDValue();
9934 
9935   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9936   if (!K0)
9937     return SDValue();
9938 
9939   if (Signed) {
9940     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9941       return SDValue();
9942   } else {
9943     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9944       return SDValue();
9945   }
9946 
9947   EVT VT = K0->getValueType(0);
9948   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9949   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9950     return DAG.getNode(Med3Opc, SL, VT,
9951                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9952   }
9953 
9954   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9955   if (VT == MVT::i16) {
9956     MVT NVT = MVT::i32;
9957     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9958 
9959     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9960     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9961     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9962 
9963     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9964     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9965   }
9966 
9967   return SDValue();
9968 }
9969 
9970 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9971   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9972     return C;
9973 
9974   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9975     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9976       return C;
9977   }
9978 
9979   return nullptr;
9980 }
9981 
9982 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9983                                                   const SDLoc &SL,
9984                                                   SDValue Op0,
9985                                                   SDValue Op1) const {
9986   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9987   if (!K1)
9988     return SDValue();
9989 
9990   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9991   if (!K0)
9992     return SDValue();
9993 
9994   // Ordered >= (although NaN inputs should have folded away by now).
9995   if (K0->getValueAPF() > K1->getValueAPF())
9996     return SDValue();
9997 
9998   const MachineFunction &MF = DAG.getMachineFunction();
9999   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10000 
10001   // TODO: Check IEEE bit enabled?
10002   EVT VT = Op0.getValueType();
10003   if (Info->getMode().DX10Clamp) {
10004     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10005     // hardware fmed3 behavior converting to a min.
10006     // FIXME: Should this be allowing -0.0?
10007     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10008       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10009   }
10010 
10011   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10012   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10013     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10014     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10015     // then give the other result, which is different from med3 with a NaN
10016     // input.
10017     SDValue Var = Op0.getOperand(0);
10018     if (!DAG.isKnownNeverSNaN(Var))
10019       return SDValue();
10020 
10021     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10022 
10023     if ((!K0->hasOneUse() ||
10024          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10025         (!K1->hasOneUse() ||
10026          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10027       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10028                          Var, SDValue(K0, 0), SDValue(K1, 0));
10029     }
10030   }
10031 
10032   return SDValue();
10033 }
10034 
10035 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10036                                                DAGCombinerInfo &DCI) const {
10037   SelectionDAG &DAG = DCI.DAG;
10038 
10039   EVT VT = N->getValueType(0);
10040   unsigned Opc = N->getOpcode();
10041   SDValue Op0 = N->getOperand(0);
10042   SDValue Op1 = N->getOperand(1);
10043 
10044   // Only do this if the inner op has one use since this will just increases
10045   // register pressure for no benefit.
10046 
10047   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10048       !VT.isVector() &&
10049       (VT == MVT::i32 || VT == MVT::f32 ||
10050        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10051     // max(max(a, b), c) -> max3(a, b, c)
10052     // min(min(a, b), c) -> min3(a, b, c)
10053     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10054       SDLoc DL(N);
10055       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10056                          DL,
10057                          N->getValueType(0),
10058                          Op0.getOperand(0),
10059                          Op0.getOperand(1),
10060                          Op1);
10061     }
10062 
10063     // Try commuted.
10064     // max(a, max(b, c)) -> max3(a, b, c)
10065     // min(a, min(b, c)) -> min3(a, b, c)
10066     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10067       SDLoc DL(N);
10068       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10069                          DL,
10070                          N->getValueType(0),
10071                          Op0,
10072                          Op1.getOperand(0),
10073                          Op1.getOperand(1));
10074     }
10075   }
10076 
10077   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10078   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10079     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10080       return Med3;
10081   }
10082 
10083   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10084     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10085       return Med3;
10086   }
10087 
10088   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10089   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10090        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10091        (Opc == AMDGPUISD::FMIN_LEGACY &&
10092         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10093       (VT == MVT::f32 || VT == MVT::f64 ||
10094        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10095        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10096       Op0.hasOneUse()) {
10097     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10098       return Res;
10099   }
10100 
10101   return SDValue();
10102 }
10103 
10104 static bool isClampZeroToOne(SDValue A, SDValue B) {
10105   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10106     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10107       // FIXME: Should this be allowing -0.0?
10108       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10109              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10110     }
10111   }
10112 
10113   return false;
10114 }
10115 
10116 // FIXME: Should only worry about snans for version with chain.
10117 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10118                                               DAGCombinerInfo &DCI) const {
10119   EVT VT = N->getValueType(0);
10120   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10121   // NaNs. With a NaN input, the order of the operands may change the result.
10122 
10123   SelectionDAG &DAG = DCI.DAG;
10124   SDLoc SL(N);
10125 
10126   SDValue Src0 = N->getOperand(0);
10127   SDValue Src1 = N->getOperand(1);
10128   SDValue Src2 = N->getOperand(2);
10129 
10130   if (isClampZeroToOne(Src0, Src1)) {
10131     // const_a, const_b, x -> clamp is safe in all cases including signaling
10132     // nans.
10133     // FIXME: Should this be allowing -0.0?
10134     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10135   }
10136 
10137   const MachineFunction &MF = DAG.getMachineFunction();
10138   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10139 
10140   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10141   // handling no dx10-clamp?
10142   if (Info->getMode().DX10Clamp) {
10143     // If NaNs is clamped to 0, we are free to reorder the inputs.
10144 
10145     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10146       std::swap(Src0, Src1);
10147 
10148     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10149       std::swap(Src1, Src2);
10150 
10151     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10152       std::swap(Src0, Src1);
10153 
10154     if (isClampZeroToOne(Src1, Src2))
10155       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10156   }
10157 
10158   return SDValue();
10159 }
10160 
10161 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10162                                                  DAGCombinerInfo &DCI) const {
10163   SDValue Src0 = N->getOperand(0);
10164   SDValue Src1 = N->getOperand(1);
10165   if (Src0.isUndef() && Src1.isUndef())
10166     return DCI.DAG.getUNDEF(N->getValueType(0));
10167   return SDValue();
10168 }
10169 
10170 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10171 // expanded into a set of cmp/select instructions.
10172 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10173                                                 unsigned NumElem,
10174                                                 bool IsDivergentIdx) {
10175   if (UseDivergentRegisterIndexing)
10176     return false;
10177 
10178   unsigned VecSize = EltSize * NumElem;
10179 
10180   // Sub-dword vectors of size 2 dword or less have better implementation.
10181   if (VecSize <= 64 && EltSize < 32)
10182     return false;
10183 
10184   // Always expand the rest of sub-dword instructions, otherwise it will be
10185   // lowered via memory.
10186   if (EltSize < 32)
10187     return true;
10188 
10189   // Always do this if var-idx is divergent, otherwise it will become a loop.
10190   if (IsDivergentIdx)
10191     return true;
10192 
10193   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10194   unsigned NumInsts = NumElem /* Number of compares */ +
10195                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10196   return NumInsts <= 16;
10197 }
10198 
10199 static bool shouldExpandVectorDynExt(SDNode *N) {
10200   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10201   if (isa<ConstantSDNode>(Idx))
10202     return false;
10203 
10204   SDValue Vec = N->getOperand(0);
10205   EVT VecVT = Vec.getValueType();
10206   EVT EltVT = VecVT.getVectorElementType();
10207   unsigned EltSize = EltVT.getSizeInBits();
10208   unsigned NumElem = VecVT.getVectorNumElements();
10209 
10210   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10211                                                     Idx->isDivergent());
10212 }
10213 
10214 SDValue SITargetLowering::performExtractVectorEltCombine(
10215   SDNode *N, DAGCombinerInfo &DCI) const {
10216   SDValue Vec = N->getOperand(0);
10217   SelectionDAG &DAG = DCI.DAG;
10218 
10219   EVT VecVT = Vec.getValueType();
10220   EVT EltVT = VecVT.getVectorElementType();
10221 
10222   if ((Vec.getOpcode() == ISD::FNEG ||
10223        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10224     SDLoc SL(N);
10225     EVT EltVT = N->getValueType(0);
10226     SDValue Idx = N->getOperand(1);
10227     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10228                               Vec.getOperand(0), Idx);
10229     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10230   }
10231 
10232   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10233   //    =>
10234   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10235   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10236   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10237   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10238     SDLoc SL(N);
10239     EVT EltVT = N->getValueType(0);
10240     SDValue Idx = N->getOperand(1);
10241     unsigned Opc = Vec.getOpcode();
10242 
10243     switch(Opc) {
10244     default:
10245       break;
10246       // TODO: Support other binary operations.
10247     case ISD::FADD:
10248     case ISD::FSUB:
10249     case ISD::FMUL:
10250     case ISD::ADD:
10251     case ISD::UMIN:
10252     case ISD::UMAX:
10253     case ISD::SMIN:
10254     case ISD::SMAX:
10255     case ISD::FMAXNUM:
10256     case ISD::FMINNUM:
10257     case ISD::FMAXNUM_IEEE:
10258     case ISD::FMINNUM_IEEE: {
10259       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10260                                  Vec.getOperand(0), Idx);
10261       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10262                                  Vec.getOperand(1), Idx);
10263 
10264       DCI.AddToWorklist(Elt0.getNode());
10265       DCI.AddToWorklist(Elt1.getNode());
10266       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10267     }
10268     }
10269   }
10270 
10271   unsigned VecSize = VecVT.getSizeInBits();
10272   unsigned EltSize = EltVT.getSizeInBits();
10273 
10274   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10275   if (::shouldExpandVectorDynExt(N)) {
10276     SDLoc SL(N);
10277     SDValue Idx = N->getOperand(1);
10278     SDValue V;
10279     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10280       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10281       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10282       if (I == 0)
10283         V = Elt;
10284       else
10285         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10286     }
10287     return V;
10288   }
10289 
10290   if (!DCI.isBeforeLegalize())
10291     return SDValue();
10292 
10293   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10294   // elements. This exposes more load reduction opportunities by replacing
10295   // multiple small extract_vector_elements with a single 32-bit extract.
10296   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10297   if (isa<MemSDNode>(Vec) &&
10298       EltSize <= 16 &&
10299       EltVT.isByteSized() &&
10300       VecSize > 32 &&
10301       VecSize % 32 == 0 &&
10302       Idx) {
10303     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10304 
10305     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10306     unsigned EltIdx = BitIndex / 32;
10307     unsigned LeftoverBitIdx = BitIndex % 32;
10308     SDLoc SL(N);
10309 
10310     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10311     DCI.AddToWorklist(Cast.getNode());
10312 
10313     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10314                               DAG.getConstant(EltIdx, SL, MVT::i32));
10315     DCI.AddToWorklist(Elt.getNode());
10316     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10317                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10318     DCI.AddToWorklist(Srl.getNode());
10319 
10320     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10321     DCI.AddToWorklist(Trunc.getNode());
10322     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10323   }
10324 
10325   return SDValue();
10326 }
10327 
10328 SDValue
10329 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10330                                                 DAGCombinerInfo &DCI) const {
10331   SDValue Vec = N->getOperand(0);
10332   SDValue Idx = N->getOperand(2);
10333   EVT VecVT = Vec.getValueType();
10334   EVT EltVT = VecVT.getVectorElementType();
10335 
10336   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10337   // => BUILD_VECTOR n x select (e, const-idx)
10338   if (!::shouldExpandVectorDynExt(N))
10339     return SDValue();
10340 
10341   SelectionDAG &DAG = DCI.DAG;
10342   SDLoc SL(N);
10343   SDValue Ins = N->getOperand(1);
10344   EVT IdxVT = Idx.getValueType();
10345 
10346   SmallVector<SDValue, 16> Ops;
10347   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10348     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10349     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10350     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10351     Ops.push_back(V);
10352   }
10353 
10354   return DAG.getBuildVector(VecVT, SL, Ops);
10355 }
10356 
10357 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10358                                           const SDNode *N0,
10359                                           const SDNode *N1) const {
10360   EVT VT = N0->getValueType(0);
10361 
10362   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10363   // support denormals ever.
10364   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10365        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10366         getSubtarget()->hasMadF16())) &&
10367        isOperationLegal(ISD::FMAD, VT))
10368     return ISD::FMAD;
10369 
10370   const TargetOptions &Options = DAG.getTarget().Options;
10371   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10372        (N0->getFlags().hasAllowContract() &&
10373         N1->getFlags().hasAllowContract())) &&
10374       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10375     return ISD::FMA;
10376   }
10377 
10378   return 0;
10379 }
10380 
10381 // For a reassociatable opcode perform:
10382 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10383 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10384                                                SelectionDAG &DAG) const {
10385   EVT VT = N->getValueType(0);
10386   if (VT != MVT::i32 && VT != MVT::i64)
10387     return SDValue();
10388 
10389   unsigned Opc = N->getOpcode();
10390   SDValue Op0 = N->getOperand(0);
10391   SDValue Op1 = N->getOperand(1);
10392 
10393   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10394     return SDValue();
10395 
10396   if (Op0->isDivergent())
10397     std::swap(Op0, Op1);
10398 
10399   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10400     return SDValue();
10401 
10402   SDValue Op2 = Op1.getOperand(1);
10403   Op1 = Op1.getOperand(0);
10404   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10405     return SDValue();
10406 
10407   if (Op1->isDivergent())
10408     std::swap(Op1, Op2);
10409 
10410   // If either operand is constant this will conflict with
10411   // DAGCombiner::ReassociateOps().
10412   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10413       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10414     return SDValue();
10415 
10416   SDLoc SL(N);
10417   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10418   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10419 }
10420 
10421 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10422                            EVT VT,
10423                            SDValue N0, SDValue N1, SDValue N2,
10424                            bool Signed) {
10425   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10426   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10427   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10428   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10429 }
10430 
10431 SDValue SITargetLowering::performAddCombine(SDNode *N,
10432                                             DAGCombinerInfo &DCI) const {
10433   SelectionDAG &DAG = DCI.DAG;
10434   EVT VT = N->getValueType(0);
10435   SDLoc SL(N);
10436   SDValue LHS = N->getOperand(0);
10437   SDValue RHS = N->getOperand(1);
10438 
10439   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10440       && Subtarget->hasMad64_32() &&
10441       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10442       VT.getScalarSizeInBits() <= 64) {
10443     if (LHS.getOpcode() != ISD::MUL)
10444       std::swap(LHS, RHS);
10445 
10446     SDValue MulLHS = LHS.getOperand(0);
10447     SDValue MulRHS = LHS.getOperand(1);
10448     SDValue AddRHS = RHS;
10449 
10450     // TODO: Maybe restrict if SGPR inputs.
10451     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10452         numBitsUnsigned(MulRHS, DAG) <= 32) {
10453       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10454       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10455       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10456       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10457     }
10458 
10459     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10460       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10461       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10462       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10463       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10464     }
10465 
10466     return SDValue();
10467   }
10468 
10469   if (SDValue V = reassociateScalarOps(N, DAG)) {
10470     return V;
10471   }
10472 
10473   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10474     return SDValue();
10475 
10476   // add x, zext (setcc) => addcarry x, 0, setcc
10477   // add x, sext (setcc) => subcarry x, 0, setcc
10478   unsigned Opc = LHS.getOpcode();
10479   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10480       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10481     std::swap(RHS, LHS);
10482 
10483   Opc = RHS.getOpcode();
10484   switch (Opc) {
10485   default: break;
10486   case ISD::ZERO_EXTEND:
10487   case ISD::SIGN_EXTEND:
10488   case ISD::ANY_EXTEND: {
10489     auto Cond = RHS.getOperand(0);
10490     // If this won't be a real VOPC output, we would still need to insert an
10491     // extra instruction anyway.
10492     if (!isBoolSGPR(Cond))
10493       break;
10494     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10495     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10496     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10497     return DAG.getNode(Opc, SL, VTList, Args);
10498   }
10499   case ISD::ADDCARRY: {
10500     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10501     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10502     if (!C || C->getZExtValue() != 0) break;
10503     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10504     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10505   }
10506   }
10507   return SDValue();
10508 }
10509 
10510 SDValue SITargetLowering::performSubCombine(SDNode *N,
10511                                             DAGCombinerInfo &DCI) const {
10512   SelectionDAG &DAG = DCI.DAG;
10513   EVT VT = N->getValueType(0);
10514 
10515   if (VT != MVT::i32)
10516     return SDValue();
10517 
10518   SDLoc SL(N);
10519   SDValue LHS = N->getOperand(0);
10520   SDValue RHS = N->getOperand(1);
10521 
10522   // sub x, zext (setcc) => subcarry x, 0, setcc
10523   // sub x, sext (setcc) => addcarry x, 0, setcc
10524   unsigned Opc = RHS.getOpcode();
10525   switch (Opc) {
10526   default: break;
10527   case ISD::ZERO_EXTEND:
10528   case ISD::SIGN_EXTEND:
10529   case ISD::ANY_EXTEND: {
10530     auto Cond = RHS.getOperand(0);
10531     // If this won't be a real VOPC output, we would still need to insert an
10532     // extra instruction anyway.
10533     if (!isBoolSGPR(Cond))
10534       break;
10535     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10536     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10537     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10538     return DAG.getNode(Opc, SL, VTList, Args);
10539   }
10540   }
10541 
10542   if (LHS.getOpcode() == ISD::SUBCARRY) {
10543     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10544     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10545     if (!C || !C->isZero())
10546       return SDValue();
10547     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10548     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10549   }
10550   return SDValue();
10551 }
10552 
10553 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10554   DAGCombinerInfo &DCI) const {
10555 
10556   if (N->getValueType(0) != MVT::i32)
10557     return SDValue();
10558 
10559   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10560   if (!C || C->getZExtValue() != 0)
10561     return SDValue();
10562 
10563   SelectionDAG &DAG = DCI.DAG;
10564   SDValue LHS = N->getOperand(0);
10565 
10566   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10567   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10568   unsigned LHSOpc = LHS.getOpcode();
10569   unsigned Opc = N->getOpcode();
10570   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10571       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10572     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10573     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10574   }
10575   return SDValue();
10576 }
10577 
10578 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10579                                              DAGCombinerInfo &DCI) const {
10580   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10581     return SDValue();
10582 
10583   SelectionDAG &DAG = DCI.DAG;
10584   EVT VT = N->getValueType(0);
10585 
10586   SDLoc SL(N);
10587   SDValue LHS = N->getOperand(0);
10588   SDValue RHS = N->getOperand(1);
10589 
10590   // These should really be instruction patterns, but writing patterns with
10591   // source modiifiers is a pain.
10592 
10593   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10594   if (LHS.getOpcode() == ISD::FADD) {
10595     SDValue A = LHS.getOperand(0);
10596     if (A == LHS.getOperand(1)) {
10597       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10598       if (FusedOp != 0) {
10599         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10600         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10601       }
10602     }
10603   }
10604 
10605   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10606   if (RHS.getOpcode() == ISD::FADD) {
10607     SDValue A = RHS.getOperand(0);
10608     if (A == RHS.getOperand(1)) {
10609       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10610       if (FusedOp != 0) {
10611         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10612         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10613       }
10614     }
10615   }
10616 
10617   return SDValue();
10618 }
10619 
10620 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10621                                              DAGCombinerInfo &DCI) const {
10622   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10623     return SDValue();
10624 
10625   SelectionDAG &DAG = DCI.DAG;
10626   SDLoc SL(N);
10627   EVT VT = N->getValueType(0);
10628   assert(!VT.isVector());
10629 
10630   // Try to get the fneg to fold into the source modifier. This undoes generic
10631   // DAG combines and folds them into the mad.
10632   //
10633   // Only do this if we are not trying to support denormals. v_mad_f32 does
10634   // not support denormals ever.
10635   SDValue LHS = N->getOperand(0);
10636   SDValue RHS = N->getOperand(1);
10637   if (LHS.getOpcode() == ISD::FADD) {
10638     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10639     SDValue A = LHS.getOperand(0);
10640     if (A == LHS.getOperand(1)) {
10641       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10642       if (FusedOp != 0){
10643         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10644         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10645 
10646         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10647       }
10648     }
10649   }
10650 
10651   if (RHS.getOpcode() == ISD::FADD) {
10652     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10653 
10654     SDValue A = RHS.getOperand(0);
10655     if (A == RHS.getOperand(1)) {
10656       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10657       if (FusedOp != 0){
10658         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10659         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10660       }
10661     }
10662   }
10663 
10664   return SDValue();
10665 }
10666 
10667 SDValue SITargetLowering::performFMACombine(SDNode *N,
10668                                             DAGCombinerInfo &DCI) const {
10669   SelectionDAG &DAG = DCI.DAG;
10670   EVT VT = N->getValueType(0);
10671   SDLoc SL(N);
10672 
10673   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10674     return SDValue();
10675 
10676   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10677   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10678   SDValue Op1 = N->getOperand(0);
10679   SDValue Op2 = N->getOperand(1);
10680   SDValue FMA = N->getOperand(2);
10681 
10682   if (FMA.getOpcode() != ISD::FMA ||
10683       Op1.getOpcode() != ISD::FP_EXTEND ||
10684       Op2.getOpcode() != ISD::FP_EXTEND)
10685     return SDValue();
10686 
10687   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10688   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10689   // is sufficient to allow generaing fdot2.
10690   const TargetOptions &Options = DAG.getTarget().Options;
10691   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10692       (N->getFlags().hasAllowContract() &&
10693        FMA->getFlags().hasAllowContract())) {
10694     Op1 = Op1.getOperand(0);
10695     Op2 = Op2.getOperand(0);
10696     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10697         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10698       return SDValue();
10699 
10700     SDValue Vec1 = Op1.getOperand(0);
10701     SDValue Idx1 = Op1.getOperand(1);
10702     SDValue Vec2 = Op2.getOperand(0);
10703 
10704     SDValue FMAOp1 = FMA.getOperand(0);
10705     SDValue FMAOp2 = FMA.getOperand(1);
10706     SDValue FMAAcc = FMA.getOperand(2);
10707 
10708     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10709         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10710       return SDValue();
10711 
10712     FMAOp1 = FMAOp1.getOperand(0);
10713     FMAOp2 = FMAOp2.getOperand(0);
10714     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10715         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10716       return SDValue();
10717 
10718     SDValue Vec3 = FMAOp1.getOperand(0);
10719     SDValue Vec4 = FMAOp2.getOperand(0);
10720     SDValue Idx2 = FMAOp1.getOperand(1);
10721 
10722     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10723         // Idx1 and Idx2 cannot be the same.
10724         Idx1 == Idx2)
10725       return SDValue();
10726 
10727     if (Vec1 == Vec2 || Vec3 == Vec4)
10728       return SDValue();
10729 
10730     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10731       return SDValue();
10732 
10733     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10734         (Vec1 == Vec4 && Vec2 == Vec3)) {
10735       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10736                          DAG.getTargetConstant(0, SL, MVT::i1));
10737     }
10738   }
10739   return SDValue();
10740 }
10741 
10742 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10743                                               DAGCombinerInfo &DCI) const {
10744   SelectionDAG &DAG = DCI.DAG;
10745   SDLoc SL(N);
10746 
10747   SDValue LHS = N->getOperand(0);
10748   SDValue RHS = N->getOperand(1);
10749   EVT VT = LHS.getValueType();
10750   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10751 
10752   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10753   if (!CRHS) {
10754     CRHS = dyn_cast<ConstantSDNode>(LHS);
10755     if (CRHS) {
10756       std::swap(LHS, RHS);
10757       CC = getSetCCSwappedOperands(CC);
10758     }
10759   }
10760 
10761   if (CRHS) {
10762     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10763         isBoolSGPR(LHS.getOperand(0))) {
10764       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10765       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10766       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10767       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10768       if ((CRHS->isAllOnes() &&
10769            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10770           (CRHS->isZero() &&
10771            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10772         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10773                            DAG.getConstant(-1, SL, MVT::i1));
10774       if ((CRHS->isAllOnes() &&
10775            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10776           (CRHS->isZero() &&
10777            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10778         return LHS.getOperand(0);
10779     }
10780 
10781     uint64_t CRHSVal = CRHS->getZExtValue();
10782     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10783         LHS.getOpcode() == ISD::SELECT &&
10784         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10785         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10786         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10787         isBoolSGPR(LHS.getOperand(0))) {
10788       // Given CT != FT:
10789       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10790       // setcc (select cc, CT, CF), CF, ne => cc
10791       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10792       // setcc (select cc, CT, CF), CT, eq => cc
10793       uint64_t CT = LHS.getConstantOperandVal(1);
10794       uint64_t CF = LHS.getConstantOperandVal(2);
10795 
10796       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10797           (CT == CRHSVal && CC == ISD::SETNE))
10798         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10799                            DAG.getConstant(-1, SL, MVT::i1));
10800       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10801           (CT == CRHSVal && CC == ISD::SETEQ))
10802         return LHS.getOperand(0);
10803     }
10804   }
10805 
10806   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10807                                            VT != MVT::f16))
10808     return SDValue();
10809 
10810   // Match isinf/isfinite pattern
10811   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10812   // (fcmp one (fabs x), inf) -> (fp_class x,
10813   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10814   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10815     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10816     if (!CRHS)
10817       return SDValue();
10818 
10819     const APFloat &APF = CRHS->getValueAPF();
10820     if (APF.isInfinity() && !APF.isNegative()) {
10821       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10822                                  SIInstrFlags::N_INFINITY;
10823       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10824                                     SIInstrFlags::P_ZERO |
10825                                     SIInstrFlags::N_NORMAL |
10826                                     SIInstrFlags::P_NORMAL |
10827                                     SIInstrFlags::N_SUBNORMAL |
10828                                     SIInstrFlags::P_SUBNORMAL;
10829       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10830       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10831                          DAG.getConstant(Mask, SL, MVT::i32));
10832     }
10833   }
10834 
10835   return SDValue();
10836 }
10837 
10838 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10839                                                      DAGCombinerInfo &DCI) const {
10840   SelectionDAG &DAG = DCI.DAG;
10841   SDLoc SL(N);
10842   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10843 
10844   SDValue Src = N->getOperand(0);
10845   SDValue Shift = N->getOperand(0);
10846 
10847   // TODO: Extend type shouldn't matter (assuming legal types).
10848   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10849     Shift = Shift.getOperand(0);
10850 
10851   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10852     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10853     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10854     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10855     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10856     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10857     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10858       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10859                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10860 
10861       unsigned ShiftOffset = 8 * Offset;
10862       if (Shift.getOpcode() == ISD::SHL)
10863         ShiftOffset -= C->getZExtValue();
10864       else
10865         ShiftOffset += C->getZExtValue();
10866 
10867       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10868         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10869                            MVT::f32, Shift);
10870       }
10871     }
10872   }
10873 
10874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10875   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10876   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10877     // We simplified Src. If this node is not dead, visit it again so it is
10878     // folded properly.
10879     if (N->getOpcode() != ISD::DELETED_NODE)
10880       DCI.AddToWorklist(N);
10881     return SDValue(N, 0);
10882   }
10883 
10884   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10885   if (SDValue DemandedSrc =
10886           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10887     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10888 
10889   return SDValue();
10890 }
10891 
10892 SDValue SITargetLowering::performClampCombine(SDNode *N,
10893                                               DAGCombinerInfo &DCI) const {
10894   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10895   if (!CSrc)
10896     return SDValue();
10897 
10898   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10899   const APFloat &F = CSrc->getValueAPF();
10900   APFloat Zero = APFloat::getZero(F.getSemantics());
10901   if (F < Zero ||
10902       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10903     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10904   }
10905 
10906   APFloat One(F.getSemantics(), "1.0");
10907   if (F > One)
10908     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10909 
10910   return SDValue(CSrc, 0);
10911 }
10912 
10913 
10914 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10915                                             DAGCombinerInfo &DCI) const {
10916   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10917     return SDValue();
10918   switch (N->getOpcode()) {
10919   case ISD::ADD:
10920     return performAddCombine(N, DCI);
10921   case ISD::SUB:
10922     return performSubCombine(N, DCI);
10923   case ISD::ADDCARRY:
10924   case ISD::SUBCARRY:
10925     return performAddCarrySubCarryCombine(N, DCI);
10926   case ISD::FADD:
10927     return performFAddCombine(N, DCI);
10928   case ISD::FSUB:
10929     return performFSubCombine(N, DCI);
10930   case ISD::SETCC:
10931     return performSetCCCombine(N, DCI);
10932   case ISD::FMAXNUM:
10933   case ISD::FMINNUM:
10934   case ISD::FMAXNUM_IEEE:
10935   case ISD::FMINNUM_IEEE:
10936   case ISD::SMAX:
10937   case ISD::SMIN:
10938   case ISD::UMAX:
10939   case ISD::UMIN:
10940   case AMDGPUISD::FMIN_LEGACY:
10941   case AMDGPUISD::FMAX_LEGACY:
10942     return performMinMaxCombine(N, DCI);
10943   case ISD::FMA:
10944     return performFMACombine(N, DCI);
10945   case ISD::AND:
10946     return performAndCombine(N, DCI);
10947   case ISD::OR:
10948     return performOrCombine(N, DCI);
10949   case ISD::XOR:
10950     return performXorCombine(N, DCI);
10951   case ISD::ZERO_EXTEND:
10952     return performZeroExtendCombine(N, DCI);
10953   case ISD::SIGN_EXTEND_INREG:
10954     return performSignExtendInRegCombine(N , DCI);
10955   case AMDGPUISD::FP_CLASS:
10956     return performClassCombine(N, DCI);
10957   case ISD::FCANONICALIZE:
10958     return performFCanonicalizeCombine(N, DCI);
10959   case AMDGPUISD::RCP:
10960     return performRcpCombine(N, DCI);
10961   case AMDGPUISD::FRACT:
10962   case AMDGPUISD::RSQ:
10963   case AMDGPUISD::RCP_LEGACY:
10964   case AMDGPUISD::RCP_IFLAG:
10965   case AMDGPUISD::RSQ_CLAMP:
10966   case AMDGPUISD::LDEXP: {
10967     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10968     SDValue Src = N->getOperand(0);
10969     if (Src.isUndef())
10970       return Src;
10971     break;
10972   }
10973   case ISD::SINT_TO_FP:
10974   case ISD::UINT_TO_FP:
10975     return performUCharToFloatCombine(N, DCI);
10976   case AMDGPUISD::CVT_F32_UBYTE0:
10977   case AMDGPUISD::CVT_F32_UBYTE1:
10978   case AMDGPUISD::CVT_F32_UBYTE2:
10979   case AMDGPUISD::CVT_F32_UBYTE3:
10980     return performCvtF32UByteNCombine(N, DCI);
10981   case AMDGPUISD::FMED3:
10982     return performFMed3Combine(N, DCI);
10983   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10984     return performCvtPkRTZCombine(N, DCI);
10985   case AMDGPUISD::CLAMP:
10986     return performClampCombine(N, DCI);
10987   case ISD::SCALAR_TO_VECTOR: {
10988     SelectionDAG &DAG = DCI.DAG;
10989     EVT VT = N->getValueType(0);
10990 
10991     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10992     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10993       SDLoc SL(N);
10994       SDValue Src = N->getOperand(0);
10995       EVT EltVT = Src.getValueType();
10996       if (EltVT == MVT::f16)
10997         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10998 
10999       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11000       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11001     }
11002 
11003     break;
11004   }
11005   case ISD::EXTRACT_VECTOR_ELT:
11006     return performExtractVectorEltCombine(N, DCI);
11007   case ISD::INSERT_VECTOR_ELT:
11008     return performInsertVectorEltCombine(N, DCI);
11009   case ISD::LOAD: {
11010     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11011       return Widended;
11012     LLVM_FALLTHROUGH;
11013   }
11014   default: {
11015     if (!DCI.isBeforeLegalize()) {
11016       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11017         return performMemSDNodeCombine(MemNode, DCI);
11018     }
11019 
11020     break;
11021   }
11022   }
11023 
11024   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11025 }
11026 
11027 /// Helper function for adjustWritemask
11028 static unsigned SubIdx2Lane(unsigned Idx) {
11029   switch (Idx) {
11030   default: return ~0u;
11031   case AMDGPU::sub0: return 0;
11032   case AMDGPU::sub1: return 1;
11033   case AMDGPU::sub2: return 2;
11034   case AMDGPU::sub3: return 3;
11035   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11036   }
11037 }
11038 
11039 /// Adjust the writemask of MIMG instructions
11040 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11041                                           SelectionDAG &DAG) const {
11042   unsigned Opcode = Node->getMachineOpcode();
11043 
11044   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11045   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11046   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11047     return Node; // not implemented for D16
11048 
11049   SDNode *Users[5] = { nullptr };
11050   unsigned Lane = 0;
11051   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11052   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11053   unsigned NewDmask = 0;
11054   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11055   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11056   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11057                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11058   unsigned TFCLane = 0;
11059   bool HasChain = Node->getNumValues() > 1;
11060 
11061   if (OldDmask == 0) {
11062     // These are folded out, but on the chance it happens don't assert.
11063     return Node;
11064   }
11065 
11066   unsigned OldBitsSet = countPopulation(OldDmask);
11067   // Work out which is the TFE/LWE lane if that is enabled.
11068   if (UsesTFC) {
11069     TFCLane = OldBitsSet;
11070   }
11071 
11072   // Try to figure out the used register components
11073   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11074        I != E; ++I) {
11075 
11076     // Don't look at users of the chain.
11077     if (I.getUse().getResNo() != 0)
11078       continue;
11079 
11080     // Abort if we can't understand the usage
11081     if (!I->isMachineOpcode() ||
11082         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11083       return Node;
11084 
11085     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11086     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11087     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11088     // set, etc.
11089     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11090     if (Lane == ~0u)
11091       return Node;
11092 
11093     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11094     if (UsesTFC && Lane == TFCLane) {
11095       Users[Lane] = *I;
11096     } else {
11097       // Set which texture component corresponds to the lane.
11098       unsigned Comp;
11099       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11100         Comp = countTrailingZeros(Dmask);
11101         Dmask &= ~(1 << Comp);
11102       }
11103 
11104       // Abort if we have more than one user per component.
11105       if (Users[Lane])
11106         return Node;
11107 
11108       Users[Lane] = *I;
11109       NewDmask |= 1 << Comp;
11110     }
11111   }
11112 
11113   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11114   bool NoChannels = !NewDmask;
11115   if (NoChannels) {
11116     if (!UsesTFC) {
11117       // No uses of the result and not using TFC. Then do nothing.
11118       return Node;
11119     }
11120     // If the original dmask has one channel - then nothing to do
11121     if (OldBitsSet == 1)
11122       return Node;
11123     // Use an arbitrary dmask - required for the instruction to work
11124     NewDmask = 1;
11125   }
11126   // Abort if there's no change
11127   if (NewDmask == OldDmask)
11128     return Node;
11129 
11130   unsigned BitsSet = countPopulation(NewDmask);
11131 
11132   // Check for TFE or LWE - increase the number of channels by one to account
11133   // for the extra return value
11134   // This will need adjustment for D16 if this is also included in
11135   // adjustWriteMask (this function) but at present D16 are excluded.
11136   unsigned NewChannels = BitsSet + UsesTFC;
11137 
11138   int NewOpcode =
11139       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11140   assert(NewOpcode != -1 &&
11141          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11142          "failed to find equivalent MIMG op");
11143 
11144   // Adjust the writemask in the node
11145   SmallVector<SDValue, 12> Ops;
11146   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11147   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11148   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11149 
11150   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11151 
11152   MVT ResultVT = NewChannels == 1 ?
11153     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11154                            NewChannels == 5 ? 8 : NewChannels);
11155   SDVTList NewVTList = HasChain ?
11156     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11157 
11158 
11159   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11160                                               NewVTList, Ops);
11161 
11162   if (HasChain) {
11163     // Update chain.
11164     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11165     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11166   }
11167 
11168   if (NewChannels == 1) {
11169     assert(Node->hasNUsesOfValue(1, 0));
11170     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11171                                       SDLoc(Node), Users[Lane]->getValueType(0),
11172                                       SDValue(NewNode, 0));
11173     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11174     return nullptr;
11175   }
11176 
11177   // Update the users of the node with the new indices
11178   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11179     SDNode *User = Users[i];
11180     if (!User) {
11181       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11182       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11183       if (i || !NoChannels)
11184         continue;
11185     } else {
11186       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11187       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11188     }
11189 
11190     switch (Idx) {
11191     default: break;
11192     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11193     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11194     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11195     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11196     }
11197   }
11198 
11199   DAG.RemoveDeadNode(Node);
11200   return nullptr;
11201 }
11202 
11203 static bool isFrameIndexOp(SDValue Op) {
11204   if (Op.getOpcode() == ISD::AssertZext)
11205     Op = Op.getOperand(0);
11206 
11207   return isa<FrameIndexSDNode>(Op);
11208 }
11209 
11210 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11211 /// with frame index operands.
11212 /// LLVM assumes that inputs are to these instructions are registers.
11213 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11214                                                         SelectionDAG &DAG) const {
11215   if (Node->getOpcode() == ISD::CopyToReg) {
11216     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11217     SDValue SrcVal = Node->getOperand(2);
11218 
11219     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11220     // to try understanding copies to physical registers.
11221     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11222       SDLoc SL(Node);
11223       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11224       SDValue VReg = DAG.getRegister(
11225         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11226 
11227       SDNode *Glued = Node->getGluedNode();
11228       SDValue ToVReg
11229         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11230                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11231       SDValue ToResultReg
11232         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11233                            VReg, ToVReg.getValue(1));
11234       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11235       DAG.RemoveDeadNode(Node);
11236       return ToResultReg.getNode();
11237     }
11238   }
11239 
11240   SmallVector<SDValue, 8> Ops;
11241   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11242     if (!isFrameIndexOp(Node->getOperand(i))) {
11243       Ops.push_back(Node->getOperand(i));
11244       continue;
11245     }
11246 
11247     SDLoc DL(Node);
11248     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11249                                      Node->getOperand(i).getValueType(),
11250                                      Node->getOperand(i)), 0));
11251   }
11252 
11253   return DAG.UpdateNodeOperands(Node, Ops);
11254 }
11255 
11256 /// Fold the instructions after selecting them.
11257 /// Returns null if users were already updated.
11258 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11259                                           SelectionDAG &DAG) const {
11260   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11261   unsigned Opcode = Node->getMachineOpcode();
11262 
11263   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11264       !TII->isGather4(Opcode) &&
11265       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11266     return adjustWritemask(Node, DAG);
11267   }
11268 
11269   if (Opcode == AMDGPU::INSERT_SUBREG ||
11270       Opcode == AMDGPU::REG_SEQUENCE) {
11271     legalizeTargetIndependentNode(Node, DAG);
11272     return Node;
11273   }
11274 
11275   switch (Opcode) {
11276   case AMDGPU::V_DIV_SCALE_F32_e64:
11277   case AMDGPU::V_DIV_SCALE_F64_e64: {
11278     // Satisfy the operand register constraint when one of the inputs is
11279     // undefined. Ordinarily each undef value will have its own implicit_def of
11280     // a vreg, so force these to use a single register.
11281     SDValue Src0 = Node->getOperand(1);
11282     SDValue Src1 = Node->getOperand(3);
11283     SDValue Src2 = Node->getOperand(5);
11284 
11285     if ((Src0.isMachineOpcode() &&
11286          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11287         (Src0 == Src1 || Src0 == Src2))
11288       break;
11289 
11290     MVT VT = Src0.getValueType().getSimpleVT();
11291     const TargetRegisterClass *RC =
11292         getRegClassFor(VT, Src0.getNode()->isDivergent());
11293 
11294     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11295     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11296 
11297     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11298                                       UndefReg, Src0, SDValue());
11299 
11300     // src0 must be the same register as src1 or src2, even if the value is
11301     // undefined, so make sure we don't violate this constraint.
11302     if (Src0.isMachineOpcode() &&
11303         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11304       if (Src1.isMachineOpcode() &&
11305           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11306         Src0 = Src1;
11307       else if (Src2.isMachineOpcode() &&
11308                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11309         Src0 = Src2;
11310       else {
11311         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11312         Src0 = UndefReg;
11313         Src1 = UndefReg;
11314       }
11315     } else
11316       break;
11317 
11318     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11319     Ops[1] = Src0;
11320     Ops[3] = Src1;
11321     Ops[5] = Src2;
11322     Ops.push_back(ImpDef.getValue(1));
11323     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11324   }
11325   default:
11326     break;
11327   }
11328 
11329   return Node;
11330 }
11331 
11332 // Any MIMG instructions that use tfe or lwe require an initialization of the
11333 // result register that will be written in the case of a memory access failure.
11334 // The required code is also added to tie this init code to the result of the
11335 // img instruction.
11336 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11337   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11338   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11339   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11340   MachineBasicBlock &MBB = *MI.getParent();
11341 
11342   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11343   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11344   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11345 
11346   if (!TFE && !LWE) // intersect_ray
11347     return;
11348 
11349   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11350   unsigned LWEVal = LWE->getImm();
11351   unsigned D16Val = D16 ? D16->getImm() : 0;
11352 
11353   if (!TFEVal && !LWEVal)
11354     return;
11355 
11356   // At least one of TFE or LWE are non-zero
11357   // We have to insert a suitable initialization of the result value and
11358   // tie this to the dest of the image instruction.
11359 
11360   const DebugLoc &DL = MI.getDebugLoc();
11361 
11362   int DstIdx =
11363       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11364 
11365   // Calculate which dword we have to initialize to 0.
11366   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11367 
11368   // check that dmask operand is found.
11369   assert(MO_Dmask && "Expected dmask operand in instruction");
11370 
11371   unsigned dmask = MO_Dmask->getImm();
11372   // Determine the number of active lanes taking into account the
11373   // Gather4 special case
11374   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11375 
11376   bool Packed = !Subtarget->hasUnpackedD16VMem();
11377 
11378   unsigned InitIdx =
11379       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11380 
11381   // Abandon attempt if the dst size isn't large enough
11382   // - this is in fact an error but this is picked up elsewhere and
11383   // reported correctly.
11384   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11385   if (DstSize < InitIdx)
11386     return;
11387 
11388   // Create a register for the intialization value.
11389   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11390   unsigned NewDst = 0; // Final initialized value will be in here
11391 
11392   // If PRTStrictNull feature is enabled (the default) then initialize
11393   // all the result registers to 0, otherwise just the error indication
11394   // register (VGPRn+1)
11395   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11396   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11397 
11398   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11399   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11400     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11401     // Initialize dword
11402     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11403     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11404       .addImm(0);
11405     // Insert into the super-reg
11406     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11407       .addReg(PrevDst)
11408       .addReg(SubReg)
11409       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11410 
11411     PrevDst = NewDst;
11412   }
11413 
11414   // Add as an implicit operand
11415   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11416 
11417   // Tie the just added implicit operand to the dst
11418   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11419 }
11420 
11421 /// Assign the register class depending on the number of
11422 /// bits set in the writemask
11423 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11424                                                      SDNode *Node) const {
11425   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11426 
11427   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11428 
11429   if (TII->isVOP3(MI.getOpcode())) {
11430     // Make sure constant bus requirements are respected.
11431     TII->legalizeOperandsVOP3(MRI, MI);
11432 
11433     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11434     // This saves a chain-copy of registers and better ballance register
11435     // use between vgpr and agpr as agpr tuples tend to be big.
11436     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11437       unsigned Opc = MI.getOpcode();
11438       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11439       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11440                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11441         if (I == -1)
11442           break;
11443         MachineOperand &Op = MI.getOperand(I);
11444         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11445              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11446             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11447           continue;
11448         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11449         if (!Src || !Src->isCopy() ||
11450             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11451           continue;
11452         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11453         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11454         // All uses of agpr64 and agpr32 can also accept vgpr except for
11455         // v_accvgpr_read, but we do not produce agpr reads during selection,
11456         // so no use checks are needed.
11457         MRI.setRegClass(Op.getReg(), NewRC);
11458       }
11459     }
11460 
11461     return;
11462   }
11463 
11464   // Replace unused atomics with the no return version.
11465   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11466   if (NoRetAtomicOp != -1) {
11467     if (!Node->hasAnyUseOfValue(0)) {
11468       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11469                                                AMDGPU::OpName::cpol);
11470       if (CPolIdx != -1) {
11471         MachineOperand &CPol = MI.getOperand(CPolIdx);
11472         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11473       }
11474       MI.RemoveOperand(0);
11475       MI.setDesc(TII->get(NoRetAtomicOp));
11476       return;
11477     }
11478 
11479     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11480     // instruction, because the return type of these instructions is a vec2 of
11481     // the memory type, so it can be tied to the input operand.
11482     // This means these instructions always have a use, so we need to add a
11483     // special case to check if the atomic has only one extract_subreg use,
11484     // which itself has no uses.
11485     if ((Node->hasNUsesOfValue(1, 0) &&
11486          Node->use_begin()->isMachineOpcode() &&
11487          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11488          !Node->use_begin()->hasAnyUseOfValue(0))) {
11489       Register Def = MI.getOperand(0).getReg();
11490 
11491       // Change this into a noret atomic.
11492       MI.setDesc(TII->get(NoRetAtomicOp));
11493       MI.RemoveOperand(0);
11494 
11495       // If we only remove the def operand from the atomic instruction, the
11496       // extract_subreg will be left with a use of a vreg without a def.
11497       // So we need to insert an implicit_def to avoid machine verifier
11498       // errors.
11499       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11500               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11501     }
11502     return;
11503   }
11504 
11505   if (TII->isMIMG(MI) && !MI.mayStore())
11506     AddIMGInit(MI);
11507 }
11508 
11509 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11510                               uint64_t Val) {
11511   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11512   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11513 }
11514 
11515 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11516                                                 const SDLoc &DL,
11517                                                 SDValue Ptr) const {
11518   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11519 
11520   // Build the half of the subregister with the constants before building the
11521   // full 128-bit register. If we are building multiple resource descriptors,
11522   // this will allow CSEing of the 2-component register.
11523   const SDValue Ops0[] = {
11524     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11525     buildSMovImm32(DAG, DL, 0),
11526     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11527     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11528     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11529   };
11530 
11531   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11532                                                 MVT::v2i32, Ops0), 0);
11533 
11534   // Combine the constants and the pointer.
11535   const SDValue Ops1[] = {
11536     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11537     Ptr,
11538     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11539     SubRegHi,
11540     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11541   };
11542 
11543   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11544 }
11545 
11546 /// Return a resource descriptor with the 'Add TID' bit enabled
11547 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11548 ///        of the resource descriptor) to create an offset, which is added to
11549 ///        the resource pointer.
11550 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11551                                            SDValue Ptr, uint32_t RsrcDword1,
11552                                            uint64_t RsrcDword2And3) const {
11553   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11554   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11555   if (RsrcDword1) {
11556     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11557                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11558                     0);
11559   }
11560 
11561   SDValue DataLo = buildSMovImm32(DAG, DL,
11562                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11563   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11564 
11565   const SDValue Ops[] = {
11566     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11567     PtrLo,
11568     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11569     PtrHi,
11570     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11571     DataLo,
11572     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11573     DataHi,
11574     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11575   };
11576 
11577   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11578 }
11579 
11580 //===----------------------------------------------------------------------===//
11581 //                         SI Inline Assembly Support
11582 //===----------------------------------------------------------------------===//
11583 
11584 std::pair<unsigned, const TargetRegisterClass *>
11585 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11586                                                StringRef Constraint,
11587                                                MVT VT) const {
11588   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11589 
11590   const TargetRegisterClass *RC = nullptr;
11591   if (Constraint.size() == 1) {
11592     const unsigned BitWidth = VT.getSizeInBits();
11593     switch (Constraint[0]) {
11594     default:
11595       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11596     case 's':
11597     case 'r':
11598       switch (BitWidth) {
11599       case 16:
11600         RC = &AMDGPU::SReg_32RegClass;
11601         break;
11602       case 64:
11603         RC = &AMDGPU::SGPR_64RegClass;
11604         break;
11605       default:
11606         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11607         if (!RC)
11608           return std::make_pair(0U, nullptr);
11609         break;
11610       }
11611       break;
11612     case 'v':
11613       switch (BitWidth) {
11614       case 16:
11615         RC = &AMDGPU::VGPR_32RegClass;
11616         break;
11617       default:
11618         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11619         if (!RC)
11620           return std::make_pair(0U, nullptr);
11621         break;
11622       }
11623       break;
11624     case 'a':
11625       if (!Subtarget->hasMAIInsts())
11626         break;
11627       switch (BitWidth) {
11628       case 16:
11629         RC = &AMDGPU::AGPR_32RegClass;
11630         break;
11631       default:
11632         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11633         if (!RC)
11634           return std::make_pair(0U, nullptr);
11635         break;
11636       }
11637       break;
11638     }
11639     // We actually support i128, i16 and f16 as inline parameters
11640     // even if they are not reported as legal
11641     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11642                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11643       return std::make_pair(0U, RC);
11644   }
11645 
11646   if (Constraint.size() > 1) {
11647     if (Constraint[1] == 'v') {
11648       RC = &AMDGPU::VGPR_32RegClass;
11649     } else if (Constraint[1] == 's') {
11650       RC = &AMDGPU::SGPR_32RegClass;
11651     } else if (Constraint[1] == 'a') {
11652       RC = &AMDGPU::AGPR_32RegClass;
11653     }
11654 
11655     if (RC) {
11656       uint32_t Idx;
11657       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11658       if (!Failed && Idx < RC->getNumRegs())
11659         return std::make_pair(RC->getRegister(Idx), RC);
11660     }
11661   }
11662 
11663   // FIXME: Returns VS_32 for physical SGPR constraints
11664   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11665 }
11666 
11667 static bool isImmConstraint(StringRef Constraint) {
11668   if (Constraint.size() == 1) {
11669     switch (Constraint[0]) {
11670     default: break;
11671     case 'I':
11672     case 'J':
11673     case 'A':
11674     case 'B':
11675     case 'C':
11676       return true;
11677     }
11678   } else if (Constraint == "DA" ||
11679              Constraint == "DB") {
11680     return true;
11681   }
11682   return false;
11683 }
11684 
11685 SITargetLowering::ConstraintType
11686 SITargetLowering::getConstraintType(StringRef Constraint) const {
11687   if (Constraint.size() == 1) {
11688     switch (Constraint[0]) {
11689     default: break;
11690     case 's':
11691     case 'v':
11692     case 'a':
11693       return C_RegisterClass;
11694     }
11695   }
11696   if (isImmConstraint(Constraint)) {
11697     return C_Other;
11698   }
11699   return TargetLowering::getConstraintType(Constraint);
11700 }
11701 
11702 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11703   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11704     Val = Val & maskTrailingOnes<uint64_t>(Size);
11705   }
11706   return Val;
11707 }
11708 
11709 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11710                                                     std::string &Constraint,
11711                                                     std::vector<SDValue> &Ops,
11712                                                     SelectionDAG &DAG) const {
11713   if (isImmConstraint(Constraint)) {
11714     uint64_t Val;
11715     if (getAsmOperandConstVal(Op, Val) &&
11716         checkAsmConstraintVal(Op, Constraint, Val)) {
11717       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11718       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11719     }
11720   } else {
11721     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11722   }
11723 }
11724 
11725 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11726   unsigned Size = Op.getScalarValueSizeInBits();
11727   if (Size > 64)
11728     return false;
11729 
11730   if (Size == 16 && !Subtarget->has16BitInsts())
11731     return false;
11732 
11733   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11734     Val = C->getSExtValue();
11735     return true;
11736   }
11737   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11738     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11739     return true;
11740   }
11741   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11742     if (Size != 16 || Op.getNumOperands() != 2)
11743       return false;
11744     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11745       return false;
11746     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11747       Val = C->getSExtValue();
11748       return true;
11749     }
11750     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11751       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11752       return true;
11753     }
11754   }
11755 
11756   return false;
11757 }
11758 
11759 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11760                                              const std::string &Constraint,
11761                                              uint64_t Val) const {
11762   if (Constraint.size() == 1) {
11763     switch (Constraint[0]) {
11764     case 'I':
11765       return AMDGPU::isInlinableIntLiteral(Val);
11766     case 'J':
11767       return isInt<16>(Val);
11768     case 'A':
11769       return checkAsmConstraintValA(Op, Val);
11770     case 'B':
11771       return isInt<32>(Val);
11772     case 'C':
11773       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11774              AMDGPU::isInlinableIntLiteral(Val);
11775     default:
11776       break;
11777     }
11778   } else if (Constraint.size() == 2) {
11779     if (Constraint == "DA") {
11780       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11781       int64_t LoBits = static_cast<int32_t>(Val);
11782       return checkAsmConstraintValA(Op, HiBits, 32) &&
11783              checkAsmConstraintValA(Op, LoBits, 32);
11784     }
11785     if (Constraint == "DB") {
11786       return true;
11787     }
11788   }
11789   llvm_unreachable("Invalid asm constraint");
11790 }
11791 
11792 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11793                                               uint64_t Val,
11794                                               unsigned MaxSize) const {
11795   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11796   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11797   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11798       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11799       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11800     return true;
11801   }
11802   return false;
11803 }
11804 
11805 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11806   switch (UnalignedClassID) {
11807   case AMDGPU::VReg_64RegClassID:
11808     return AMDGPU::VReg_64_Align2RegClassID;
11809   case AMDGPU::VReg_96RegClassID:
11810     return AMDGPU::VReg_96_Align2RegClassID;
11811   case AMDGPU::VReg_128RegClassID:
11812     return AMDGPU::VReg_128_Align2RegClassID;
11813   case AMDGPU::VReg_160RegClassID:
11814     return AMDGPU::VReg_160_Align2RegClassID;
11815   case AMDGPU::VReg_192RegClassID:
11816     return AMDGPU::VReg_192_Align2RegClassID;
11817   case AMDGPU::VReg_224RegClassID:
11818     return AMDGPU::VReg_224_Align2RegClassID;
11819   case AMDGPU::VReg_256RegClassID:
11820     return AMDGPU::VReg_256_Align2RegClassID;
11821   case AMDGPU::VReg_512RegClassID:
11822     return AMDGPU::VReg_512_Align2RegClassID;
11823   case AMDGPU::VReg_1024RegClassID:
11824     return AMDGPU::VReg_1024_Align2RegClassID;
11825   case AMDGPU::AReg_64RegClassID:
11826     return AMDGPU::AReg_64_Align2RegClassID;
11827   case AMDGPU::AReg_96RegClassID:
11828     return AMDGPU::AReg_96_Align2RegClassID;
11829   case AMDGPU::AReg_128RegClassID:
11830     return AMDGPU::AReg_128_Align2RegClassID;
11831   case AMDGPU::AReg_160RegClassID:
11832     return AMDGPU::AReg_160_Align2RegClassID;
11833   case AMDGPU::AReg_192RegClassID:
11834     return AMDGPU::AReg_192_Align2RegClassID;
11835   case AMDGPU::AReg_256RegClassID:
11836     return AMDGPU::AReg_256_Align2RegClassID;
11837   case AMDGPU::AReg_512RegClassID:
11838     return AMDGPU::AReg_512_Align2RegClassID;
11839   case AMDGPU::AReg_1024RegClassID:
11840     return AMDGPU::AReg_1024_Align2RegClassID;
11841   default:
11842     return -1;
11843   }
11844 }
11845 
11846 // Figure out which registers should be reserved for stack access. Only after
11847 // the function is legalized do we know all of the non-spill stack objects or if
11848 // calls are present.
11849 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11850   MachineRegisterInfo &MRI = MF.getRegInfo();
11851   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11852   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11853   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11854   const SIInstrInfo *TII = ST.getInstrInfo();
11855 
11856   if (Info->isEntryFunction()) {
11857     // Callable functions have fixed registers used for stack access.
11858     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11859   }
11860 
11861   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11862                              Info->getStackPtrOffsetReg()));
11863   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11864     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11865 
11866   // We need to worry about replacing the default register with itself in case
11867   // of MIR testcases missing the MFI.
11868   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11869     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11870 
11871   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11872     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11873 
11874   Info->limitOccupancy(MF);
11875 
11876   if (ST.isWave32() && !MF.empty()) {
11877     for (auto &MBB : MF) {
11878       for (auto &MI : MBB) {
11879         TII->fixImplicitOperands(MI);
11880       }
11881     }
11882   }
11883 
11884   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11885   // classes if required. Ideally the register class constraints would differ
11886   // per-subtarget, but there's no easy way to achieve that right now. This is
11887   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11888   // from using them as the register class for legal types.
11889   if (ST.needsAlignedVGPRs()) {
11890     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11891       const Register Reg = Register::index2VirtReg(I);
11892       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11893       if (!RC)
11894         continue;
11895       int NewClassID = getAlignedAGPRClassID(RC->getID());
11896       if (NewClassID != -1)
11897         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11898     }
11899   }
11900 
11901   TargetLoweringBase::finalizeLowering(MF);
11902 
11903   // Allocate a VGPR for future SGPR Spill if
11904   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11905   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11906   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11907       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11908     Info->reserveVGPRforSGPRSpills(MF);
11909 }
11910 
11911 void SITargetLowering::computeKnownBitsForFrameIndex(
11912   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11913   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11914 
11915   // Set the high bits to zero based on the maximum allowed scratch size per
11916   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11917   // calculation won't overflow, so assume the sign bit is never set.
11918   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11919 }
11920 
11921 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11922                                    KnownBits &Known, unsigned Dim) {
11923   unsigned MaxValue =
11924       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11925   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11926 }
11927 
11928 void SITargetLowering::computeKnownBitsForTargetInstr(
11929     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11930     const MachineRegisterInfo &MRI, unsigned Depth) const {
11931   const MachineInstr *MI = MRI.getVRegDef(R);
11932   switch (MI->getOpcode()) {
11933   case AMDGPU::G_INTRINSIC: {
11934     switch (MI->getIntrinsicID()) {
11935     case Intrinsic::amdgcn_workitem_id_x:
11936       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11937       break;
11938     case Intrinsic::amdgcn_workitem_id_y:
11939       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11940       break;
11941     case Intrinsic::amdgcn_workitem_id_z:
11942       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11943       break;
11944     case Intrinsic::amdgcn_mbcnt_lo:
11945     case Intrinsic::amdgcn_mbcnt_hi: {
11946       // These return at most the wavefront size - 1.
11947       unsigned Size = MRI.getType(R).getSizeInBits();
11948       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11949       break;
11950     }
11951     case Intrinsic::amdgcn_groupstaticsize: {
11952       // We can report everything over the maximum size as 0. We can't report
11953       // based on the actual size because we don't know if it's accurate or not
11954       // at any given point.
11955       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11956       break;
11957     }
11958     }
11959     break;
11960   }
11961   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11962     Known.Zero.setHighBits(24);
11963     break;
11964   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11965     Known.Zero.setHighBits(16);
11966     break;
11967   }
11968 }
11969 
11970 Align SITargetLowering::computeKnownAlignForTargetInstr(
11971   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11972   unsigned Depth) const {
11973   const MachineInstr *MI = MRI.getVRegDef(R);
11974   switch (MI->getOpcode()) {
11975   case AMDGPU::G_INTRINSIC:
11976   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11977     // FIXME: Can this move to generic code? What about the case where the call
11978     // site specifies a lower alignment?
11979     Intrinsic::ID IID = MI->getIntrinsicID();
11980     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11981     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11982     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11983       return *RetAlign;
11984     return Align(1);
11985   }
11986   default:
11987     return Align(1);
11988   }
11989 }
11990 
11991 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11992   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11993   const Align CacheLineAlign = Align(64);
11994 
11995   // Pre-GFX10 target did not benefit from loop alignment
11996   if (!ML || DisableLoopAlignment ||
11997       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11998       getSubtarget()->hasInstFwdPrefetchBug())
11999     return PrefAlign;
12000 
12001   // On GFX10 I$ is 4 x 64 bytes cache lines.
12002   // By default prefetcher keeps one cache line behind and reads two ahead.
12003   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12004   // behind and one ahead.
12005   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12006   // If loop fits 64 bytes it always spans no more than two cache lines and
12007   // does not need an alignment.
12008   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12009   // Else if loop is less or equal 192 bytes we need two lines behind.
12010 
12011   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12012   const MachineBasicBlock *Header = ML->getHeader();
12013   if (Header->getAlignment() != PrefAlign)
12014     return Header->getAlignment(); // Already processed.
12015 
12016   unsigned LoopSize = 0;
12017   for (const MachineBasicBlock *MBB : ML->blocks()) {
12018     // If inner loop block is aligned assume in average half of the alignment
12019     // size to be added as nops.
12020     if (MBB != Header)
12021       LoopSize += MBB->getAlignment().value() / 2;
12022 
12023     for (const MachineInstr &MI : *MBB) {
12024       LoopSize += TII->getInstSizeInBytes(MI);
12025       if (LoopSize > 192)
12026         return PrefAlign;
12027     }
12028   }
12029 
12030   if (LoopSize <= 64)
12031     return PrefAlign;
12032 
12033   if (LoopSize <= 128)
12034     return CacheLineAlign;
12035 
12036   // If any of parent loops is surrounded by prefetch instructions do not
12037   // insert new for inner loop, which would reset parent's settings.
12038   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12039     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12040       auto I = Exit->getFirstNonDebugInstr();
12041       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12042         return CacheLineAlign;
12043     }
12044   }
12045 
12046   MachineBasicBlock *Pre = ML->getLoopPreheader();
12047   MachineBasicBlock *Exit = ML->getExitBlock();
12048 
12049   if (Pre && Exit) {
12050     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12051             TII->get(AMDGPU::S_INST_PREFETCH))
12052       .addImm(1); // prefetch 2 lines behind PC
12053 
12054     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12055             TII->get(AMDGPU::S_INST_PREFETCH))
12056       .addImm(2); // prefetch 1 line behind PC
12057   }
12058 
12059   return CacheLineAlign;
12060 }
12061 
12062 LLVM_ATTRIBUTE_UNUSED
12063 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12064   assert(N->getOpcode() == ISD::CopyFromReg);
12065   do {
12066     // Follow the chain until we find an INLINEASM node.
12067     N = N->getOperand(0).getNode();
12068     if (N->getOpcode() == ISD::INLINEASM ||
12069         N->getOpcode() == ISD::INLINEASM_BR)
12070       return true;
12071   } while (N->getOpcode() == ISD::CopyFromReg);
12072   return false;
12073 }
12074 
12075 bool SITargetLowering::isSDNodeSourceOfDivergence(
12076     const SDNode *N, FunctionLoweringInfo *FLI,
12077     LegacyDivergenceAnalysis *KDA) const {
12078   switch (N->getOpcode()) {
12079   case ISD::CopyFromReg: {
12080     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12081     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12082     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12083     Register Reg = R->getReg();
12084 
12085     // FIXME: Why does this need to consider isLiveIn?
12086     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12087       return !TRI->isSGPRReg(MRI, Reg);
12088 
12089     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12090       return KDA->isDivergent(V);
12091 
12092     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12093     return !TRI->isSGPRReg(MRI, Reg);
12094   }
12095   case ISD::LOAD: {
12096     const LoadSDNode *L = cast<LoadSDNode>(N);
12097     unsigned AS = L->getAddressSpace();
12098     // A flat load may access private memory.
12099     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12100   }
12101   case ISD::CALLSEQ_END:
12102     return true;
12103   case ISD::INTRINSIC_WO_CHAIN:
12104     return AMDGPU::isIntrinsicSourceOfDivergence(
12105         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12106   case ISD::INTRINSIC_W_CHAIN:
12107     return AMDGPU::isIntrinsicSourceOfDivergence(
12108         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12109   case AMDGPUISD::ATOMIC_CMP_SWAP:
12110   case AMDGPUISD::ATOMIC_INC:
12111   case AMDGPUISD::ATOMIC_DEC:
12112   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12113   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12114   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12115   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12116   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12117   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12118   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12119   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12120   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12121   case AMDGPUISD::BUFFER_ATOMIC_AND:
12122   case AMDGPUISD::BUFFER_ATOMIC_OR:
12123   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12124   case AMDGPUISD::BUFFER_ATOMIC_INC:
12125   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12126   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12127   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12128   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12129   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12130   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12131     // Target-specific read-modify-write atomics are sources of divergence.
12132     return true;
12133   default:
12134     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12135       // Generic read-modify-write atomics are sources of divergence.
12136       return A->readMem() && A->writeMem();
12137     }
12138     return false;
12139   }
12140 }
12141 
12142 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12143                                                EVT VT) const {
12144   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12145   case MVT::f32:
12146     return hasFP32Denormals(DAG.getMachineFunction());
12147   case MVT::f64:
12148   case MVT::f16:
12149     return hasFP64FP16Denormals(DAG.getMachineFunction());
12150   default:
12151     return false;
12152   }
12153 }
12154 
12155 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12156                                                MachineFunction &MF) const {
12157   switch (Ty.getScalarSizeInBits()) {
12158   case 32:
12159     return hasFP32Denormals(MF);
12160   case 64:
12161   case 16:
12162     return hasFP64FP16Denormals(MF);
12163   default:
12164     return false;
12165   }
12166 }
12167 
12168 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12169                                                     const SelectionDAG &DAG,
12170                                                     bool SNaN,
12171                                                     unsigned Depth) const {
12172   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12173     const MachineFunction &MF = DAG.getMachineFunction();
12174     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12175 
12176     if (Info->getMode().DX10Clamp)
12177       return true; // Clamped to 0.
12178     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12179   }
12180 
12181   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12182                                                             SNaN, Depth);
12183 }
12184 
12185 // Global FP atomic instructions have a hardcoded FP mode and do not support
12186 // FP32 denormals, and only support v2f16 denormals.
12187 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12188   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12189   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12190   if (&Flt == &APFloat::IEEEsingle())
12191     return DenormMode == DenormalMode::getPreserveSign();
12192   return DenormMode == DenormalMode::getIEEE();
12193 }
12194 
12195 TargetLowering::AtomicExpansionKind
12196 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12197 
12198   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12199     OptimizationRemarkEmitter ORE(RMW->getFunction());
12200     LLVMContext &Ctx = RMW->getFunction()->getContext();
12201     SmallVector<StringRef> SSNs;
12202     Ctx.getSyncScopeNames(SSNs);
12203     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12204                         ? "system"
12205                         : SSNs[RMW->getSyncScopeID()];
12206     ORE.emit([&]() {
12207       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12208              << "Hardware instruction generated for atomic "
12209              << RMW->getOperationName(RMW->getOperation())
12210              << " operation at memory scope " << MemScope
12211              << " due to an unsafe request.";
12212     });
12213     return Kind;
12214   };
12215 
12216   switch (RMW->getOperation()) {
12217   case AtomicRMWInst::FAdd: {
12218     Type *Ty = RMW->getType();
12219 
12220     // We don't have a way to support 16-bit atomics now, so just leave them
12221     // as-is.
12222     if (Ty->isHalfTy())
12223       return AtomicExpansionKind::None;
12224 
12225     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12226       return AtomicExpansionKind::CmpXChg;
12227 
12228     unsigned AS = RMW->getPointerAddressSpace();
12229 
12230     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12231          Subtarget->hasAtomicFaddInsts()) {
12232       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12233       // floating point atomic instructions. May generate more efficient code,
12234       // but may not respect rounding and denormal modes, and may give incorrect
12235       // results for certain memory destinations.
12236       if (RMW->getFunction()
12237               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12238               .getValueAsString() != "true")
12239         return AtomicExpansionKind::CmpXChg;
12240 
12241       if (Subtarget->hasGFX90AInsts()) {
12242         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12243           return AtomicExpansionKind::CmpXChg;
12244 
12245         auto SSID = RMW->getSyncScopeID();
12246         if (SSID == SyncScope::System ||
12247             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12248           return AtomicExpansionKind::CmpXChg;
12249 
12250         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12251       }
12252 
12253       if (AS == AMDGPUAS::FLAT_ADDRESS)
12254         return AtomicExpansionKind::CmpXChg;
12255 
12256       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12257                               : AtomicExpansionKind::CmpXChg;
12258     }
12259 
12260     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12261     // to round-to-nearest-even.
12262     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12263     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12264       if (!Ty->isDoubleTy())
12265         return AtomicExpansionKind::None;
12266 
12267       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12268         return AtomicExpansionKind::None;
12269 
12270       return RMW->getFunction()
12271                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12272                          .getValueAsString() == "true"
12273                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12274                  : AtomicExpansionKind::CmpXChg;
12275     }
12276 
12277     return AtomicExpansionKind::CmpXChg;
12278   }
12279   default:
12280     break;
12281   }
12282 
12283   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12284 }
12285 
12286 const TargetRegisterClass *
12287 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12288   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12289   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12290   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12291     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12292                                                : &AMDGPU::SReg_32RegClass;
12293   if (!TRI->isSGPRClass(RC) && !isDivergent)
12294     return TRI->getEquivalentSGPRClass(RC);
12295   else if (TRI->isSGPRClass(RC) && isDivergent)
12296     return TRI->getEquivalentVGPRClass(RC);
12297 
12298   return RC;
12299 }
12300 
12301 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12302 // uniform values (as produced by the mask results of control flow intrinsics)
12303 // used outside of divergent blocks. The phi users need to also be treated as
12304 // always uniform.
12305 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12306                       unsigned WaveSize) {
12307   // FIXME: We asssume we never cast the mask results of a control flow
12308   // intrinsic.
12309   // Early exit if the type won't be consistent as a compile time hack.
12310   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12311   if (!IT || IT->getBitWidth() != WaveSize)
12312     return false;
12313 
12314   if (!isa<Instruction>(V))
12315     return false;
12316   if (!Visited.insert(V).second)
12317     return false;
12318   bool Result = false;
12319   for (auto U : V->users()) {
12320     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12321       if (V == U->getOperand(1)) {
12322         switch (Intrinsic->getIntrinsicID()) {
12323         default:
12324           Result = false;
12325           break;
12326         case Intrinsic::amdgcn_if_break:
12327         case Intrinsic::amdgcn_if:
12328         case Intrinsic::amdgcn_else:
12329           Result = true;
12330           break;
12331         }
12332       }
12333       if (V == U->getOperand(0)) {
12334         switch (Intrinsic->getIntrinsicID()) {
12335         default:
12336           Result = false;
12337           break;
12338         case Intrinsic::amdgcn_end_cf:
12339         case Intrinsic::amdgcn_loop:
12340           Result = true;
12341           break;
12342         }
12343       }
12344     } else {
12345       Result = hasCFUser(U, Visited, WaveSize);
12346     }
12347     if (Result)
12348       break;
12349   }
12350   return Result;
12351 }
12352 
12353 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12354                                                const Value *V) const {
12355   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12356     if (CI->isInlineAsm()) {
12357       // FIXME: This cannot give a correct answer. This should only trigger in
12358       // the case where inline asm returns mixed SGPR and VGPR results, used
12359       // outside the defining block. We don't have a specific result to
12360       // consider, so this assumes if any value is SGPR, the overall register
12361       // also needs to be SGPR.
12362       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12363       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12364           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12365       for (auto &TC : TargetConstraints) {
12366         if (TC.Type == InlineAsm::isOutput) {
12367           ComputeConstraintToUse(TC, SDValue());
12368           unsigned AssignedReg;
12369           const TargetRegisterClass *RC;
12370           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12371               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12372           if (RC) {
12373             MachineRegisterInfo &MRI = MF.getRegInfo();
12374             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12375               return true;
12376             else if (SIRI->isSGPRClass(RC))
12377               return true;
12378           }
12379         }
12380       }
12381     }
12382   }
12383   SmallPtrSet<const Value *, 16> Visited;
12384   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12385 }
12386 
12387 std::pair<InstructionCost, MVT>
12388 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12389                                           Type *Ty) const {
12390   std::pair<InstructionCost, MVT> Cost =
12391       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12392   auto Size = DL.getTypeSizeInBits(Ty);
12393   // Maximum load or store can handle 8 dwords for scalar and 4 for
12394   // vector ALU. Let's assume anything above 8 dwords is expensive
12395   // even if legal.
12396   if (Size <= 256)
12397     return Cost;
12398 
12399   Cost.first = (Size + 255) / 256;
12400   return Cost;
12401 }
12402