1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/IntrinsicsAMDGPU.h"
33 #include "llvm/IR/IntrinsicsR600.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "si-lower"
40 
41 STATISTIC(NumTailCalls, "Number of tail calls");
42 
43 static cl::opt<bool> DisableLoopAlignment(
44   "amdgpu-disable-loop-alignment",
45   cl::desc("Do not align and prefetch loops"),
46   cl::init(false));
47 
48 static cl::opt<bool> UseDivergentRegisterIndexing(
49   "amdgpu-use-divergent-register-indexing",
50   cl::Hidden,
51   cl::desc("Use indirect register addressing for divergent indexes"),
52   cl::init(false));
53 
54 static bool hasFP32Denormals(const MachineFunction &MF) {
55   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56   return Info->getMode().allFP32Denormals();
57 }
58 
59 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61   return Info->getMode().allFP64FP16Denormals();
62 }
63 
64 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68       return AMDGPU::SGPR0 + Reg;
69     }
70   }
71   llvm_unreachable("Cannot allocate sgpr");
72 }
73 
74 SITargetLowering::SITargetLowering(const TargetMachine &TM,
75                                    const GCNSubtarget &STI)
76     : AMDGPUTargetLowering(TM, STI),
77       Subtarget(&STI) {
78   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80 
81   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83 
84   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85 
86   const SIRegisterInfo *TRI = STI.getRegisterInfo();
87   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
88 
89   addRegisterClass(MVT::f64, V64RegClass);
90   addRegisterClass(MVT::v2f32, V64RegClass);
91 
92   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
93   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
94 
95   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
96   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
97 
98   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
100 
101   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
102   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
103 
104   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
105   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
106 
107   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
108   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
109 
110   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
111   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
112 
113   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
114   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
115 
116   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
117   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
118 
119   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
120   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
121 
122   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
123   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
124 
125   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
126   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
127 
128   if (Subtarget->has16BitInsts()) {
129     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
130     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
131 
132     // Unless there are also VOP3P operations, not operations are really legal.
133     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
134     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
135     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
136     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
137   }
138 
139   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
140   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
141 
142   computeRegisterProperties(Subtarget->getRegisterInfo());
143 
144   // The boolean content concept here is too inflexible. Compares only ever
145   // really produce a 1-bit result. Any copy/extend from these will turn into a
146   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
147   // it's what most targets use.
148   setBooleanContents(ZeroOrOneBooleanContent);
149   setBooleanVectorContents(ZeroOrOneBooleanContent);
150 
151   // We need to custom lower vector stores from local memory
152   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
153   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
154   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::i1, Custom);
161   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
162 
163   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
164   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
165   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
166   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
171   setOperationAction(ISD::STORE, MVT::i1, Custom);
172   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
173 
174   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
175   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
176   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
177   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
178   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
179   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
180   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
181   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
182   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
183   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
184   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
185   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
186   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
187   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
188   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
189   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
190 
191   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
192   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
193   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
194   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
195   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
196   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
197   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
198 
199   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
200   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
201 
202   setOperationAction(ISD::SELECT, MVT::i1, Promote);
203   setOperationAction(ISD::SELECT, MVT::i64, Custom);
204   setOperationAction(ISD::SELECT, MVT::f64, Promote);
205   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
206 
207   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
208   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
209   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
210   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
212 
213   setOperationAction(ISD::SETCC, MVT::i1, Promote);
214   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
215   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
216   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
217 
218   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
219   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
220   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
221   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
222   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
234 
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
236   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
243 
244   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
246   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
247   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
248   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
250 
251   setOperationAction(ISD::UADDO, MVT::i32, Legal);
252   setOperationAction(ISD::USUBO, MVT::i32, Legal);
253 
254   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
255   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
256 
257   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
258   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
259   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
260 
261 #if 0
262   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
263   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
264 #endif
265 
266   // We only support LOAD/STORE and vector manipulation ops for vectors
267   // with > 4 elements.
268   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
269                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
270                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
271                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
272                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
273     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
274       switch (Op) {
275       case ISD::LOAD:
276       case ISD::STORE:
277       case ISD::BUILD_VECTOR:
278       case ISD::BITCAST:
279       case ISD::EXTRACT_VECTOR_ELT:
280       case ISD::INSERT_VECTOR_ELT:
281       case ISD::EXTRACT_SUBVECTOR:
282       case ISD::SCALAR_TO_VECTOR:
283         break;
284       case ISD::INSERT_SUBVECTOR:
285       case ISD::CONCAT_VECTORS:
286         setOperationAction(Op, VT, Custom);
287         break;
288       default:
289         setOperationAction(Op, VT, Expand);
290         break;
291       }
292     }
293   }
294 
295   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
296 
297   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
298   // is expanded to avoid having two separate loops in case the index is a VGPR.
299 
300   // Most operations are naturally 32-bit vector operations. We only support
301   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
302   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
303     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
305 
306     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
307     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
313     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
314   }
315 
316   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
317     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
319 
320     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
321     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
322 
323     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
325 
326     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
328   }
329 
330   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
331     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
333 
334     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
335     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
342   }
343 
344   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
345     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
346     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
347 
348     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
349     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
356   }
357 
358   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
359     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
360     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
361 
362     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
363     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
370   }
371 
372   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
373   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
374   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
376 
377   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
378   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
379 
380   // Avoid stack access for these.
381   // TODO: Generalize to more vector types.
382   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
383   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
384   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
385   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
386 
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
388   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
389   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
393 
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
397   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
398 
399   // Deal with vec3 vector operations when widened to vec4.
400   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
401   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
402   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
404 
405   // Deal with vec5/6/7 vector operations when widened to vec8.
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
408   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
414 
415   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
416   // and output demarshalling
417   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
418   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
419 
420   // We can't return success/failure, only the old value,
421   // let LLVM add the comparison
422   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
423   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
424 
425   if (Subtarget->hasFlatAddressSpace()) {
426     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
427     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
428   }
429 
430   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
431   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
432 
433   // FIXME: This should be narrowed to i32, but that only happens if i64 is
434   // illegal.
435   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
436   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
437   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
438 
439   // On SI this is s_memtime and s_memrealtime on VI.
440   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
441   setOperationAction(ISD::TRAP, MVT::Other, Custom);
442   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
443 
444   if (Subtarget->has16BitInsts()) {
445     setOperationAction(ISD::FPOW, MVT::f16, Promote);
446     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
447     setOperationAction(ISD::FLOG, MVT::f16, Custom);
448     setOperationAction(ISD::FEXP, MVT::f16, Custom);
449     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
450   }
451 
452   if (Subtarget->hasMadMacF32Insts())
453     setOperationAction(ISD::FMAD, MVT::f32, Legal);
454 
455   if (!Subtarget->hasBFI()) {
456     // fcopysign can be done in a single instruction with BFI.
457     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
458     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
459   }
460 
461   if (!Subtarget->hasBCNT(32))
462     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
463 
464   if (!Subtarget->hasBCNT(64))
465     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
466 
467   if (Subtarget->hasFFBH()) {
468     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
469     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
470   }
471 
472   if (Subtarget->hasFFBL()) {
473     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
474     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
475   }
476 
477   // We only really have 32-bit BFE instructions (and 16-bit on VI).
478   //
479   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
480   // effort to match them now. We want this to be false for i64 cases when the
481   // extraction isn't restricted to the upper or lower half. Ideally we would
482   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
483   // span the midpoint are probably relatively rare, so don't worry about them
484   // for now.
485   if (Subtarget->hasBFE())
486     setHasExtractBitsInsn(true);
487 
488   // Clamp modifier on add/sub
489   if (Subtarget->hasIntClamp()) {
490     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
491     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
492   }
493 
494   if (Subtarget->hasAddNoCarry()) {
495     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
496     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
497     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
498     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
499   }
500 
501   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
502   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
503   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
504   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
505 
506 
507   // These are really only legal for ieee_mode functions. We should be avoiding
508   // them for functions that don't have ieee_mode enabled, so just say they are
509   // legal.
510   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
511   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
512   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
513   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
514 
515 
516   if (Subtarget->haveRoundOpsF64()) {
517     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
518     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
519     setOperationAction(ISD::FRINT, MVT::f64, Legal);
520   } else {
521     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
522     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
523     setOperationAction(ISD::FRINT, MVT::f64, Custom);
524     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
525   }
526 
527   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
528 
529   setOperationAction(ISD::FSIN, MVT::f32, Custom);
530   setOperationAction(ISD::FCOS, MVT::f32, Custom);
531   setOperationAction(ISD::FDIV, MVT::f32, Custom);
532   setOperationAction(ISD::FDIV, MVT::f64, Custom);
533 
534   if (Subtarget->has16BitInsts()) {
535     setOperationAction(ISD::Constant, MVT::i16, Legal);
536 
537     setOperationAction(ISD::SMIN, MVT::i16, Legal);
538     setOperationAction(ISD::SMAX, MVT::i16, Legal);
539 
540     setOperationAction(ISD::UMIN, MVT::i16, Legal);
541     setOperationAction(ISD::UMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
544     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
545 
546     setOperationAction(ISD::ROTR, MVT::i16, Expand);
547     setOperationAction(ISD::ROTL, MVT::i16, Expand);
548 
549     setOperationAction(ISD::SDIV, MVT::i16, Promote);
550     setOperationAction(ISD::UDIV, MVT::i16, Promote);
551     setOperationAction(ISD::SREM, MVT::i16, Promote);
552     setOperationAction(ISD::UREM, MVT::i16, Promote);
553     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
554     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
555 
556     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
557 
558     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
559     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
560     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
561     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
562     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
563 
564     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
565 
566     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
567 
568     setOperationAction(ISD::LOAD, MVT::i16, Custom);
569 
570     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
571 
572     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
573     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
574     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
575     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
576 
577     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
578     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
579 
580     // F16 - Constant Actions.
581     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
582 
583     // F16 - Load/Store Actions.
584     setOperationAction(ISD::LOAD, MVT::f16, Promote);
585     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
586     setOperationAction(ISD::STORE, MVT::f16, Promote);
587     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
588 
589     // F16 - VOP1 Actions.
590     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
591     setOperationAction(ISD::FCOS, MVT::f16, Custom);
592     setOperationAction(ISD::FSIN, MVT::f16, Custom);
593 
594     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
595     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
596 
597     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
598     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
599     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
600     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
601     setOperationAction(ISD::FROUND, MVT::f16, Custom);
602 
603     // F16 - VOP2 Actions.
604     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
605     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
606 
607     setOperationAction(ISD::FDIV, MVT::f16, Custom);
608 
609     // F16 - VOP3 Actions.
610     setOperationAction(ISD::FMA, MVT::f16, Legal);
611     if (STI.hasMadF16())
612       setOperationAction(ISD::FMAD, MVT::f16, Legal);
613 
614     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
615       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
616         switch (Op) {
617         case ISD::LOAD:
618         case ISD::STORE:
619         case ISD::BUILD_VECTOR:
620         case ISD::BITCAST:
621         case ISD::EXTRACT_VECTOR_ELT:
622         case ISD::INSERT_VECTOR_ELT:
623         case ISD::INSERT_SUBVECTOR:
624         case ISD::EXTRACT_SUBVECTOR:
625         case ISD::SCALAR_TO_VECTOR:
626           break;
627         case ISD::CONCAT_VECTORS:
628           setOperationAction(Op, VT, Custom);
629           break;
630         default:
631           setOperationAction(Op, VT, Expand);
632           break;
633         }
634       }
635     }
636 
637     // v_perm_b32 can handle either of these.
638     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
639     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
640     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
641 
642     // XXX - Do these do anything? Vector constants turn into build_vector.
643     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
644     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
645 
646     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
647     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
650     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
651     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
653 
654     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
655     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
656     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
657     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
658 
659     setOperationAction(ISD::AND, MVT::v2i16, Promote);
660     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
661     setOperationAction(ISD::OR, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
665 
666     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
667     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
668     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
669     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
670 
671     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
672     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
673     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
674     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
675 
676     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
677     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
678     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
679     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
680 
681     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
682     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
683     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
684 
685     if (!Subtarget->hasVOP3PInsts()) {
686       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
687       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
688     }
689 
690     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
691     // This isn't really legal, but this avoids the legalizer unrolling it (and
692     // allows matching fneg (fabs x) patterns)
693     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
694 
695     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
696     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
697     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
698     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
699 
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
701     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
702 
703     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
704     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
705   }
706 
707   if (Subtarget->hasVOP3PInsts()) {
708     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
709     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
710     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
711     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
712     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
713     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
714     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
715     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
716     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
717     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
718 
719     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
720     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
721     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
722     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
723 
724     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
725     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
726     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
727 
728     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
732 
733     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
734     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
735 
736     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
737     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
738 
739     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
740     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
741     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
742     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
743     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
744     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
745 
746     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
747     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
748     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
749     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
750 
751     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
752     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
753     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
754     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
755 
756     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
757     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
758     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
759 
760     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
761     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
762 
763     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
764     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
765     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
766 
767     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
768     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
769     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
770 
771     if (Subtarget->hasPackedFP32Ops()) {
772       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
773       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
774       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
775       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
776 
777       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
778         setOperationAction(ISD::FADD, VT, Custom);
779         setOperationAction(ISD::FMUL, VT, Custom);
780         setOperationAction(ISD::FMA, VT, Custom);
781       }
782     }
783   }
784 
785   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
786   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
787 
788   if (Subtarget->has16BitInsts()) {
789     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
790     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
791     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
792     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
793   } else {
794     // Legalization hack.
795     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
796     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
797 
798     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
799     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
800   }
801 
802   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
803     setOperationAction(ISD::SELECT, VT, Custom);
804   }
805 
806   setOperationAction(ISD::SMULO, MVT::i64, Custom);
807   setOperationAction(ISD::UMULO, MVT::i64, Custom);
808 
809   if (Subtarget->hasMad64_32()) {
810     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
811     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
812   }
813 
814   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
816   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
817   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
819   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
820   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
821 
822   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
823   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
824   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
825   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
831   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
832   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
833 
834   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
835   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
836   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
837   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
842   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
843   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
844 
845   setTargetDAGCombine(ISD::ADD);
846   setTargetDAGCombine(ISD::ADDCARRY);
847   setTargetDAGCombine(ISD::SUB);
848   setTargetDAGCombine(ISD::SUBCARRY);
849   setTargetDAGCombine(ISD::FADD);
850   setTargetDAGCombine(ISD::FSUB);
851   setTargetDAGCombine(ISD::FMINNUM);
852   setTargetDAGCombine(ISD::FMAXNUM);
853   setTargetDAGCombine(ISD::FMINNUM_IEEE);
854   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
855   setTargetDAGCombine(ISD::FMA);
856   setTargetDAGCombine(ISD::SMIN);
857   setTargetDAGCombine(ISD::SMAX);
858   setTargetDAGCombine(ISD::UMIN);
859   setTargetDAGCombine(ISD::UMAX);
860   setTargetDAGCombine(ISD::SETCC);
861   setTargetDAGCombine(ISD::AND);
862   setTargetDAGCombine(ISD::OR);
863   setTargetDAGCombine(ISD::XOR);
864   setTargetDAGCombine(ISD::SINT_TO_FP);
865   setTargetDAGCombine(ISD::UINT_TO_FP);
866   setTargetDAGCombine(ISD::FCANONICALIZE);
867   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
868   setTargetDAGCombine(ISD::ZERO_EXTEND);
869   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
870   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
871   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
872 
873   // All memory operations. Some folding on the pointer operand is done to help
874   // matching the constant offsets in the addressing modes.
875   setTargetDAGCombine(ISD::LOAD);
876   setTargetDAGCombine(ISD::STORE);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD);
878   setTargetDAGCombine(ISD::ATOMIC_STORE);
879   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
880   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
881   setTargetDAGCombine(ISD::ATOMIC_SWAP);
882   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
883   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
884   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
885   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
891   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
892   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
893   setTargetDAGCombine(ISD::INTRINSIC_VOID);
894   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
895 
896   // FIXME: In other contexts we pretend this is a per-function property.
897   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
898 
899   setSchedulingPreference(Sched::RegPressure);
900 }
901 
902 const GCNSubtarget *SITargetLowering::getSubtarget() const {
903   return Subtarget;
904 }
905 
906 //===----------------------------------------------------------------------===//
907 // TargetLowering queries
908 //===----------------------------------------------------------------------===//
909 
910 // v_mad_mix* support a conversion from f16 to f32.
911 //
912 // There is only one special case when denormals are enabled we don't currently,
913 // where this is OK to use.
914 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
915                                        EVT DestVT, EVT SrcVT) const {
916   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
917           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
918     DestVT.getScalarType() == MVT::f32 &&
919     SrcVT.getScalarType() == MVT::f16 &&
920     // TODO: This probably only requires no input flushing?
921     !hasFP32Denormals(DAG.getMachineFunction());
922 }
923 
924 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
925                                        LLT DestTy, LLT SrcTy) const {
926   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
927           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
928          DestTy.getScalarSizeInBits() == 32 &&
929          SrcTy.getScalarSizeInBits() == 16 &&
930          // TODO: This probably only requires no input flushing?
931          !hasFP32Denormals(*MI.getMF());
932 }
933 
934 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
935   // SI has some legal vector types, but no legal vector operations. Say no
936   // shuffles are legal in order to prefer scalarizing some vector operations.
937   return false;
938 }
939 
940 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
941                                                     CallingConv::ID CC,
942                                                     EVT VT) const {
943   if (CC == CallingConv::AMDGPU_KERNEL)
944     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
945 
946   if (VT.isVector()) {
947     EVT ScalarVT = VT.getScalarType();
948     unsigned Size = ScalarVT.getSizeInBits();
949     if (Size == 16) {
950       if (Subtarget->has16BitInsts())
951         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
952       return VT.isInteger() ? MVT::i32 : MVT::f32;
953     }
954 
955     if (Size < 16)
956       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
957     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
958   }
959 
960   if (VT.getSizeInBits() > 32)
961     return MVT::i32;
962 
963   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
964 }
965 
966 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
967                                                          CallingConv::ID CC,
968                                                          EVT VT) const {
969   if (CC == CallingConv::AMDGPU_KERNEL)
970     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
971 
972   if (VT.isVector()) {
973     unsigned NumElts = VT.getVectorNumElements();
974     EVT ScalarVT = VT.getScalarType();
975     unsigned Size = ScalarVT.getSizeInBits();
976 
977     // FIXME: Should probably promote 8-bit vectors to i16.
978     if (Size == 16 && Subtarget->has16BitInsts())
979       return (NumElts + 1) / 2;
980 
981     if (Size <= 32)
982       return NumElts;
983 
984     if (Size > 32)
985       return NumElts * ((Size + 31) / 32);
986   } else if (VT.getSizeInBits() > 32)
987     return (VT.getSizeInBits() + 31) / 32;
988 
989   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
990 }
991 
992 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
993   LLVMContext &Context, CallingConv::ID CC,
994   EVT VT, EVT &IntermediateVT,
995   unsigned &NumIntermediates, MVT &RegisterVT) const {
996   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
997     unsigned NumElts = VT.getVectorNumElements();
998     EVT ScalarVT = VT.getScalarType();
999     unsigned Size = ScalarVT.getSizeInBits();
1000     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1001     // support, but unless we can properly handle 3-vectors, it will be still be
1002     // inconsistent.
1003     if (Size == 16 && Subtarget->has16BitInsts()) {
1004       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1005       IntermediateVT = RegisterVT;
1006       NumIntermediates = (NumElts + 1) / 2;
1007       return NumIntermediates;
1008     }
1009 
1010     if (Size == 32) {
1011       RegisterVT = ScalarVT.getSimpleVT();
1012       IntermediateVT = RegisterVT;
1013       NumIntermediates = NumElts;
1014       return NumIntermediates;
1015     }
1016 
1017     if (Size < 16 && Subtarget->has16BitInsts()) {
1018       // FIXME: Should probably form v2i16 pieces
1019       RegisterVT = MVT::i16;
1020       IntermediateVT = ScalarVT;
1021       NumIntermediates = NumElts;
1022       return NumIntermediates;
1023     }
1024 
1025 
1026     if (Size != 16 && Size <= 32) {
1027       RegisterVT = MVT::i32;
1028       IntermediateVT = ScalarVT;
1029       NumIntermediates = NumElts;
1030       return NumIntermediates;
1031     }
1032 
1033     if (Size > 32) {
1034       RegisterVT = MVT::i32;
1035       IntermediateVT = RegisterVT;
1036       NumIntermediates = NumElts * ((Size + 31) / 32);
1037       return NumIntermediates;
1038     }
1039   }
1040 
1041   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1042     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1043 }
1044 
1045 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1046   assert(DMaskLanes != 0);
1047 
1048   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1049     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1050     return EVT::getVectorVT(Ty->getContext(),
1051                             EVT::getEVT(VT->getElementType()),
1052                             NumElts);
1053   }
1054 
1055   return EVT::getEVT(Ty);
1056 }
1057 
1058 // Peek through TFE struct returns to only use the data size.
1059 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1060   auto *ST = dyn_cast<StructType>(Ty);
1061   if (!ST)
1062     return memVTFromImageData(Ty, DMaskLanes);
1063 
1064   // Some intrinsics return an aggregate type - special case to work out the
1065   // correct memVT.
1066   //
1067   // Only limited forms of aggregate type currently expected.
1068   if (ST->getNumContainedTypes() != 2 ||
1069       !ST->getContainedType(1)->isIntegerTy(32))
1070     return EVT();
1071   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1072 }
1073 
1074 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1075                                           const CallInst &CI,
1076                                           MachineFunction &MF,
1077                                           unsigned IntrID) const {
1078   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1079           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1080     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1081                                                   (Intrinsic::ID)IntrID);
1082     if (Attr.hasFnAttr(Attribute::ReadNone))
1083       return false;
1084 
1085     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1086 
1087     if (RsrcIntr->IsImage) {
1088       Info.ptrVal =
1089           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1090       Info.align.reset();
1091     } else {
1092       Info.ptrVal =
1093           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1094     }
1095 
1096     Info.flags = MachineMemOperand::MODereferenceable;
1097     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1098       unsigned DMaskLanes = 4;
1099 
1100       if (RsrcIntr->IsImage) {
1101         const AMDGPU::ImageDimIntrinsicInfo *Intr
1102           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1103         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1104           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1105 
1106         if (!BaseOpcode->Gather4) {
1107           // If this isn't a gather, we may have excess loaded elements in the
1108           // IR type. Check the dmask for the real number of elements loaded.
1109           unsigned DMask
1110             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1111           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1112         }
1113 
1114         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1115       } else
1116         Info.memVT = EVT::getEVT(CI.getType());
1117 
1118       // FIXME: What does alignment mean for an image?
1119       Info.opc = ISD::INTRINSIC_W_CHAIN;
1120       Info.flags |= MachineMemOperand::MOLoad;
1121     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1122       Info.opc = ISD::INTRINSIC_VOID;
1123 
1124       Type *DataTy = CI.getArgOperand(0)->getType();
1125       if (RsrcIntr->IsImage) {
1126         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1127         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1128         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1129       } else
1130         Info.memVT = EVT::getEVT(DataTy);
1131 
1132       Info.flags |= MachineMemOperand::MOStore;
1133     } else {
1134       // Atomic
1135       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1136                                             ISD::INTRINSIC_W_CHAIN;
1137       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1138       Info.flags = MachineMemOperand::MOLoad |
1139                    MachineMemOperand::MOStore |
1140                    MachineMemOperand::MODereferenceable;
1141 
1142       // XXX - Should this be volatile without known ordering?
1143       Info.flags |= MachineMemOperand::MOVolatile;
1144     }
1145     return true;
1146   }
1147 
1148   switch (IntrID) {
1149   case Intrinsic::amdgcn_atomic_inc:
1150   case Intrinsic::amdgcn_atomic_dec:
1151   case Intrinsic::amdgcn_ds_ordered_add:
1152   case Intrinsic::amdgcn_ds_ordered_swap:
1153   case Intrinsic::amdgcn_ds_fadd:
1154   case Intrinsic::amdgcn_ds_fmin:
1155   case Intrinsic::amdgcn_ds_fmax: {
1156     Info.opc = ISD::INTRINSIC_W_CHAIN;
1157     Info.memVT = MVT::getVT(CI.getType());
1158     Info.ptrVal = CI.getOperand(0);
1159     Info.align.reset();
1160     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1161 
1162     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1163     if (!Vol->isZero())
1164       Info.flags |= MachineMemOperand::MOVolatile;
1165 
1166     return true;
1167   }
1168   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1169     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1170 
1171     Info.opc = ISD::INTRINSIC_W_CHAIN;
1172     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1173     Info.ptrVal =
1174         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1175     Info.align.reset();
1176     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1177 
1178     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1179     if (!Vol || !Vol->isZero())
1180       Info.flags |= MachineMemOperand::MOVolatile;
1181 
1182     return true;
1183   }
1184   case Intrinsic::amdgcn_ds_append:
1185   case Intrinsic::amdgcn_ds_consume: {
1186     Info.opc = ISD::INTRINSIC_W_CHAIN;
1187     Info.memVT = MVT::getVT(CI.getType());
1188     Info.ptrVal = CI.getOperand(0);
1189     Info.align.reset();
1190     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1191 
1192     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1193     if (!Vol->isZero())
1194       Info.flags |= MachineMemOperand::MOVolatile;
1195 
1196     return true;
1197   }
1198   case Intrinsic::amdgcn_global_atomic_csub: {
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType());
1201     Info.ptrVal = CI.getOperand(0);
1202     Info.align.reset();
1203     Info.flags = MachineMemOperand::MOLoad |
1204                  MachineMemOperand::MOStore |
1205                  MachineMemOperand::MOVolatile;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1209     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1210     Info.opc = ISD::INTRINSIC_W_CHAIN;
1211     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1212     Info.ptrVal =
1213         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1214     Info.align.reset();
1215     Info.flags = MachineMemOperand::MOLoad |
1216                  MachineMemOperand::MODereferenceable;
1217     return true;
1218   }
1219   case Intrinsic::amdgcn_global_atomic_fadd:
1220   case Intrinsic::amdgcn_global_atomic_fmin:
1221   case Intrinsic::amdgcn_global_atomic_fmax:
1222   case Intrinsic::amdgcn_flat_atomic_fadd:
1223   case Intrinsic::amdgcn_flat_atomic_fmin:
1224   case Intrinsic::amdgcn_flat_atomic_fmax: {
1225     Info.opc = ISD::INTRINSIC_W_CHAIN;
1226     Info.memVT = MVT::getVT(CI.getType());
1227     Info.ptrVal = CI.getOperand(0);
1228     Info.align.reset();
1229     Info.flags = MachineMemOperand::MOLoad |
1230                  MachineMemOperand::MOStore |
1231                  MachineMemOperand::MODereferenceable |
1232                  MachineMemOperand::MOVolatile;
1233     return true;
1234   }
1235   case Intrinsic::amdgcn_ds_gws_init:
1236   case Intrinsic::amdgcn_ds_gws_barrier:
1237   case Intrinsic::amdgcn_ds_gws_sema_v:
1238   case Intrinsic::amdgcn_ds_gws_sema_br:
1239   case Intrinsic::amdgcn_ds_gws_sema_p:
1240   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1241     Info.opc = ISD::INTRINSIC_VOID;
1242 
1243     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1244     Info.ptrVal =
1245         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1246 
1247     // This is an abstract access, but we need to specify a type and size.
1248     Info.memVT = MVT::i32;
1249     Info.size = 4;
1250     Info.align = Align(4);
1251 
1252     Info.flags = MachineMemOperand::MOStore;
1253     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1254       Info.flags = MachineMemOperand::MOLoad;
1255     return true;
1256   }
1257   default:
1258     return false;
1259   }
1260 }
1261 
1262 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1263                                             SmallVectorImpl<Value*> &Ops,
1264                                             Type *&AccessTy) const {
1265   switch (II->getIntrinsicID()) {
1266   case Intrinsic::amdgcn_atomic_inc:
1267   case Intrinsic::amdgcn_atomic_dec:
1268   case Intrinsic::amdgcn_ds_ordered_add:
1269   case Intrinsic::amdgcn_ds_ordered_swap:
1270   case Intrinsic::amdgcn_ds_append:
1271   case Intrinsic::amdgcn_ds_consume:
1272   case Intrinsic::amdgcn_ds_fadd:
1273   case Intrinsic::amdgcn_ds_fmin:
1274   case Intrinsic::amdgcn_ds_fmax:
1275   case Intrinsic::amdgcn_global_atomic_fadd:
1276   case Intrinsic::amdgcn_flat_atomic_fadd:
1277   case Intrinsic::amdgcn_flat_atomic_fmin:
1278   case Intrinsic::amdgcn_flat_atomic_fmax:
1279   case Intrinsic::amdgcn_global_atomic_csub: {
1280     Value *Ptr = II->getArgOperand(0);
1281     AccessTy = II->getType();
1282     Ops.push_back(Ptr);
1283     return true;
1284   }
1285   default:
1286     return false;
1287   }
1288 }
1289 
1290 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1291   if (!Subtarget->hasFlatInstOffsets()) {
1292     // Flat instructions do not have offsets, and only have the register
1293     // address.
1294     return AM.BaseOffs == 0 && AM.Scale == 0;
1295   }
1296 
1297   return AM.Scale == 0 &&
1298          (AM.BaseOffs == 0 ||
1299           Subtarget->getInstrInfo()->isLegalFLATOffset(
1300               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1301 }
1302 
1303 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1304   if (Subtarget->hasFlatGlobalInsts())
1305     return AM.Scale == 0 &&
1306            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1307                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1308                                     SIInstrFlags::FlatGlobal));
1309 
1310   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1311       // Assume the we will use FLAT for all global memory accesses
1312       // on VI.
1313       // FIXME: This assumption is currently wrong.  On VI we still use
1314       // MUBUF instructions for the r + i addressing mode.  As currently
1315       // implemented, the MUBUF instructions only work on buffer < 4GB.
1316       // It may be possible to support > 4GB buffers with MUBUF instructions,
1317       // by setting the stride value in the resource descriptor which would
1318       // increase the size limit to (stride * 4GB).  However, this is risky,
1319       // because it has never been validated.
1320     return isLegalFlatAddressingMode(AM);
1321   }
1322 
1323   return isLegalMUBUFAddressingMode(AM);
1324 }
1325 
1326 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1327   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1328   // additionally can do r + r + i with addr64. 32-bit has more addressing
1329   // mode options. Depending on the resource constant, it can also do
1330   // (i64 r0) + (i32 r1) * (i14 i).
1331   //
1332   // Private arrays end up using a scratch buffer most of the time, so also
1333   // assume those use MUBUF instructions. Scratch loads / stores are currently
1334   // implemented as mubuf instructions with offen bit set, so slightly
1335   // different than the normal addr64.
1336   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1337     return false;
1338 
1339   // FIXME: Since we can split immediate into soffset and immediate offset,
1340   // would it make sense to allow any immediate?
1341 
1342   switch (AM.Scale) {
1343   case 0: // r + i or just i, depending on HasBaseReg.
1344     return true;
1345   case 1:
1346     return true; // We have r + r or r + i.
1347   case 2:
1348     if (AM.HasBaseReg) {
1349       // Reject 2 * r + r.
1350       return false;
1351     }
1352 
1353     // Allow 2 * r as r + r
1354     // Or  2 * r + i is allowed as r + r + i.
1355     return true;
1356   default: // Don't allow n * r
1357     return false;
1358   }
1359 }
1360 
1361 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1362                                              const AddrMode &AM, Type *Ty,
1363                                              unsigned AS, Instruction *I) const {
1364   // No global is ever allowed as a base.
1365   if (AM.BaseGV)
1366     return false;
1367 
1368   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1369     return isLegalGlobalAddressingMode(AM);
1370 
1371   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1372       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1373       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1374     // If the offset isn't a multiple of 4, it probably isn't going to be
1375     // correctly aligned.
1376     // FIXME: Can we get the real alignment here?
1377     if (AM.BaseOffs % 4 != 0)
1378       return isLegalMUBUFAddressingMode(AM);
1379 
1380     // There are no SMRD extloads, so if we have to do a small type access we
1381     // will use a MUBUF load.
1382     // FIXME?: We also need to do this if unaligned, but we don't know the
1383     // alignment here.
1384     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1385       return isLegalGlobalAddressingMode(AM);
1386 
1387     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1388       // SMRD instructions have an 8-bit, dword offset on SI.
1389       if (!isUInt<8>(AM.BaseOffs / 4))
1390         return false;
1391     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1392       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1393       // in 8-bits, it can use a smaller encoding.
1394       if (!isUInt<32>(AM.BaseOffs / 4))
1395         return false;
1396     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1397       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1398       if (!isUInt<20>(AM.BaseOffs))
1399         return false;
1400     } else
1401       llvm_unreachable("unhandled generation");
1402 
1403     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1404       return true;
1405 
1406     if (AM.Scale == 1 && AM.HasBaseReg)
1407       return true;
1408 
1409     return false;
1410 
1411   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1412     return isLegalMUBUFAddressingMode(AM);
1413   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1414              AS == AMDGPUAS::REGION_ADDRESS) {
1415     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1416     // field.
1417     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1418     // an 8-bit dword offset but we don't know the alignment here.
1419     if (!isUInt<16>(AM.BaseOffs))
1420       return false;
1421 
1422     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1423       return true;
1424 
1425     if (AM.Scale == 1 && AM.HasBaseReg)
1426       return true;
1427 
1428     return false;
1429   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1430              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1431     // For an unknown address space, this usually means that this is for some
1432     // reason being used for pure arithmetic, and not based on some addressing
1433     // computation. We don't have instructions that compute pointers with any
1434     // addressing modes, so treat them as having no offset like flat
1435     // instructions.
1436     return isLegalFlatAddressingMode(AM);
1437   }
1438 
1439   // Assume a user alias of global for unknown address spaces.
1440   return isLegalGlobalAddressingMode(AM);
1441 }
1442 
1443 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1444                                         const MachineFunction &MF) const {
1445   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1446     return (MemVT.getSizeInBits() <= 4 * 32);
1447   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1448     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1449     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1450   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1451     return (MemVT.getSizeInBits() <= 2 * 32);
1452   }
1453   return true;
1454 }
1455 
1456 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1457     unsigned Size, unsigned AddrSpace, Align Alignment,
1458     MachineMemOperand::Flags Flags, bool *IsFast) const {
1459   if (IsFast)
1460     *IsFast = false;
1461 
1462   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1463       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1464     // Check if alignment requirements for ds_read/write instructions are
1465     // disabled.
1466     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1467         !Subtarget->hasLDSMisalignedBug()) {
1468       if (IsFast)
1469         *IsFast = Alignment != Align(2);
1470       return true;
1471     }
1472 
1473     // Either, the alignment requirements are "enabled", or there is an
1474     // unaligned LDS access related hardware bug though alignment requirements
1475     // are "disabled". In either case, we need to check for proper alignment
1476     // requirements.
1477     //
1478     if (Size == 64) {
1479       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1480       // can do a 4 byte aligned, 8 byte access in a single operation using
1481       // ds_read2/write2_b32 with adjacent offsets.
1482       bool AlignedBy4 = Alignment >= Align(4);
1483       if (IsFast)
1484         *IsFast = AlignedBy4;
1485 
1486       return AlignedBy4;
1487     }
1488     if (Size == 96) {
1489       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1490       // gfx8 and older.
1491       bool AlignedBy16 = Alignment >= Align(16);
1492       if (IsFast)
1493         *IsFast = AlignedBy16;
1494 
1495       return AlignedBy16;
1496     }
1497     if (Size == 128) {
1498       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1499       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1500       // single operation using ds_read2/write2_b64.
1501       bool AlignedBy8 = Alignment >= Align(8);
1502       if (IsFast)
1503         *IsFast = AlignedBy8;
1504 
1505       return AlignedBy8;
1506     }
1507   }
1508 
1509   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1510     bool AlignedBy4 = Alignment >= Align(4);
1511     if (IsFast)
1512       *IsFast = AlignedBy4;
1513 
1514     return AlignedBy4 ||
1515            Subtarget->enableFlatScratch() ||
1516            Subtarget->hasUnalignedScratchAccess();
1517   }
1518 
1519   // FIXME: We have to be conservative here and assume that flat operations
1520   // will access scratch.  If we had access to the IR function, then we
1521   // could determine if any private memory was used in the function.
1522   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1523       !Subtarget->hasUnalignedScratchAccess()) {
1524     bool AlignedBy4 = Alignment >= Align(4);
1525     if (IsFast)
1526       *IsFast = AlignedBy4;
1527 
1528     return AlignedBy4;
1529   }
1530 
1531   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1532       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1533         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1534     // If we have an uniform constant load, it still requires using a slow
1535     // buffer instruction if unaligned.
1536     if (IsFast) {
1537       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1538       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1539       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1540                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1541         Alignment >= Align(4) : Alignment != Align(2);
1542     }
1543 
1544     return true;
1545   }
1546 
1547   // Smaller than dword value must be aligned.
1548   if (Size < 32)
1549     return false;
1550 
1551   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1552   // byte-address are ignored, thus forcing Dword alignment.
1553   // This applies to private, global, and constant memory.
1554   if (IsFast)
1555     *IsFast = true;
1556 
1557   return Size >= 32 && Alignment >= Align(4);
1558 }
1559 
1560 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1561     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1562     bool *IsFast) const {
1563   if (IsFast)
1564     *IsFast = false;
1565 
1566   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1567   // which isn't a simple VT.
1568   // Until MVT is extended to handle this, simply check for the size and
1569   // rely on the condition below: allow accesses if the size is a multiple of 4.
1570   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1571                            VT.getStoreSize() > 16)) {
1572     return false;
1573   }
1574 
1575   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1576                                             Alignment, Flags, IsFast);
1577 }
1578 
1579 EVT SITargetLowering::getOptimalMemOpType(
1580     const MemOp &Op, const AttributeList &FuncAttributes) const {
1581   // FIXME: Should account for address space here.
1582 
1583   // The default fallback uses the private pointer size as a guess for a type to
1584   // use. Make sure we switch these to 64-bit accesses.
1585 
1586   if (Op.size() >= 16 &&
1587       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1588     return MVT::v4i32;
1589 
1590   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1591     return MVT::v2i32;
1592 
1593   // Use the default.
1594   return MVT::Other;
1595 }
1596 
1597 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1598   const MemSDNode *MemNode = cast<MemSDNode>(N);
1599   const Value *Ptr = MemNode->getMemOperand()->getValue();
1600   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1601   return I && I->getMetadata("amdgpu.noclobber");
1602 }
1603 
1604 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1605   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1606          AS == AMDGPUAS::PRIVATE_ADDRESS;
1607 }
1608 
1609 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1610                                            unsigned DestAS) const {
1611   // Flat -> private/local is a simple truncate.
1612   // Flat -> global is no-op
1613   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1614     return true;
1615 
1616   const GCNTargetMachine &TM =
1617       static_cast<const GCNTargetMachine &>(getTargetMachine());
1618   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1619 }
1620 
1621 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1622   const MemSDNode *MemNode = cast<MemSDNode>(N);
1623 
1624   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1625 }
1626 
1627 TargetLoweringBase::LegalizeTypeAction
1628 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1629   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1630       VT.getScalarType().bitsLE(MVT::i16))
1631     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1632   return TargetLoweringBase::getPreferredVectorAction(VT);
1633 }
1634 
1635 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1636                                                          Type *Ty) const {
1637   // FIXME: Could be smarter if called for vector constants.
1638   return true;
1639 }
1640 
1641 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1642   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1643     switch (Op) {
1644     case ISD::LOAD:
1645     case ISD::STORE:
1646 
1647     // These operations are done with 32-bit instructions anyway.
1648     case ISD::AND:
1649     case ISD::OR:
1650     case ISD::XOR:
1651     case ISD::SELECT:
1652       // TODO: Extensions?
1653       return true;
1654     default:
1655       return false;
1656     }
1657   }
1658 
1659   // SimplifySetCC uses this function to determine whether or not it should
1660   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1661   if (VT == MVT::i1 && Op == ISD::SETCC)
1662     return false;
1663 
1664   return TargetLowering::isTypeDesirableForOp(Op, VT);
1665 }
1666 
1667 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1668                                                    const SDLoc &SL,
1669                                                    SDValue Chain,
1670                                                    uint64_t Offset) const {
1671   const DataLayout &DL = DAG.getDataLayout();
1672   MachineFunction &MF = DAG.getMachineFunction();
1673   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1674 
1675   const ArgDescriptor *InputPtrReg;
1676   const TargetRegisterClass *RC;
1677   LLT ArgTy;
1678   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1679 
1680   std::tie(InputPtrReg, RC, ArgTy) =
1681       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1682 
1683   // We may not have the kernarg segment argument if we have no kernel
1684   // arguments.
1685   if (!InputPtrReg)
1686     return DAG.getConstant(0, SL, PtrVT);
1687 
1688   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1689   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1690     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1691 
1692   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1693 }
1694 
1695 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1696                                             const SDLoc &SL) const {
1697   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1698                                                FIRST_IMPLICIT);
1699   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1700 }
1701 
1702 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1703                                          const SDLoc &SL, SDValue Val,
1704                                          bool Signed,
1705                                          const ISD::InputArg *Arg) const {
1706   // First, if it is a widened vector, narrow it.
1707   if (VT.isVector() &&
1708       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1709     EVT NarrowedVT =
1710         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1711                          VT.getVectorNumElements());
1712     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1713                       DAG.getConstant(0, SL, MVT::i32));
1714   }
1715 
1716   // Then convert the vector elements or scalar value.
1717   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1718       VT.bitsLT(MemVT)) {
1719     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1720     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1721   }
1722 
1723   if (MemVT.isFloatingPoint())
1724     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1725   else if (Signed)
1726     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1727   else
1728     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1729 
1730   return Val;
1731 }
1732 
1733 SDValue SITargetLowering::lowerKernargMemParameter(
1734     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1735     uint64_t Offset, Align Alignment, bool Signed,
1736     const ISD::InputArg *Arg) const {
1737   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1738 
1739   // Try to avoid using an extload by loading earlier than the argument address,
1740   // and extracting the relevant bits. The load should hopefully be merged with
1741   // the previous argument.
1742   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1743     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1744     int64_t AlignDownOffset = alignDown(Offset, 4);
1745     int64_t OffsetDiff = Offset - AlignDownOffset;
1746 
1747     EVT IntVT = MemVT.changeTypeToInteger();
1748 
1749     // TODO: If we passed in the base kernel offset we could have a better
1750     // alignment than 4, but we don't really need it.
1751     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1752     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1753                                MachineMemOperand::MODereferenceable |
1754                                    MachineMemOperand::MOInvariant);
1755 
1756     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1757     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1758 
1759     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1760     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1761     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1762 
1763 
1764     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1765   }
1766 
1767   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1768   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1769                              MachineMemOperand::MODereferenceable |
1770                                  MachineMemOperand::MOInvariant);
1771 
1772   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1773   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1774 }
1775 
1776 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1777                                               const SDLoc &SL, SDValue Chain,
1778                                               const ISD::InputArg &Arg) const {
1779   MachineFunction &MF = DAG.getMachineFunction();
1780   MachineFrameInfo &MFI = MF.getFrameInfo();
1781 
1782   if (Arg.Flags.isByVal()) {
1783     unsigned Size = Arg.Flags.getByValSize();
1784     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1785     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1786   }
1787 
1788   unsigned ArgOffset = VA.getLocMemOffset();
1789   unsigned ArgSize = VA.getValVT().getStoreSize();
1790 
1791   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1792 
1793   // Create load nodes to retrieve arguments from the stack.
1794   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1795   SDValue ArgValue;
1796 
1797   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1798   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1799   MVT MemVT = VA.getValVT();
1800 
1801   switch (VA.getLocInfo()) {
1802   default:
1803     break;
1804   case CCValAssign::BCvt:
1805     MemVT = VA.getLocVT();
1806     break;
1807   case CCValAssign::SExt:
1808     ExtType = ISD::SEXTLOAD;
1809     break;
1810   case CCValAssign::ZExt:
1811     ExtType = ISD::ZEXTLOAD;
1812     break;
1813   case CCValAssign::AExt:
1814     ExtType = ISD::EXTLOAD;
1815     break;
1816   }
1817 
1818   ArgValue = DAG.getExtLoad(
1819     ExtType, SL, VA.getLocVT(), Chain, FIN,
1820     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1821     MemVT);
1822   return ArgValue;
1823 }
1824 
1825 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1826   const SIMachineFunctionInfo &MFI,
1827   EVT VT,
1828   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1829   const ArgDescriptor *Reg;
1830   const TargetRegisterClass *RC;
1831   LLT Ty;
1832 
1833   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1834   if (!Reg) {
1835     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1836       // It's possible for a kernarg intrinsic call to appear in a kernel with
1837       // no allocated segment, in which case we do not add the user sgpr
1838       // argument, so just return null.
1839       return DAG.getConstant(0, SDLoc(), VT);
1840     }
1841 
1842     // It's undefined behavior if a function marked with the amdgpu-no-*
1843     // attributes uses the corresponding intrinsic.
1844     return DAG.getUNDEF(VT);
1845   }
1846 
1847   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1848 }
1849 
1850 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1851                                CallingConv::ID CallConv,
1852                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1853                                FunctionType *FType,
1854                                SIMachineFunctionInfo *Info) {
1855   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1856     const ISD::InputArg *Arg = &Ins[I];
1857 
1858     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1859            "vector type argument should have been split");
1860 
1861     // First check if it's a PS input addr.
1862     if (CallConv == CallingConv::AMDGPU_PS &&
1863         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1864       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1865 
1866       // Inconveniently only the first part of the split is marked as isSplit,
1867       // so skip to the end. We only want to increment PSInputNum once for the
1868       // entire split argument.
1869       if (Arg->Flags.isSplit()) {
1870         while (!Arg->Flags.isSplitEnd()) {
1871           assert((!Arg->VT.isVector() ||
1872                   Arg->VT.getScalarSizeInBits() == 16) &&
1873                  "unexpected vector split in ps argument type");
1874           if (!SkipArg)
1875             Splits.push_back(*Arg);
1876           Arg = &Ins[++I];
1877         }
1878       }
1879 
1880       if (SkipArg) {
1881         // We can safely skip PS inputs.
1882         Skipped.set(Arg->getOrigArgIndex());
1883         ++PSInputNum;
1884         continue;
1885       }
1886 
1887       Info->markPSInputAllocated(PSInputNum);
1888       if (Arg->Used)
1889         Info->markPSInputEnabled(PSInputNum);
1890 
1891       ++PSInputNum;
1892     }
1893 
1894     Splits.push_back(*Arg);
1895   }
1896 }
1897 
1898 // Allocate special inputs passed in VGPRs.
1899 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1900                                                       MachineFunction &MF,
1901                                                       const SIRegisterInfo &TRI,
1902                                                       SIMachineFunctionInfo &Info) const {
1903   const LLT S32 = LLT::scalar(32);
1904   MachineRegisterInfo &MRI = MF.getRegInfo();
1905 
1906   if (Info.hasWorkItemIDX()) {
1907     Register Reg = AMDGPU::VGPR0;
1908     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1909 
1910     CCInfo.AllocateReg(Reg);
1911     unsigned Mask = (Subtarget->hasPackedTID() &&
1912                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1913     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1914   }
1915 
1916   if (Info.hasWorkItemIDY()) {
1917     assert(Info.hasWorkItemIDX());
1918     if (Subtarget->hasPackedTID()) {
1919       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1920                                                         0x3ff << 10));
1921     } else {
1922       unsigned Reg = AMDGPU::VGPR1;
1923       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1924 
1925       CCInfo.AllocateReg(Reg);
1926       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1927     }
1928   }
1929 
1930   if (Info.hasWorkItemIDZ()) {
1931     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1932     if (Subtarget->hasPackedTID()) {
1933       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1934                                                         0x3ff << 20));
1935     } else {
1936       unsigned Reg = AMDGPU::VGPR2;
1937       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1938 
1939       CCInfo.AllocateReg(Reg);
1940       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1941     }
1942   }
1943 }
1944 
1945 // Try to allocate a VGPR at the end of the argument list, or if no argument
1946 // VGPRs are left allocating a stack slot.
1947 // If \p Mask is is given it indicates bitfield position in the register.
1948 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1949 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1950                                          ArgDescriptor Arg = ArgDescriptor()) {
1951   if (Arg.isSet())
1952     return ArgDescriptor::createArg(Arg, Mask);
1953 
1954   ArrayRef<MCPhysReg> ArgVGPRs
1955     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1956   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1957   if (RegIdx == ArgVGPRs.size()) {
1958     // Spill to stack required.
1959     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1960 
1961     return ArgDescriptor::createStack(Offset, Mask);
1962   }
1963 
1964   unsigned Reg = ArgVGPRs[RegIdx];
1965   Reg = CCInfo.AllocateReg(Reg);
1966   assert(Reg != AMDGPU::NoRegister);
1967 
1968   MachineFunction &MF = CCInfo.getMachineFunction();
1969   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1970   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1971   return ArgDescriptor::createRegister(Reg, Mask);
1972 }
1973 
1974 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1975                                              const TargetRegisterClass *RC,
1976                                              unsigned NumArgRegs) {
1977   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1978   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1979   if (RegIdx == ArgSGPRs.size())
1980     report_fatal_error("ran out of SGPRs for arguments");
1981 
1982   unsigned Reg = ArgSGPRs[RegIdx];
1983   Reg = CCInfo.AllocateReg(Reg);
1984   assert(Reg != AMDGPU::NoRegister);
1985 
1986   MachineFunction &MF = CCInfo.getMachineFunction();
1987   MF.addLiveIn(Reg, RC);
1988   return ArgDescriptor::createRegister(Reg);
1989 }
1990 
1991 // If this has a fixed position, we still should allocate the register in the
1992 // CCInfo state. Technically we could get away with this for values passed
1993 // outside of the normal argument range.
1994 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1995                                        const TargetRegisterClass *RC,
1996                                        MCRegister Reg) {
1997   Reg = CCInfo.AllocateReg(Reg);
1998   assert(Reg != AMDGPU::NoRegister);
1999   MachineFunction &MF = CCInfo.getMachineFunction();
2000   MF.addLiveIn(Reg, RC);
2001 }
2002 
2003 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2004   if (Arg) {
2005     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2006                                Arg.getRegister());
2007   } else
2008     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2009 }
2010 
2011 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2012   if (Arg) {
2013     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2014                                Arg.getRegister());
2015   } else
2016     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2017 }
2018 
2019 /// Allocate implicit function VGPR arguments at the end of allocated user
2020 /// arguments.
2021 void SITargetLowering::allocateSpecialInputVGPRs(
2022   CCState &CCInfo, MachineFunction &MF,
2023   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2024   const unsigned Mask = 0x3ff;
2025   ArgDescriptor Arg;
2026 
2027   if (Info.hasWorkItemIDX()) {
2028     Arg = allocateVGPR32Input(CCInfo, Mask);
2029     Info.setWorkItemIDX(Arg);
2030   }
2031 
2032   if (Info.hasWorkItemIDY()) {
2033     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2034     Info.setWorkItemIDY(Arg);
2035   }
2036 
2037   if (Info.hasWorkItemIDZ())
2038     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2039 }
2040 
2041 /// Allocate implicit function VGPR arguments in fixed registers.
2042 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2043   CCState &CCInfo, MachineFunction &MF,
2044   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2045   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2046   if (!Reg)
2047     report_fatal_error("failed to allocated VGPR for implicit arguments");
2048 
2049   const unsigned Mask = 0x3ff;
2050   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2051   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2052   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2053 }
2054 
2055 void SITargetLowering::allocateSpecialInputSGPRs(
2056   CCState &CCInfo,
2057   MachineFunction &MF,
2058   const SIRegisterInfo &TRI,
2059   SIMachineFunctionInfo &Info) const {
2060   auto &ArgInfo = Info.getArgInfo();
2061 
2062   // TODO: Unify handling with private memory pointers.
2063   if (Info.hasDispatchPtr())
2064     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2065 
2066   if (Info.hasQueuePtr())
2067     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2068 
2069   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2070   // constant offset from the kernarg segment.
2071   if (Info.hasImplicitArgPtr())
2072     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2073 
2074   if (Info.hasDispatchID())
2075     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2076 
2077   // flat_scratch_init is not applicable for non-kernel functions.
2078 
2079   if (Info.hasWorkGroupIDX())
2080     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2081 
2082   if (Info.hasWorkGroupIDY())
2083     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2084 
2085   if (Info.hasWorkGroupIDZ())
2086     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2087 }
2088 
2089 // Allocate special inputs passed in user SGPRs.
2090 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2091                                             MachineFunction &MF,
2092                                             const SIRegisterInfo &TRI,
2093                                             SIMachineFunctionInfo &Info) const {
2094   if (Info.hasImplicitBufferPtr()) {
2095     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2096     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2097     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2098   }
2099 
2100   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2101   if (Info.hasPrivateSegmentBuffer()) {
2102     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2103     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2104     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2105   }
2106 
2107   if (Info.hasDispatchPtr()) {
2108     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2109     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2110     CCInfo.AllocateReg(DispatchPtrReg);
2111   }
2112 
2113   if (Info.hasQueuePtr()) {
2114     Register QueuePtrReg = Info.addQueuePtr(TRI);
2115     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2116     CCInfo.AllocateReg(QueuePtrReg);
2117   }
2118 
2119   if (Info.hasKernargSegmentPtr()) {
2120     MachineRegisterInfo &MRI = MF.getRegInfo();
2121     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2122     CCInfo.AllocateReg(InputPtrReg);
2123 
2124     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2125     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2126   }
2127 
2128   if (Info.hasDispatchID()) {
2129     Register DispatchIDReg = Info.addDispatchID(TRI);
2130     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2131     CCInfo.AllocateReg(DispatchIDReg);
2132   }
2133 
2134   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2135     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2136     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2137     CCInfo.AllocateReg(FlatScratchInitReg);
2138   }
2139 
2140   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2141   // these from the dispatch pointer.
2142 }
2143 
2144 // Allocate special input registers that are initialized per-wave.
2145 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2146                                            MachineFunction &MF,
2147                                            SIMachineFunctionInfo &Info,
2148                                            CallingConv::ID CallConv,
2149                                            bool IsShader) const {
2150   if (Info.hasWorkGroupIDX()) {
2151     Register Reg = Info.addWorkGroupIDX();
2152     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2153     CCInfo.AllocateReg(Reg);
2154   }
2155 
2156   if (Info.hasWorkGroupIDY()) {
2157     Register Reg = Info.addWorkGroupIDY();
2158     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2159     CCInfo.AllocateReg(Reg);
2160   }
2161 
2162   if (Info.hasWorkGroupIDZ()) {
2163     Register Reg = Info.addWorkGroupIDZ();
2164     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2165     CCInfo.AllocateReg(Reg);
2166   }
2167 
2168   if (Info.hasWorkGroupInfo()) {
2169     Register Reg = Info.addWorkGroupInfo();
2170     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2171     CCInfo.AllocateReg(Reg);
2172   }
2173 
2174   if (Info.hasPrivateSegmentWaveByteOffset()) {
2175     // Scratch wave offset passed in system SGPR.
2176     unsigned PrivateSegmentWaveByteOffsetReg;
2177 
2178     if (IsShader) {
2179       PrivateSegmentWaveByteOffsetReg =
2180         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2181 
2182       // This is true if the scratch wave byte offset doesn't have a fixed
2183       // location.
2184       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2185         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2186         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2187       }
2188     } else
2189       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2190 
2191     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2192     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2193   }
2194 }
2195 
2196 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2197                                      MachineFunction &MF,
2198                                      const SIRegisterInfo &TRI,
2199                                      SIMachineFunctionInfo &Info) {
2200   // Now that we've figured out where the scratch register inputs are, see if
2201   // should reserve the arguments and use them directly.
2202   MachineFrameInfo &MFI = MF.getFrameInfo();
2203   bool HasStackObjects = MFI.hasStackObjects();
2204   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2205 
2206   // Record that we know we have non-spill stack objects so we don't need to
2207   // check all stack objects later.
2208   if (HasStackObjects)
2209     Info.setHasNonSpillStackObjects(true);
2210 
2211   // Everything live out of a block is spilled with fast regalloc, so it's
2212   // almost certain that spilling will be required.
2213   if (TM.getOptLevel() == CodeGenOpt::None)
2214     HasStackObjects = true;
2215 
2216   // For now assume stack access is needed in any callee functions, so we need
2217   // the scratch registers to pass in.
2218   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2219 
2220   if (!ST.enableFlatScratch()) {
2221     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2222       // If we have stack objects, we unquestionably need the private buffer
2223       // resource. For the Code Object V2 ABI, this will be the first 4 user
2224       // SGPR inputs. We can reserve those and use them directly.
2225 
2226       Register PrivateSegmentBufferReg =
2227           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2228       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2229     } else {
2230       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2231       // We tentatively reserve the last registers (skipping the last registers
2232       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2233       // we'll replace these with the ones immediately after those which were
2234       // really allocated. In the prologue copies will be inserted from the
2235       // argument to these reserved registers.
2236 
2237       // Without HSA, relocations are used for the scratch pointer and the
2238       // buffer resource setup is always inserted in the prologue. Scratch wave
2239       // offset is still in an input SGPR.
2240       Info.setScratchRSrcReg(ReservedBufferReg);
2241     }
2242   }
2243 
2244   MachineRegisterInfo &MRI = MF.getRegInfo();
2245 
2246   // For entry functions we have to set up the stack pointer if we use it,
2247   // whereas non-entry functions get this "for free". This means there is no
2248   // intrinsic advantage to using S32 over S34 in cases where we do not have
2249   // calls but do need a frame pointer (i.e. if we are requested to have one
2250   // because frame pointer elimination is disabled). To keep things simple we
2251   // only ever use S32 as the call ABI stack pointer, and so using it does not
2252   // imply we need a separate frame pointer.
2253   //
2254   // Try to use s32 as the SP, but move it if it would interfere with input
2255   // arguments. This won't work with calls though.
2256   //
2257   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2258   // registers.
2259   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2260     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2261   } else {
2262     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2263 
2264     if (MFI.hasCalls())
2265       report_fatal_error("call in graphics shader with too many input SGPRs");
2266 
2267     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2268       if (!MRI.isLiveIn(Reg)) {
2269         Info.setStackPtrOffsetReg(Reg);
2270         break;
2271       }
2272     }
2273 
2274     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2275       report_fatal_error("failed to find register for SP");
2276   }
2277 
2278   // hasFP should be accurate for entry functions even before the frame is
2279   // finalized, because it does not rely on the known stack size, only
2280   // properties like whether variable sized objects are present.
2281   if (ST.getFrameLowering()->hasFP(MF)) {
2282     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2283   }
2284 }
2285 
2286 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2287   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2288   return !Info->isEntryFunction();
2289 }
2290 
2291 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2292 
2293 }
2294 
2295 void SITargetLowering::insertCopiesSplitCSR(
2296   MachineBasicBlock *Entry,
2297   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2298   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2299 
2300   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2301   if (!IStart)
2302     return;
2303 
2304   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2305   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2306   MachineBasicBlock::iterator MBBI = Entry->begin();
2307   for (const MCPhysReg *I = IStart; *I; ++I) {
2308     const TargetRegisterClass *RC = nullptr;
2309     if (AMDGPU::SReg_64RegClass.contains(*I))
2310       RC = &AMDGPU::SGPR_64RegClass;
2311     else if (AMDGPU::SReg_32RegClass.contains(*I))
2312       RC = &AMDGPU::SGPR_32RegClass;
2313     else
2314       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2315 
2316     Register NewVR = MRI->createVirtualRegister(RC);
2317     // Create copy from CSR to a virtual register.
2318     Entry->addLiveIn(*I);
2319     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2320       .addReg(*I);
2321 
2322     // Insert the copy-back instructions right before the terminator.
2323     for (auto *Exit : Exits)
2324       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2325               TII->get(TargetOpcode::COPY), *I)
2326         .addReg(NewVR);
2327   }
2328 }
2329 
2330 SDValue SITargetLowering::LowerFormalArguments(
2331     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2332     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2333     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2334   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2335 
2336   MachineFunction &MF = DAG.getMachineFunction();
2337   const Function &Fn = MF.getFunction();
2338   FunctionType *FType = MF.getFunction().getFunctionType();
2339   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2340 
2341   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2342     DiagnosticInfoUnsupported NoGraphicsHSA(
2343         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2344     DAG.getContext()->diagnose(NoGraphicsHSA);
2345     return DAG.getEntryNode();
2346   }
2347 
2348   Info->allocateModuleLDSGlobal(Fn.getParent());
2349 
2350   SmallVector<ISD::InputArg, 16> Splits;
2351   SmallVector<CCValAssign, 16> ArgLocs;
2352   BitVector Skipped(Ins.size());
2353   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2354                  *DAG.getContext());
2355 
2356   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2357   bool IsKernel = AMDGPU::isKernel(CallConv);
2358   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2359 
2360   if (IsGraphics) {
2361     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2362            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2363            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2364            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2365            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2366            !Info->hasWorkItemIDZ());
2367   }
2368 
2369   if (CallConv == CallingConv::AMDGPU_PS) {
2370     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2371 
2372     // At least one interpolation mode must be enabled or else the GPU will
2373     // hang.
2374     //
2375     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2376     // set PSInputAddr, the user wants to enable some bits after the compilation
2377     // based on run-time states. Since we can't know what the final PSInputEna
2378     // will look like, so we shouldn't do anything here and the user should take
2379     // responsibility for the correct programming.
2380     //
2381     // Otherwise, the following restrictions apply:
2382     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2383     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2384     //   enabled too.
2385     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2386         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2387       CCInfo.AllocateReg(AMDGPU::VGPR0);
2388       CCInfo.AllocateReg(AMDGPU::VGPR1);
2389       Info->markPSInputAllocated(0);
2390       Info->markPSInputEnabled(0);
2391     }
2392     if (Subtarget->isAmdPalOS()) {
2393       // For isAmdPalOS, the user does not enable some bits after compilation
2394       // based on run-time states; the register values being generated here are
2395       // the final ones set in hardware. Therefore we need to apply the
2396       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2397       // a bit is set in PSInputAddr but not PSInputEnable is where the
2398       // frontend set up an input arg for a particular interpolation mode, but
2399       // nothing uses that input arg. Really we should have an earlier pass
2400       // that removes such an arg.)
2401       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2402       if ((PsInputBits & 0x7F) == 0 ||
2403           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2404         Info->markPSInputEnabled(
2405             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2406     }
2407   } else if (IsKernel) {
2408     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2409   } else {
2410     Splits.append(Ins.begin(), Ins.end());
2411   }
2412 
2413   if (IsEntryFunc) {
2414     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2415     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2416   } else if (!IsGraphics) {
2417     // For the fixed ABI, pass workitem IDs in the last argument register.
2418     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2419   }
2420 
2421   if (IsKernel) {
2422     analyzeFormalArgumentsCompute(CCInfo, Ins);
2423   } else {
2424     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2425     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2426   }
2427 
2428   SmallVector<SDValue, 16> Chains;
2429 
2430   // FIXME: This is the minimum kernel argument alignment. We should improve
2431   // this to the maximum alignment of the arguments.
2432   //
2433   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2434   // kern arg offset.
2435   const Align KernelArgBaseAlign = Align(16);
2436 
2437   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2438     const ISD::InputArg &Arg = Ins[i];
2439     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2440       InVals.push_back(DAG.getUNDEF(Arg.VT));
2441       continue;
2442     }
2443 
2444     CCValAssign &VA = ArgLocs[ArgIdx++];
2445     MVT VT = VA.getLocVT();
2446 
2447     if (IsEntryFunc && VA.isMemLoc()) {
2448       VT = Ins[i].VT;
2449       EVT MemVT = VA.getLocVT();
2450 
2451       const uint64_t Offset = VA.getLocMemOffset();
2452       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2453 
2454       if (Arg.Flags.isByRef()) {
2455         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2456 
2457         const GCNTargetMachine &TM =
2458             static_cast<const GCNTargetMachine &>(getTargetMachine());
2459         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2460                                     Arg.Flags.getPointerAddrSpace())) {
2461           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2462                                      Arg.Flags.getPointerAddrSpace());
2463         }
2464 
2465         InVals.push_back(Ptr);
2466         continue;
2467       }
2468 
2469       SDValue Arg = lowerKernargMemParameter(
2470         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2471       Chains.push_back(Arg.getValue(1));
2472 
2473       auto *ParamTy =
2474         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2475       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2476           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2477                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2478         // On SI local pointers are just offsets into LDS, so they are always
2479         // less than 16-bits.  On CI and newer they could potentially be
2480         // real pointers, so we can't guarantee their size.
2481         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2482                           DAG.getValueType(MVT::i16));
2483       }
2484 
2485       InVals.push_back(Arg);
2486       continue;
2487     } else if (!IsEntryFunc && VA.isMemLoc()) {
2488       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2489       InVals.push_back(Val);
2490       if (!Arg.Flags.isByVal())
2491         Chains.push_back(Val.getValue(1));
2492       continue;
2493     }
2494 
2495     assert(VA.isRegLoc() && "Parameter must be in a register!");
2496 
2497     Register Reg = VA.getLocReg();
2498     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2499     EVT ValVT = VA.getValVT();
2500 
2501     Reg = MF.addLiveIn(Reg, RC);
2502     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2503 
2504     if (Arg.Flags.isSRet()) {
2505       // The return object should be reasonably addressable.
2506 
2507       // FIXME: This helps when the return is a real sret. If it is a
2508       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2509       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2510       unsigned NumBits
2511         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2512       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2513         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2514     }
2515 
2516     // If this is an 8 or 16-bit value, it is really passed promoted
2517     // to 32 bits. Insert an assert[sz]ext to capture this, then
2518     // truncate to the right size.
2519     switch (VA.getLocInfo()) {
2520     case CCValAssign::Full:
2521       break;
2522     case CCValAssign::BCvt:
2523       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2524       break;
2525     case CCValAssign::SExt:
2526       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2527                         DAG.getValueType(ValVT));
2528       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2529       break;
2530     case CCValAssign::ZExt:
2531       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2532                         DAG.getValueType(ValVT));
2533       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2534       break;
2535     case CCValAssign::AExt:
2536       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2537       break;
2538     default:
2539       llvm_unreachable("Unknown loc info!");
2540     }
2541 
2542     InVals.push_back(Val);
2543   }
2544 
2545   // Start adding system SGPRs.
2546   if (IsEntryFunc) {
2547     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2548   } else {
2549     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2550     if (!IsGraphics)
2551       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2552   }
2553 
2554   auto &ArgUsageInfo =
2555     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2556   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2557 
2558   unsigned StackArgSize = CCInfo.getNextStackOffset();
2559   Info->setBytesInStackArgArea(StackArgSize);
2560 
2561   return Chains.empty() ? Chain :
2562     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2563 }
2564 
2565 // TODO: If return values can't fit in registers, we should return as many as
2566 // possible in registers before passing on stack.
2567 bool SITargetLowering::CanLowerReturn(
2568   CallingConv::ID CallConv,
2569   MachineFunction &MF, bool IsVarArg,
2570   const SmallVectorImpl<ISD::OutputArg> &Outs,
2571   LLVMContext &Context) const {
2572   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2573   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2574   // for shaders. Vector types should be explicitly handled by CC.
2575   if (AMDGPU::isEntryFunctionCC(CallConv))
2576     return true;
2577 
2578   SmallVector<CCValAssign, 16> RVLocs;
2579   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2580   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2581 }
2582 
2583 SDValue
2584 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2585                               bool isVarArg,
2586                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2587                               const SmallVectorImpl<SDValue> &OutVals,
2588                               const SDLoc &DL, SelectionDAG &DAG) const {
2589   MachineFunction &MF = DAG.getMachineFunction();
2590   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2591 
2592   if (AMDGPU::isKernel(CallConv)) {
2593     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2594                                              OutVals, DL, DAG);
2595   }
2596 
2597   bool IsShader = AMDGPU::isShader(CallConv);
2598 
2599   Info->setIfReturnsVoid(Outs.empty());
2600   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2601 
2602   // CCValAssign - represent the assignment of the return value to a location.
2603   SmallVector<CCValAssign, 48> RVLocs;
2604   SmallVector<ISD::OutputArg, 48> Splits;
2605 
2606   // CCState - Info about the registers and stack slots.
2607   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2608                  *DAG.getContext());
2609 
2610   // Analyze outgoing return values.
2611   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2612 
2613   SDValue Flag;
2614   SmallVector<SDValue, 48> RetOps;
2615   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2616 
2617   // Add return address for callable functions.
2618   if (!Info->isEntryFunction()) {
2619     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2620     SDValue ReturnAddrReg = CreateLiveInRegister(
2621       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2622 
2623     SDValue ReturnAddrVirtualReg =
2624         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2625                             CallConv != CallingConv::AMDGPU_Gfx
2626                                 ? &AMDGPU::CCR_SGPR_64RegClass
2627                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2628                         MVT::i64);
2629     Chain =
2630         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2631     Flag = Chain.getValue(1);
2632     RetOps.push_back(ReturnAddrVirtualReg);
2633   }
2634 
2635   // Copy the result values into the output registers.
2636   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2637        ++I, ++RealRVLocIdx) {
2638     CCValAssign &VA = RVLocs[I];
2639     assert(VA.isRegLoc() && "Can only return in registers!");
2640     // TODO: Partially return in registers if return values don't fit.
2641     SDValue Arg = OutVals[RealRVLocIdx];
2642 
2643     // Copied from other backends.
2644     switch (VA.getLocInfo()) {
2645     case CCValAssign::Full:
2646       break;
2647     case CCValAssign::BCvt:
2648       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2649       break;
2650     case CCValAssign::SExt:
2651       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2652       break;
2653     case CCValAssign::ZExt:
2654       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2655       break;
2656     case CCValAssign::AExt:
2657       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2658       break;
2659     default:
2660       llvm_unreachable("Unknown loc info!");
2661     }
2662 
2663     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2664     Flag = Chain.getValue(1);
2665     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2666   }
2667 
2668   // FIXME: Does sret work properly?
2669   if (!Info->isEntryFunction()) {
2670     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2671     const MCPhysReg *I =
2672       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2673     if (I) {
2674       for (; *I; ++I) {
2675         if (AMDGPU::SReg_64RegClass.contains(*I))
2676           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2677         else if (AMDGPU::SReg_32RegClass.contains(*I))
2678           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2679         else
2680           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2681       }
2682     }
2683   }
2684 
2685   // Update chain and glue.
2686   RetOps[0] = Chain;
2687   if (Flag.getNode())
2688     RetOps.push_back(Flag);
2689 
2690   unsigned Opc = AMDGPUISD::ENDPGM;
2691   if (!IsWaveEnd) {
2692     if (IsShader)
2693       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2694     else if (CallConv == CallingConv::AMDGPU_Gfx)
2695       Opc = AMDGPUISD::RET_GFX_FLAG;
2696     else
2697       Opc = AMDGPUISD::RET_FLAG;
2698   }
2699 
2700   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2701 }
2702 
2703 SDValue SITargetLowering::LowerCallResult(
2704     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2705     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2706     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2707     SDValue ThisVal) const {
2708   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2709 
2710   // Assign locations to each value returned by this call.
2711   SmallVector<CCValAssign, 16> RVLocs;
2712   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2713                  *DAG.getContext());
2714   CCInfo.AnalyzeCallResult(Ins, RetCC);
2715 
2716   // Copy all of the result registers out of their specified physreg.
2717   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2718     CCValAssign VA = RVLocs[i];
2719     SDValue Val;
2720 
2721     if (VA.isRegLoc()) {
2722       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2723       Chain = Val.getValue(1);
2724       InFlag = Val.getValue(2);
2725     } else if (VA.isMemLoc()) {
2726       report_fatal_error("TODO: return values in memory");
2727     } else
2728       llvm_unreachable("unknown argument location type");
2729 
2730     switch (VA.getLocInfo()) {
2731     case CCValAssign::Full:
2732       break;
2733     case CCValAssign::BCvt:
2734       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2735       break;
2736     case CCValAssign::ZExt:
2737       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2738                         DAG.getValueType(VA.getValVT()));
2739       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2740       break;
2741     case CCValAssign::SExt:
2742       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2743                         DAG.getValueType(VA.getValVT()));
2744       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2745       break;
2746     case CCValAssign::AExt:
2747       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2748       break;
2749     default:
2750       llvm_unreachable("Unknown loc info!");
2751     }
2752 
2753     InVals.push_back(Val);
2754   }
2755 
2756   return Chain;
2757 }
2758 
2759 // Add code to pass special inputs required depending on used features separate
2760 // from the explicit user arguments present in the IR.
2761 void SITargetLowering::passSpecialInputs(
2762     CallLoweringInfo &CLI,
2763     CCState &CCInfo,
2764     const SIMachineFunctionInfo &Info,
2765     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2766     SmallVectorImpl<SDValue> &MemOpChains,
2767     SDValue Chain) const {
2768   // If we don't have a call site, this was a call inserted by
2769   // legalization. These can never use special inputs.
2770   if (!CLI.CB)
2771     return;
2772 
2773   SelectionDAG &DAG = CLI.DAG;
2774   const SDLoc &DL = CLI.DL;
2775   const Function &F = DAG.getMachineFunction().getFunction();
2776 
2777   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2778   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2779 
2780   const AMDGPUFunctionArgInfo *CalleeArgInfo
2781     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2782   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2783     auto &ArgUsageInfo =
2784       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2785     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2786   }
2787 
2788   // TODO: Unify with private memory register handling. This is complicated by
2789   // the fact that at least in kernels, the input argument is not necessarily
2790   // in the same location as the input.
2791   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2792                              StringLiteral> ImplicitAttrs[] = {
2793     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2794     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2795     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2796     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2797     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2798     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2799     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2800   };
2801 
2802   for (auto Attr : ImplicitAttrs) {
2803     const ArgDescriptor *OutgoingArg;
2804     const TargetRegisterClass *ArgRC;
2805     LLT ArgTy;
2806 
2807     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2808 
2809     // If the callee does not use the attribute value, skip copying the value.
2810     if (CLI.CB->hasFnAttr(Attr.second))
2811       continue;
2812 
2813     std::tie(OutgoingArg, ArgRC, ArgTy) =
2814         CalleeArgInfo->getPreloadedValue(InputID);
2815     if (!OutgoingArg)
2816       continue;
2817 
2818     const ArgDescriptor *IncomingArg;
2819     const TargetRegisterClass *IncomingArgRC;
2820     LLT Ty;
2821     std::tie(IncomingArg, IncomingArgRC, Ty) =
2822         CallerArgInfo.getPreloadedValue(InputID);
2823     assert(IncomingArgRC == ArgRC);
2824 
2825     // All special arguments are ints for now.
2826     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2827     SDValue InputReg;
2828 
2829     if (IncomingArg) {
2830       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2831     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2832       // The implicit arg ptr is special because it doesn't have a corresponding
2833       // input for kernels, and is computed from the kernarg segment pointer.
2834       InputReg = getImplicitArgPtr(DAG, DL);
2835     } else {
2836       // We may have proven the input wasn't needed, although the ABI is
2837       // requiring it. We just need to allocate the register appropriately.
2838       InputReg = DAG.getUNDEF(ArgVT);
2839     }
2840 
2841     if (OutgoingArg->isRegister()) {
2842       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2843       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2844         report_fatal_error("failed to allocate implicit input argument");
2845     } else {
2846       unsigned SpecialArgOffset =
2847           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2848       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2849                                               SpecialArgOffset);
2850       MemOpChains.push_back(ArgStore);
2851     }
2852   }
2853 
2854   // Pack workitem IDs into a single register or pass it as is if already
2855   // packed.
2856   const ArgDescriptor *OutgoingArg;
2857   const TargetRegisterClass *ArgRC;
2858   LLT Ty;
2859 
2860   std::tie(OutgoingArg, ArgRC, Ty) =
2861       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2862   if (!OutgoingArg)
2863     std::tie(OutgoingArg, ArgRC, Ty) =
2864         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2865   if (!OutgoingArg)
2866     std::tie(OutgoingArg, ArgRC, Ty) =
2867         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2868   if (!OutgoingArg)
2869     return;
2870 
2871   const ArgDescriptor *IncomingArgX = std::get<0>(
2872       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2873   const ArgDescriptor *IncomingArgY = std::get<0>(
2874       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2875   const ArgDescriptor *IncomingArgZ = std::get<0>(
2876       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2877 
2878   SDValue InputReg;
2879   SDLoc SL;
2880 
2881   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2882   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2883   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2884 
2885   // If incoming ids are not packed we need to pack them.
2886   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2887       NeedWorkItemIDX) {
2888     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2889       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2890     } else {
2891       InputReg = DAG.getConstant(0, DL, MVT::i32);
2892     }
2893   }
2894 
2895   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2896       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2897     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2898     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2899                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2900     InputReg = InputReg.getNode() ?
2901                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2902   }
2903 
2904   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2905       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2906     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2907     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2908                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2909     InputReg = InputReg.getNode() ?
2910                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2911   }
2912 
2913   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2914     // Workitem ids are already packed, any of present incoming arguments
2915     // will carry all required fields.
2916     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2917       IncomingArgX ? *IncomingArgX :
2918       IncomingArgY ? *IncomingArgY :
2919                      *IncomingArgZ, ~0u);
2920     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2921   }
2922 
2923   if (OutgoingArg->isRegister()) {
2924     if (InputReg)
2925       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2926 
2927     CCInfo.AllocateReg(OutgoingArg->getRegister());
2928   } else {
2929     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2930     if (InputReg) {
2931       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2932                                               SpecialArgOffset);
2933       MemOpChains.push_back(ArgStore);
2934     }
2935   }
2936 }
2937 
2938 static bool canGuaranteeTCO(CallingConv::ID CC) {
2939   return CC == CallingConv::Fast;
2940 }
2941 
2942 /// Return true if we might ever do TCO for calls with this calling convention.
2943 static bool mayTailCallThisCC(CallingConv::ID CC) {
2944   switch (CC) {
2945   case CallingConv::C:
2946   case CallingConv::AMDGPU_Gfx:
2947     return true;
2948   default:
2949     return canGuaranteeTCO(CC);
2950   }
2951 }
2952 
2953 bool SITargetLowering::isEligibleForTailCallOptimization(
2954     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2955     const SmallVectorImpl<ISD::OutputArg> &Outs,
2956     const SmallVectorImpl<SDValue> &OutVals,
2957     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2958   if (!mayTailCallThisCC(CalleeCC))
2959     return false;
2960 
2961   // For a divergent call target, we need to do a waterfall loop over the
2962   // possible callees which precludes us from using a simple jump.
2963   if (Callee->isDivergent())
2964     return false;
2965 
2966   MachineFunction &MF = DAG.getMachineFunction();
2967   const Function &CallerF = MF.getFunction();
2968   CallingConv::ID CallerCC = CallerF.getCallingConv();
2969   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2970   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2971 
2972   // Kernels aren't callable, and don't have a live in return address so it
2973   // doesn't make sense to do a tail call with entry functions.
2974   if (!CallerPreserved)
2975     return false;
2976 
2977   bool CCMatch = CallerCC == CalleeCC;
2978 
2979   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2980     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2981       return true;
2982     return false;
2983   }
2984 
2985   // TODO: Can we handle var args?
2986   if (IsVarArg)
2987     return false;
2988 
2989   for (const Argument &Arg : CallerF.args()) {
2990     if (Arg.hasByValAttr())
2991       return false;
2992   }
2993 
2994   LLVMContext &Ctx = *DAG.getContext();
2995 
2996   // Check that the call results are passed in the same way.
2997   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2998                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2999                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3000     return false;
3001 
3002   // The callee has to preserve all registers the caller needs to preserve.
3003   if (!CCMatch) {
3004     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3005     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3006       return false;
3007   }
3008 
3009   // Nothing more to check if the callee is taking no arguments.
3010   if (Outs.empty())
3011     return true;
3012 
3013   SmallVector<CCValAssign, 16> ArgLocs;
3014   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3015 
3016   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3017 
3018   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3019   // If the stack arguments for this call do not fit into our own save area then
3020   // the call cannot be made tail.
3021   // TODO: Is this really necessary?
3022   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3023     return false;
3024 
3025   const MachineRegisterInfo &MRI = MF.getRegInfo();
3026   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3027 }
3028 
3029 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3030   if (!CI->isTailCall())
3031     return false;
3032 
3033   const Function *ParentFn = CI->getParent()->getParent();
3034   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3035     return false;
3036   return true;
3037 }
3038 
3039 // The wave scratch offset register is used as the global base pointer.
3040 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3041                                     SmallVectorImpl<SDValue> &InVals) const {
3042   SelectionDAG &DAG = CLI.DAG;
3043   const SDLoc &DL = CLI.DL;
3044   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3045   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3046   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3047   SDValue Chain = CLI.Chain;
3048   SDValue Callee = CLI.Callee;
3049   bool &IsTailCall = CLI.IsTailCall;
3050   CallingConv::ID CallConv = CLI.CallConv;
3051   bool IsVarArg = CLI.IsVarArg;
3052   bool IsSibCall = false;
3053   bool IsThisReturn = false;
3054   MachineFunction &MF = DAG.getMachineFunction();
3055 
3056   if (Callee.isUndef() || isNullConstant(Callee)) {
3057     if (!CLI.IsTailCall) {
3058       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3059         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3060     }
3061 
3062     return Chain;
3063   }
3064 
3065   if (IsVarArg) {
3066     return lowerUnhandledCall(CLI, InVals,
3067                               "unsupported call to variadic function ");
3068   }
3069 
3070   if (!CLI.CB)
3071     report_fatal_error("unsupported libcall legalization");
3072 
3073   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3074     return lowerUnhandledCall(CLI, InVals,
3075                               "unsupported required tail call to function ");
3076   }
3077 
3078   if (AMDGPU::isShader(CallConv)) {
3079     // Note the issue is with the CC of the called function, not of the call
3080     // itself.
3081     return lowerUnhandledCall(CLI, InVals,
3082                               "unsupported call to a shader function ");
3083   }
3084 
3085   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3086       CallConv != CallingConv::AMDGPU_Gfx) {
3087     // Only allow calls with specific calling conventions.
3088     return lowerUnhandledCall(CLI, InVals,
3089                               "unsupported calling convention for call from "
3090                               "graphics shader of function ");
3091   }
3092 
3093   if (IsTailCall) {
3094     IsTailCall = isEligibleForTailCallOptimization(
3095       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3096     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3097       report_fatal_error("failed to perform tail call elimination on a call "
3098                          "site marked musttail");
3099     }
3100 
3101     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3102 
3103     // A sibling call is one where we're under the usual C ABI and not planning
3104     // to change that but can still do a tail call:
3105     if (!TailCallOpt && IsTailCall)
3106       IsSibCall = true;
3107 
3108     if (IsTailCall)
3109       ++NumTailCalls;
3110   }
3111 
3112   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3113   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3114   SmallVector<SDValue, 8> MemOpChains;
3115 
3116   // Analyze operands of the call, assigning locations to each operand.
3117   SmallVector<CCValAssign, 16> ArgLocs;
3118   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3119   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3120 
3121   if (CallConv != CallingConv::AMDGPU_Gfx) {
3122     // With a fixed ABI, allocate fixed registers before user arguments.
3123     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3124   }
3125 
3126   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3127 
3128   // Get a count of how many bytes are to be pushed on the stack.
3129   unsigned NumBytes = CCInfo.getNextStackOffset();
3130 
3131   if (IsSibCall) {
3132     // Since we're not changing the ABI to make this a tail call, the memory
3133     // operands are already available in the caller's incoming argument space.
3134     NumBytes = 0;
3135   }
3136 
3137   // FPDiff is the byte offset of the call's argument area from the callee's.
3138   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3139   // by this amount for a tail call. In a sibling call it must be 0 because the
3140   // caller will deallocate the entire stack and the callee still expects its
3141   // arguments to begin at SP+0. Completely unused for non-tail calls.
3142   int32_t FPDiff = 0;
3143   MachineFrameInfo &MFI = MF.getFrameInfo();
3144 
3145   // Adjust the stack pointer for the new arguments...
3146   // These operations are automatically eliminated by the prolog/epilog pass
3147   if (!IsSibCall) {
3148     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3149 
3150     if (!Subtarget->enableFlatScratch()) {
3151       SmallVector<SDValue, 4> CopyFromChains;
3152 
3153       // In the HSA case, this should be an identity copy.
3154       SDValue ScratchRSrcReg
3155         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3156       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3157       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3158       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3159     }
3160   }
3161 
3162   MVT PtrVT = MVT::i32;
3163 
3164   // Walk the register/memloc assignments, inserting copies/loads.
3165   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3166     CCValAssign &VA = ArgLocs[i];
3167     SDValue Arg = OutVals[i];
3168 
3169     // Promote the value if needed.
3170     switch (VA.getLocInfo()) {
3171     case CCValAssign::Full:
3172       break;
3173     case CCValAssign::BCvt:
3174       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3175       break;
3176     case CCValAssign::ZExt:
3177       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3178       break;
3179     case CCValAssign::SExt:
3180       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3181       break;
3182     case CCValAssign::AExt:
3183       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3184       break;
3185     case CCValAssign::FPExt:
3186       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3187       break;
3188     default:
3189       llvm_unreachable("Unknown loc info!");
3190     }
3191 
3192     if (VA.isRegLoc()) {
3193       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3194     } else {
3195       assert(VA.isMemLoc());
3196 
3197       SDValue DstAddr;
3198       MachinePointerInfo DstInfo;
3199 
3200       unsigned LocMemOffset = VA.getLocMemOffset();
3201       int32_t Offset = LocMemOffset;
3202 
3203       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3204       MaybeAlign Alignment;
3205 
3206       if (IsTailCall) {
3207         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3208         unsigned OpSize = Flags.isByVal() ?
3209           Flags.getByValSize() : VA.getValVT().getStoreSize();
3210 
3211         // FIXME: We can have better than the minimum byval required alignment.
3212         Alignment =
3213             Flags.isByVal()
3214                 ? Flags.getNonZeroByValAlign()
3215                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3216 
3217         Offset = Offset + FPDiff;
3218         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3219 
3220         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3221         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3222 
3223         // Make sure any stack arguments overlapping with where we're storing
3224         // are loaded before this eventual operation. Otherwise they'll be
3225         // clobbered.
3226 
3227         // FIXME: Why is this really necessary? This seems to just result in a
3228         // lot of code to copy the stack and write them back to the same
3229         // locations, which are supposed to be immutable?
3230         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3231       } else {
3232         // Stores to the argument stack area are relative to the stack pointer.
3233         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3234                                         MVT::i32);
3235         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3236         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3237         Alignment =
3238             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3239       }
3240 
3241       if (Outs[i].Flags.isByVal()) {
3242         SDValue SizeNode =
3243             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3244         SDValue Cpy =
3245             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3246                           Outs[i].Flags.getNonZeroByValAlign(),
3247                           /*isVol = */ false, /*AlwaysInline = */ true,
3248                           /*isTailCall = */ false, DstInfo,
3249                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3250 
3251         MemOpChains.push_back(Cpy);
3252       } else {
3253         SDValue Store =
3254             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3255         MemOpChains.push_back(Store);
3256       }
3257     }
3258   }
3259 
3260   if (!MemOpChains.empty())
3261     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3262 
3263   // Build a sequence of copy-to-reg nodes chained together with token chain
3264   // and flag operands which copy the outgoing args into the appropriate regs.
3265   SDValue InFlag;
3266   for (auto &RegToPass : RegsToPass) {
3267     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3268                              RegToPass.second, InFlag);
3269     InFlag = Chain.getValue(1);
3270   }
3271 
3272 
3273   SDValue PhysReturnAddrReg;
3274   if (IsTailCall) {
3275     // Since the return is being combined with the call, we need to pass on the
3276     // return address.
3277 
3278     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3279     SDValue ReturnAddrReg = CreateLiveInRegister(
3280       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3281 
3282     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3283                                         MVT::i64);
3284     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3285     InFlag = Chain.getValue(1);
3286   }
3287 
3288   // We don't usually want to end the call-sequence here because we would tidy
3289   // the frame up *after* the call, however in the ABI-changing tail-call case
3290   // we've carefully laid out the parameters so that when sp is reset they'll be
3291   // in the correct location.
3292   if (IsTailCall && !IsSibCall) {
3293     Chain = DAG.getCALLSEQ_END(Chain,
3294                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3295                                DAG.getTargetConstant(0, DL, MVT::i32),
3296                                InFlag, DL);
3297     InFlag = Chain.getValue(1);
3298   }
3299 
3300   std::vector<SDValue> Ops;
3301   Ops.push_back(Chain);
3302   Ops.push_back(Callee);
3303   // Add a redundant copy of the callee global which will not be legalized, as
3304   // we need direct access to the callee later.
3305   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3306     const GlobalValue *GV = GSD->getGlobal();
3307     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3308   } else {
3309     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3310   }
3311 
3312   if (IsTailCall) {
3313     // Each tail call may have to adjust the stack by a different amount, so
3314     // this information must travel along with the operation for eventual
3315     // consumption by emitEpilogue.
3316     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3317 
3318     Ops.push_back(PhysReturnAddrReg);
3319   }
3320 
3321   // Add argument registers to the end of the list so that they are known live
3322   // into the call.
3323   for (auto &RegToPass : RegsToPass) {
3324     Ops.push_back(DAG.getRegister(RegToPass.first,
3325                                   RegToPass.second.getValueType()));
3326   }
3327 
3328   // Add a register mask operand representing the call-preserved registers.
3329 
3330   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3331   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3332   assert(Mask && "Missing call preserved mask for calling convention");
3333   Ops.push_back(DAG.getRegisterMask(Mask));
3334 
3335   if (InFlag.getNode())
3336     Ops.push_back(InFlag);
3337 
3338   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3339 
3340   // If we're doing a tall call, use a TC_RETURN here rather than an
3341   // actual call instruction.
3342   if (IsTailCall) {
3343     MFI.setHasTailCall();
3344     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3345   }
3346 
3347   // Returns a chain and a flag for retval copy to use.
3348   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3349   Chain = Call.getValue(0);
3350   InFlag = Call.getValue(1);
3351 
3352   uint64_t CalleePopBytes = NumBytes;
3353   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3354                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3355                              InFlag, DL);
3356   if (!Ins.empty())
3357     InFlag = Chain.getValue(1);
3358 
3359   // Handle result values, copying them out of physregs into vregs that we
3360   // return.
3361   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3362                          InVals, IsThisReturn,
3363                          IsThisReturn ? OutVals[0] : SDValue());
3364 }
3365 
3366 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3367 // except for applying the wave size scale to the increment amount.
3368 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3369     SDValue Op, SelectionDAG &DAG) const {
3370   const MachineFunction &MF = DAG.getMachineFunction();
3371   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3372 
3373   SDLoc dl(Op);
3374   EVT VT = Op.getValueType();
3375   SDValue Tmp1 = Op;
3376   SDValue Tmp2 = Op.getValue(1);
3377   SDValue Tmp3 = Op.getOperand(2);
3378   SDValue Chain = Tmp1.getOperand(0);
3379 
3380   Register SPReg = Info->getStackPtrOffsetReg();
3381 
3382   // Chain the dynamic stack allocation so that it doesn't modify the stack
3383   // pointer when other instructions are using the stack.
3384   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3385 
3386   SDValue Size  = Tmp2.getOperand(1);
3387   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3388   Chain = SP.getValue(1);
3389   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3390   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3391   const TargetFrameLowering *TFL = ST.getFrameLowering();
3392   unsigned Opc =
3393     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3394     ISD::ADD : ISD::SUB;
3395 
3396   SDValue ScaledSize = DAG.getNode(
3397       ISD::SHL, dl, VT, Size,
3398       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3399 
3400   Align StackAlign = TFL->getStackAlign();
3401   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3402   if (Alignment && *Alignment > StackAlign) {
3403     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3404                        DAG.getConstant(-(uint64_t)Alignment->value()
3405                                            << ST.getWavefrontSizeLog2(),
3406                                        dl, VT));
3407   }
3408 
3409   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3410   Tmp2 = DAG.getCALLSEQ_END(
3411       Chain, DAG.getIntPtrConstant(0, dl, true),
3412       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3413 
3414   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3415 }
3416 
3417 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3418                                                   SelectionDAG &DAG) const {
3419   // We only handle constant sizes here to allow non-entry block, static sized
3420   // allocas. A truly dynamic value is more difficult to support because we
3421   // don't know if the size value is uniform or not. If the size isn't uniform,
3422   // we would need to do a wave reduction to get the maximum size to know how
3423   // much to increment the uniform stack pointer.
3424   SDValue Size = Op.getOperand(1);
3425   if (isa<ConstantSDNode>(Size))
3426       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3427 
3428   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3429 }
3430 
3431 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3432                                              const MachineFunction &MF) const {
3433   Register Reg = StringSwitch<Register>(RegName)
3434     .Case("m0", AMDGPU::M0)
3435     .Case("exec", AMDGPU::EXEC)
3436     .Case("exec_lo", AMDGPU::EXEC_LO)
3437     .Case("exec_hi", AMDGPU::EXEC_HI)
3438     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3439     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3440     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3441     .Default(Register());
3442 
3443   if (Reg == AMDGPU::NoRegister) {
3444     report_fatal_error(Twine("invalid register name \""
3445                              + StringRef(RegName)  + "\"."));
3446 
3447   }
3448 
3449   if (!Subtarget->hasFlatScrRegister() &&
3450        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3451     report_fatal_error(Twine("invalid register \""
3452                              + StringRef(RegName)  + "\" for subtarget."));
3453   }
3454 
3455   switch (Reg) {
3456   case AMDGPU::M0:
3457   case AMDGPU::EXEC_LO:
3458   case AMDGPU::EXEC_HI:
3459   case AMDGPU::FLAT_SCR_LO:
3460   case AMDGPU::FLAT_SCR_HI:
3461     if (VT.getSizeInBits() == 32)
3462       return Reg;
3463     break;
3464   case AMDGPU::EXEC:
3465   case AMDGPU::FLAT_SCR:
3466     if (VT.getSizeInBits() == 64)
3467       return Reg;
3468     break;
3469   default:
3470     llvm_unreachable("missing register type checking");
3471   }
3472 
3473   report_fatal_error(Twine("invalid type for register \""
3474                            + StringRef(RegName) + "\"."));
3475 }
3476 
3477 // If kill is not the last instruction, split the block so kill is always a
3478 // proper terminator.
3479 MachineBasicBlock *
3480 SITargetLowering::splitKillBlock(MachineInstr &MI,
3481                                  MachineBasicBlock *BB) const {
3482   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3483   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3484   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3485   return SplitBB;
3486 }
3487 
3488 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3489 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3490 // be the first instruction in the remainder block.
3491 //
3492 /// \returns { LoopBody, Remainder }
3493 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3494 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3495   MachineFunction *MF = MBB.getParent();
3496   MachineBasicBlock::iterator I(&MI);
3497 
3498   // To insert the loop we need to split the block. Move everything after this
3499   // point to a new block, and insert a new empty block between the two.
3500   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3501   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3502   MachineFunction::iterator MBBI(MBB);
3503   ++MBBI;
3504 
3505   MF->insert(MBBI, LoopBB);
3506   MF->insert(MBBI, RemainderBB);
3507 
3508   LoopBB->addSuccessor(LoopBB);
3509   LoopBB->addSuccessor(RemainderBB);
3510 
3511   // Move the rest of the block into a new block.
3512   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3513 
3514   if (InstInLoop) {
3515     auto Next = std::next(I);
3516 
3517     // Move instruction to loop body.
3518     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3519 
3520     // Move the rest of the block.
3521     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3522   } else {
3523     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3524   }
3525 
3526   MBB.addSuccessor(LoopBB);
3527 
3528   return std::make_pair(LoopBB, RemainderBB);
3529 }
3530 
3531 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3532 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3533   MachineBasicBlock *MBB = MI.getParent();
3534   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3535   auto I = MI.getIterator();
3536   auto E = std::next(I);
3537 
3538   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3539     .addImm(0);
3540 
3541   MIBundleBuilder Bundler(*MBB, I, E);
3542   finalizeBundle(*MBB, Bundler.begin());
3543 }
3544 
3545 MachineBasicBlock *
3546 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3547                                          MachineBasicBlock *BB) const {
3548   const DebugLoc &DL = MI.getDebugLoc();
3549 
3550   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3551 
3552   MachineBasicBlock *LoopBB;
3553   MachineBasicBlock *RemainderBB;
3554   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3555 
3556   // Apparently kill flags are only valid if the def is in the same block?
3557   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3558     Src->setIsKill(false);
3559 
3560   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3561 
3562   MachineBasicBlock::iterator I = LoopBB->end();
3563 
3564   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3565     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3566 
3567   // Clear TRAP_STS.MEM_VIOL
3568   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3569     .addImm(0)
3570     .addImm(EncodedReg);
3571 
3572   bundleInstWithWaitcnt(MI);
3573 
3574   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3575 
3576   // Load and check TRAP_STS.MEM_VIOL
3577   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3578     .addImm(EncodedReg);
3579 
3580   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3581   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3582     .addReg(Reg, RegState::Kill)
3583     .addImm(0);
3584   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3585     .addMBB(LoopBB);
3586 
3587   return RemainderBB;
3588 }
3589 
3590 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3591 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3592 // will only do one iteration. In the worst case, this will loop 64 times.
3593 //
3594 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3595 static MachineBasicBlock::iterator
3596 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3597                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3598                        const DebugLoc &DL, const MachineOperand &Idx,
3599                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3600                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3601                        Register &SGPRIdxReg) {
3602 
3603   MachineFunction *MF = OrigBB.getParent();
3604   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3605   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3606   MachineBasicBlock::iterator I = LoopBB.begin();
3607 
3608   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3609   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3610   Register NewExec = MRI.createVirtualRegister(BoolRC);
3611   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3612   Register CondReg = MRI.createVirtualRegister(BoolRC);
3613 
3614   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3615     .addReg(InitReg)
3616     .addMBB(&OrigBB)
3617     .addReg(ResultReg)
3618     .addMBB(&LoopBB);
3619 
3620   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3621     .addReg(InitSaveExecReg)
3622     .addMBB(&OrigBB)
3623     .addReg(NewExec)
3624     .addMBB(&LoopBB);
3625 
3626   // Read the next variant <- also loop target.
3627   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3628       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3629 
3630   // Compare the just read M0 value to all possible Idx values.
3631   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3632       .addReg(CurrentIdxReg)
3633       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3634 
3635   // Update EXEC, save the original EXEC value to VCC.
3636   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3637                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3638           NewExec)
3639     .addReg(CondReg, RegState::Kill);
3640 
3641   MRI.setSimpleHint(NewExec, CondReg);
3642 
3643   if (UseGPRIdxMode) {
3644     if (Offset == 0) {
3645       SGPRIdxReg = CurrentIdxReg;
3646     } else {
3647       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3648       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3649           .addReg(CurrentIdxReg, RegState::Kill)
3650           .addImm(Offset);
3651     }
3652   } else {
3653     // Move index from VCC into M0
3654     if (Offset == 0) {
3655       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3656         .addReg(CurrentIdxReg, RegState::Kill);
3657     } else {
3658       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3659         .addReg(CurrentIdxReg, RegState::Kill)
3660         .addImm(Offset);
3661     }
3662   }
3663 
3664   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3665   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3666   MachineInstr *InsertPt =
3667     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3668                                                   : AMDGPU::S_XOR_B64_term), Exec)
3669       .addReg(Exec)
3670       .addReg(NewExec);
3671 
3672   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3673   // s_cbranch_scc0?
3674 
3675   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3676   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3677     .addMBB(&LoopBB);
3678 
3679   return InsertPt->getIterator();
3680 }
3681 
3682 // This has slightly sub-optimal regalloc when the source vector is killed by
3683 // the read. The register allocator does not understand that the kill is
3684 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3685 // subregister from it, using 1 more VGPR than necessary. This was saved when
3686 // this was expanded after register allocation.
3687 static MachineBasicBlock::iterator
3688 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3689                unsigned InitResultReg, unsigned PhiReg, int Offset,
3690                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3691   MachineFunction *MF = MBB.getParent();
3692   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3693   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3694   MachineRegisterInfo &MRI = MF->getRegInfo();
3695   const DebugLoc &DL = MI.getDebugLoc();
3696   MachineBasicBlock::iterator I(&MI);
3697 
3698   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3699   Register DstReg = MI.getOperand(0).getReg();
3700   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3701   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3702   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3703   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3704 
3705   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3706 
3707   // Save the EXEC mask
3708   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3709     .addReg(Exec);
3710 
3711   MachineBasicBlock *LoopBB;
3712   MachineBasicBlock *RemainderBB;
3713   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3714 
3715   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3716 
3717   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3718                                       InitResultReg, DstReg, PhiReg, TmpExec,
3719                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3720 
3721   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3722   MachineFunction::iterator MBBI(LoopBB);
3723   ++MBBI;
3724   MF->insert(MBBI, LandingPad);
3725   LoopBB->removeSuccessor(RemainderBB);
3726   LandingPad->addSuccessor(RemainderBB);
3727   LoopBB->addSuccessor(LandingPad);
3728   MachineBasicBlock::iterator First = LandingPad->begin();
3729   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3730     .addReg(SaveExec);
3731 
3732   return InsPt;
3733 }
3734 
3735 // Returns subreg index, offset
3736 static std::pair<unsigned, int>
3737 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3738                             const TargetRegisterClass *SuperRC,
3739                             unsigned VecReg,
3740                             int Offset) {
3741   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3742 
3743   // Skip out of bounds offsets, or else we would end up using an undefined
3744   // register.
3745   if (Offset >= NumElts || Offset < 0)
3746     return std::make_pair(AMDGPU::sub0, Offset);
3747 
3748   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3749 }
3750 
3751 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3752                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3753                                  int Offset) {
3754   MachineBasicBlock *MBB = MI.getParent();
3755   const DebugLoc &DL = MI.getDebugLoc();
3756   MachineBasicBlock::iterator I(&MI);
3757 
3758   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3759 
3760   assert(Idx->getReg() != AMDGPU::NoRegister);
3761 
3762   if (Offset == 0) {
3763     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3764   } else {
3765     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3766         .add(*Idx)
3767         .addImm(Offset);
3768   }
3769 }
3770 
3771 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3772                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3773                                    int Offset) {
3774   MachineBasicBlock *MBB = MI.getParent();
3775   const DebugLoc &DL = MI.getDebugLoc();
3776   MachineBasicBlock::iterator I(&MI);
3777 
3778   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3779 
3780   if (Offset == 0)
3781     return Idx->getReg();
3782 
3783   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3784   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3785       .add(*Idx)
3786       .addImm(Offset);
3787   return Tmp;
3788 }
3789 
3790 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3791                                           MachineBasicBlock &MBB,
3792                                           const GCNSubtarget &ST) {
3793   const SIInstrInfo *TII = ST.getInstrInfo();
3794   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3795   MachineFunction *MF = MBB.getParent();
3796   MachineRegisterInfo &MRI = MF->getRegInfo();
3797 
3798   Register Dst = MI.getOperand(0).getReg();
3799   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3800   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3801   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3802 
3803   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3804   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3805 
3806   unsigned SubReg;
3807   std::tie(SubReg, Offset)
3808     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3809 
3810   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3811 
3812   // Check for a SGPR index.
3813   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3814     MachineBasicBlock::iterator I(&MI);
3815     const DebugLoc &DL = MI.getDebugLoc();
3816 
3817     if (UseGPRIdxMode) {
3818       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3819       // to avoid interfering with other uses, so probably requires a new
3820       // optimization pass.
3821       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3822 
3823       const MCInstrDesc &GPRIDXDesc =
3824           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3825       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3826           .addReg(SrcReg)
3827           .addReg(Idx)
3828           .addImm(SubReg);
3829     } else {
3830       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3831 
3832       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3833         .addReg(SrcReg, 0, SubReg)
3834         .addReg(SrcReg, RegState::Implicit);
3835     }
3836 
3837     MI.eraseFromParent();
3838 
3839     return &MBB;
3840   }
3841 
3842   // Control flow needs to be inserted if indexing with a VGPR.
3843   const DebugLoc &DL = MI.getDebugLoc();
3844   MachineBasicBlock::iterator I(&MI);
3845 
3846   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3847   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3848 
3849   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3850 
3851   Register SGPRIdxReg;
3852   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3853                               UseGPRIdxMode, SGPRIdxReg);
3854 
3855   MachineBasicBlock *LoopBB = InsPt->getParent();
3856 
3857   if (UseGPRIdxMode) {
3858     const MCInstrDesc &GPRIDXDesc =
3859         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3860 
3861     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3862         .addReg(SrcReg)
3863         .addReg(SGPRIdxReg)
3864         .addImm(SubReg);
3865   } else {
3866     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3867       .addReg(SrcReg, 0, SubReg)
3868       .addReg(SrcReg, RegState::Implicit);
3869   }
3870 
3871   MI.eraseFromParent();
3872 
3873   return LoopBB;
3874 }
3875 
3876 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3877                                           MachineBasicBlock &MBB,
3878                                           const GCNSubtarget &ST) {
3879   const SIInstrInfo *TII = ST.getInstrInfo();
3880   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3881   MachineFunction *MF = MBB.getParent();
3882   MachineRegisterInfo &MRI = MF->getRegInfo();
3883 
3884   Register Dst = MI.getOperand(0).getReg();
3885   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3886   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3887   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3888   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3889   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3890   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3891 
3892   // This can be an immediate, but will be folded later.
3893   assert(Val->getReg());
3894 
3895   unsigned SubReg;
3896   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3897                                                          SrcVec->getReg(),
3898                                                          Offset);
3899   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3900 
3901   if (Idx->getReg() == AMDGPU::NoRegister) {
3902     MachineBasicBlock::iterator I(&MI);
3903     const DebugLoc &DL = MI.getDebugLoc();
3904 
3905     assert(Offset == 0);
3906 
3907     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3908         .add(*SrcVec)
3909         .add(*Val)
3910         .addImm(SubReg);
3911 
3912     MI.eraseFromParent();
3913     return &MBB;
3914   }
3915 
3916   // Check for a SGPR index.
3917   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3918     MachineBasicBlock::iterator I(&MI);
3919     const DebugLoc &DL = MI.getDebugLoc();
3920 
3921     if (UseGPRIdxMode) {
3922       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3923 
3924       const MCInstrDesc &GPRIDXDesc =
3925           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3926       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3927           .addReg(SrcVec->getReg())
3928           .add(*Val)
3929           .addReg(Idx)
3930           .addImm(SubReg);
3931     } else {
3932       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3933 
3934       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3935           TRI.getRegSizeInBits(*VecRC), 32, false);
3936       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3937           .addReg(SrcVec->getReg())
3938           .add(*Val)
3939           .addImm(SubReg);
3940     }
3941     MI.eraseFromParent();
3942     return &MBB;
3943   }
3944 
3945   // Control flow needs to be inserted if indexing with a VGPR.
3946   if (Val->isReg())
3947     MRI.clearKillFlags(Val->getReg());
3948 
3949   const DebugLoc &DL = MI.getDebugLoc();
3950 
3951   Register PhiReg = MRI.createVirtualRegister(VecRC);
3952 
3953   Register SGPRIdxReg;
3954   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3955                               UseGPRIdxMode, SGPRIdxReg);
3956   MachineBasicBlock *LoopBB = InsPt->getParent();
3957 
3958   if (UseGPRIdxMode) {
3959     const MCInstrDesc &GPRIDXDesc =
3960         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3961 
3962     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3963         .addReg(PhiReg)
3964         .add(*Val)
3965         .addReg(SGPRIdxReg)
3966         .addImm(AMDGPU::sub0);
3967   } else {
3968     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3969         TRI.getRegSizeInBits(*VecRC), 32, false);
3970     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3971         .addReg(PhiReg)
3972         .add(*Val)
3973         .addImm(AMDGPU::sub0);
3974   }
3975 
3976   MI.eraseFromParent();
3977   return LoopBB;
3978 }
3979 
3980 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3981   MachineInstr &MI, MachineBasicBlock *BB) const {
3982 
3983   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3984   MachineFunction *MF = BB->getParent();
3985   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3986 
3987   switch (MI.getOpcode()) {
3988   case AMDGPU::S_UADDO_PSEUDO:
3989   case AMDGPU::S_USUBO_PSEUDO: {
3990     const DebugLoc &DL = MI.getDebugLoc();
3991     MachineOperand &Dest0 = MI.getOperand(0);
3992     MachineOperand &Dest1 = MI.getOperand(1);
3993     MachineOperand &Src0 = MI.getOperand(2);
3994     MachineOperand &Src1 = MI.getOperand(3);
3995 
3996     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3997                        ? AMDGPU::S_ADD_I32
3998                        : AMDGPU::S_SUB_I32;
3999     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4000 
4001     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4002         .addImm(1)
4003         .addImm(0);
4004 
4005     MI.eraseFromParent();
4006     return BB;
4007   }
4008   case AMDGPU::S_ADD_U64_PSEUDO:
4009   case AMDGPU::S_SUB_U64_PSEUDO: {
4010     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4011     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4012     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4013     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4014     const DebugLoc &DL = MI.getDebugLoc();
4015 
4016     MachineOperand &Dest = MI.getOperand(0);
4017     MachineOperand &Src0 = MI.getOperand(1);
4018     MachineOperand &Src1 = MI.getOperand(2);
4019 
4020     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4021     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4022 
4023     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4024         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4025     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4026         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4027 
4028     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4029         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4030     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4031         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4032 
4033     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4034 
4035     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4036     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4037     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4038     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4039     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4040         .addReg(DestSub0)
4041         .addImm(AMDGPU::sub0)
4042         .addReg(DestSub1)
4043         .addImm(AMDGPU::sub1);
4044     MI.eraseFromParent();
4045     return BB;
4046   }
4047   case AMDGPU::V_ADD_U64_PSEUDO:
4048   case AMDGPU::V_SUB_U64_PSEUDO: {
4049     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4050     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4051     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4052     const DebugLoc &DL = MI.getDebugLoc();
4053 
4054     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4055 
4056     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4057 
4058     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4059     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4060 
4061     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4062     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4063 
4064     MachineOperand &Dest = MI.getOperand(0);
4065     MachineOperand &Src0 = MI.getOperand(1);
4066     MachineOperand &Src1 = MI.getOperand(2);
4067 
4068     const TargetRegisterClass *Src0RC = Src0.isReg()
4069                                             ? MRI.getRegClass(Src0.getReg())
4070                                             : &AMDGPU::VReg_64RegClass;
4071     const TargetRegisterClass *Src1RC = Src1.isReg()
4072                                             ? MRI.getRegClass(Src1.getReg())
4073                                             : &AMDGPU::VReg_64RegClass;
4074 
4075     const TargetRegisterClass *Src0SubRC =
4076         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4077     const TargetRegisterClass *Src1SubRC =
4078         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4079 
4080     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4081         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4082     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4083         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4084 
4085     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4087     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4088         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4089 
4090     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4091     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4092                                .addReg(CarryReg, RegState::Define)
4093                                .add(SrcReg0Sub0)
4094                                .add(SrcReg1Sub0)
4095                                .addImm(0); // clamp bit
4096 
4097     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4098     MachineInstr *HiHalf =
4099         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4100             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4101             .add(SrcReg0Sub1)
4102             .add(SrcReg1Sub1)
4103             .addReg(CarryReg, RegState::Kill)
4104             .addImm(0); // clamp bit
4105 
4106     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4107         .addReg(DestSub0)
4108         .addImm(AMDGPU::sub0)
4109         .addReg(DestSub1)
4110         .addImm(AMDGPU::sub1);
4111     TII->legalizeOperands(*LoHalf);
4112     TII->legalizeOperands(*HiHalf);
4113     MI.eraseFromParent();
4114     return BB;
4115   }
4116   case AMDGPU::S_ADD_CO_PSEUDO:
4117   case AMDGPU::S_SUB_CO_PSEUDO: {
4118     // This pseudo has a chance to be selected
4119     // only from uniform add/subcarry node. All the VGPR operands
4120     // therefore assumed to be splat vectors.
4121     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4122     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4123     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4124     MachineBasicBlock::iterator MII = MI;
4125     const DebugLoc &DL = MI.getDebugLoc();
4126     MachineOperand &Dest = MI.getOperand(0);
4127     MachineOperand &CarryDest = MI.getOperand(1);
4128     MachineOperand &Src0 = MI.getOperand(2);
4129     MachineOperand &Src1 = MI.getOperand(3);
4130     MachineOperand &Src2 = MI.getOperand(4);
4131     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4132                        ? AMDGPU::S_ADDC_U32
4133                        : AMDGPU::S_SUBB_U32;
4134     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4135       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4136       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4137           .addReg(Src0.getReg());
4138       Src0.setReg(RegOp0);
4139     }
4140     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4141       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4142       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4143           .addReg(Src1.getReg());
4144       Src1.setReg(RegOp1);
4145     }
4146     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4147     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4148       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4149           .addReg(Src2.getReg());
4150       Src2.setReg(RegOp2);
4151     }
4152 
4153     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4154     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4155     assert(WaveSize == 64 || WaveSize == 32);
4156 
4157     if (WaveSize == 64) {
4158       if (ST.hasScalarCompareEq64()) {
4159         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4160             .addReg(Src2.getReg())
4161             .addImm(0);
4162       } else {
4163         const TargetRegisterClass *SubRC =
4164             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4165         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4166             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4167         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4168             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4169         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4170 
4171         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4172             .add(Src2Sub0)
4173             .add(Src2Sub1);
4174 
4175         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4176             .addReg(Src2_32, RegState::Kill)
4177             .addImm(0);
4178       }
4179     } else {
4180       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4181           .addReg(Src2.getReg())
4182           .addImm(0);
4183     }
4184 
4185     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4186 
4187     unsigned SelOpc =
4188         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4189 
4190     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4191         .addImm(-1)
4192         .addImm(0);
4193 
4194     MI.eraseFromParent();
4195     return BB;
4196   }
4197   case AMDGPU::SI_INIT_M0: {
4198     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4199             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4200         .add(MI.getOperand(0));
4201     MI.eraseFromParent();
4202     return BB;
4203   }
4204   case AMDGPU::GET_GROUPSTATICSIZE: {
4205     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4206            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4207     DebugLoc DL = MI.getDebugLoc();
4208     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4209         .add(MI.getOperand(0))
4210         .addImm(MFI->getLDSSize());
4211     MI.eraseFromParent();
4212     return BB;
4213   }
4214   case AMDGPU::SI_INDIRECT_SRC_V1:
4215   case AMDGPU::SI_INDIRECT_SRC_V2:
4216   case AMDGPU::SI_INDIRECT_SRC_V4:
4217   case AMDGPU::SI_INDIRECT_SRC_V8:
4218   case AMDGPU::SI_INDIRECT_SRC_V16:
4219   case AMDGPU::SI_INDIRECT_SRC_V32:
4220     return emitIndirectSrc(MI, *BB, *getSubtarget());
4221   case AMDGPU::SI_INDIRECT_DST_V1:
4222   case AMDGPU::SI_INDIRECT_DST_V2:
4223   case AMDGPU::SI_INDIRECT_DST_V4:
4224   case AMDGPU::SI_INDIRECT_DST_V8:
4225   case AMDGPU::SI_INDIRECT_DST_V16:
4226   case AMDGPU::SI_INDIRECT_DST_V32:
4227     return emitIndirectDst(MI, *BB, *getSubtarget());
4228   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4229   case AMDGPU::SI_KILL_I1_PSEUDO:
4230     return splitKillBlock(MI, BB);
4231   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4232     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4233     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4234     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4235 
4236     Register Dst = MI.getOperand(0).getReg();
4237     Register Src0 = MI.getOperand(1).getReg();
4238     Register Src1 = MI.getOperand(2).getReg();
4239     const DebugLoc &DL = MI.getDebugLoc();
4240     Register SrcCond = MI.getOperand(3).getReg();
4241 
4242     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4243     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4244     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4245     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4246 
4247     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4248       .addReg(SrcCond);
4249     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4250       .addImm(0)
4251       .addReg(Src0, 0, AMDGPU::sub0)
4252       .addImm(0)
4253       .addReg(Src1, 0, AMDGPU::sub0)
4254       .addReg(SrcCondCopy);
4255     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4256       .addImm(0)
4257       .addReg(Src0, 0, AMDGPU::sub1)
4258       .addImm(0)
4259       .addReg(Src1, 0, AMDGPU::sub1)
4260       .addReg(SrcCondCopy);
4261 
4262     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4263       .addReg(DstLo)
4264       .addImm(AMDGPU::sub0)
4265       .addReg(DstHi)
4266       .addImm(AMDGPU::sub1);
4267     MI.eraseFromParent();
4268     return BB;
4269   }
4270   case AMDGPU::SI_BR_UNDEF: {
4271     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4272     const DebugLoc &DL = MI.getDebugLoc();
4273     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4274                            .add(MI.getOperand(0));
4275     Br->getOperand(1).setIsUndef(true); // read undef SCC
4276     MI.eraseFromParent();
4277     return BB;
4278   }
4279   case AMDGPU::ADJCALLSTACKUP:
4280   case AMDGPU::ADJCALLSTACKDOWN: {
4281     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4282     MachineInstrBuilder MIB(*MF, &MI);
4283     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4284        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4285     return BB;
4286   }
4287   case AMDGPU::SI_CALL_ISEL: {
4288     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4289     const DebugLoc &DL = MI.getDebugLoc();
4290 
4291     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4292 
4293     MachineInstrBuilder MIB;
4294     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4295 
4296     for (const MachineOperand &MO : MI.operands())
4297       MIB.add(MO);
4298 
4299     MIB.cloneMemRefs(MI);
4300     MI.eraseFromParent();
4301     return BB;
4302   }
4303   case AMDGPU::V_ADD_CO_U32_e32:
4304   case AMDGPU::V_SUB_CO_U32_e32:
4305   case AMDGPU::V_SUBREV_CO_U32_e32: {
4306     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4307     const DebugLoc &DL = MI.getDebugLoc();
4308     unsigned Opc = MI.getOpcode();
4309 
4310     bool NeedClampOperand = false;
4311     if (TII->pseudoToMCOpcode(Opc) == -1) {
4312       Opc = AMDGPU::getVOPe64(Opc);
4313       NeedClampOperand = true;
4314     }
4315 
4316     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4317     if (TII->isVOP3(*I)) {
4318       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4319       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4320       I.addReg(TRI->getVCC(), RegState::Define);
4321     }
4322     I.add(MI.getOperand(1))
4323      .add(MI.getOperand(2));
4324     if (NeedClampOperand)
4325       I.addImm(0); // clamp bit for e64 encoding
4326 
4327     TII->legalizeOperands(*I);
4328 
4329     MI.eraseFromParent();
4330     return BB;
4331   }
4332   case AMDGPU::V_ADDC_U32_e32:
4333   case AMDGPU::V_SUBB_U32_e32:
4334   case AMDGPU::V_SUBBREV_U32_e32:
4335     // These instructions have an implicit use of vcc which counts towards the
4336     // constant bus limit.
4337     TII->legalizeOperands(MI);
4338     return BB;
4339   case AMDGPU::DS_GWS_INIT:
4340   case AMDGPU::DS_GWS_SEMA_BR:
4341   case AMDGPU::DS_GWS_BARRIER:
4342     if (Subtarget->needsAlignedVGPRs()) {
4343       // Add implicit aligned super-reg to force alignment on the data operand.
4344       const DebugLoc &DL = MI.getDebugLoc();
4345       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4346       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4347       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4348       Register DataReg = Op->getReg();
4349       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4350       Register Undef = MRI.createVirtualRegister(
4351           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4352       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4353       Register NewVR =
4354           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4355                                            : &AMDGPU::VReg_64_Align2RegClass);
4356       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4357           .addReg(DataReg, 0, Op->getSubReg())
4358           .addImm(AMDGPU::sub0)
4359           .addReg(Undef)
4360           .addImm(AMDGPU::sub1);
4361       Op->setReg(NewVR);
4362       Op->setSubReg(AMDGPU::sub0);
4363       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4364     }
4365     LLVM_FALLTHROUGH;
4366   case AMDGPU::DS_GWS_SEMA_V:
4367   case AMDGPU::DS_GWS_SEMA_P:
4368   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4369     // A s_waitcnt 0 is required to be the instruction immediately following.
4370     if (getSubtarget()->hasGWSAutoReplay()) {
4371       bundleInstWithWaitcnt(MI);
4372       return BB;
4373     }
4374 
4375     return emitGWSMemViolTestLoop(MI, BB);
4376   case AMDGPU::S_SETREG_B32: {
4377     // Try to optimize cases that only set the denormal mode or rounding mode.
4378     //
4379     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4380     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4381     // instead.
4382     //
4383     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4384     // allow you to have a no side effect instruction in the output of a
4385     // sideeffecting pattern.
4386     unsigned ID, Offset, Width;
4387     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4388     if (ID != AMDGPU::Hwreg::ID_MODE)
4389       return BB;
4390 
4391     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4392     const unsigned SetMask = WidthMask << Offset;
4393 
4394     if (getSubtarget()->hasDenormModeInst()) {
4395       unsigned SetDenormOp = 0;
4396       unsigned SetRoundOp = 0;
4397 
4398       // The dedicated instructions can only set the whole denorm or round mode
4399       // at once, not a subset of bits in either.
4400       if (SetMask ==
4401           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4402         // If this fully sets both the round and denorm mode, emit the two
4403         // dedicated instructions for these.
4404         SetRoundOp = AMDGPU::S_ROUND_MODE;
4405         SetDenormOp = AMDGPU::S_DENORM_MODE;
4406       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4407         SetRoundOp = AMDGPU::S_ROUND_MODE;
4408       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4409         SetDenormOp = AMDGPU::S_DENORM_MODE;
4410       }
4411 
4412       if (SetRoundOp || SetDenormOp) {
4413         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4414         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4415         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4416           unsigned ImmVal = Def->getOperand(1).getImm();
4417           if (SetRoundOp) {
4418             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4419                 .addImm(ImmVal & 0xf);
4420 
4421             // If we also have the denorm mode, get just the denorm mode bits.
4422             ImmVal >>= 4;
4423           }
4424 
4425           if (SetDenormOp) {
4426             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4427                 .addImm(ImmVal & 0xf);
4428           }
4429 
4430           MI.eraseFromParent();
4431           return BB;
4432         }
4433       }
4434     }
4435 
4436     // If only FP bits are touched, used the no side effects pseudo.
4437     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4438                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4439       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4440 
4441     return BB;
4442   }
4443   default:
4444     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4445   }
4446 }
4447 
4448 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4449   return isTypeLegal(VT.getScalarType());
4450 }
4451 
4452 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4453   // This currently forces unfolding various combinations of fsub into fma with
4454   // free fneg'd operands. As long as we have fast FMA (controlled by
4455   // isFMAFasterThanFMulAndFAdd), we should perform these.
4456 
4457   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4458   // most of these combines appear to be cycle neutral but save on instruction
4459   // count / code size.
4460   return true;
4461 }
4462 
4463 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4464 
4465 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4466                                          EVT VT) const {
4467   if (!VT.isVector()) {
4468     return MVT::i1;
4469   }
4470   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4471 }
4472 
4473 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4474   // TODO: Should i16 be used always if legal? For now it would force VALU
4475   // shifts.
4476   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4477 }
4478 
4479 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4480   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4481              ? Ty.changeElementSize(16)
4482              : Ty.changeElementSize(32);
4483 }
4484 
4485 // Answering this is somewhat tricky and depends on the specific device which
4486 // have different rates for fma or all f64 operations.
4487 //
4488 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4489 // regardless of which device (although the number of cycles differs between
4490 // devices), so it is always profitable for f64.
4491 //
4492 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4493 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4494 // which we can always do even without fused FP ops since it returns the same
4495 // result as the separate operations and since it is always full
4496 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4497 // however does not support denormals, so we do report fma as faster if we have
4498 // a fast fma device and require denormals.
4499 //
4500 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4501                                                   EVT VT) const {
4502   VT = VT.getScalarType();
4503 
4504   switch (VT.getSimpleVT().SimpleTy) {
4505   case MVT::f32: {
4506     // If mad is not available this depends only on if f32 fma is full rate.
4507     if (!Subtarget->hasMadMacF32Insts())
4508       return Subtarget->hasFastFMAF32();
4509 
4510     // Otherwise f32 mad is always full rate and returns the same result as
4511     // the separate operations so should be preferred over fma.
4512     // However does not support denomals.
4513     if (hasFP32Denormals(MF))
4514       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4515 
4516     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4517     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4518   }
4519   case MVT::f64:
4520     return true;
4521   case MVT::f16:
4522     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4523   default:
4524     break;
4525   }
4526 
4527   return false;
4528 }
4529 
4530 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4531                                                   LLT Ty) const {
4532   switch (Ty.getScalarSizeInBits()) {
4533   case 16:
4534     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4535   case 32:
4536     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4537   case 64:
4538     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4539   default:
4540     break;
4541   }
4542 
4543   return false;
4544 }
4545 
4546 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4547   if (!Ty.isScalar())
4548     return false;
4549 
4550   if (Ty.getScalarSizeInBits() == 16)
4551     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4552   if (Ty.getScalarSizeInBits() == 32)
4553     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4554 
4555   return false;
4556 }
4557 
4558 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4559                                    const SDNode *N) const {
4560   // TODO: Check future ftz flag
4561   // v_mad_f32/v_mac_f32 do not support denormals.
4562   EVT VT = N->getValueType(0);
4563   if (VT == MVT::f32)
4564     return Subtarget->hasMadMacF32Insts() &&
4565            !hasFP32Denormals(DAG.getMachineFunction());
4566   if (VT == MVT::f16) {
4567     return Subtarget->hasMadF16() &&
4568            !hasFP64FP16Denormals(DAG.getMachineFunction());
4569   }
4570 
4571   return false;
4572 }
4573 
4574 //===----------------------------------------------------------------------===//
4575 // Custom DAG Lowering Operations
4576 //===----------------------------------------------------------------------===//
4577 
4578 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4579 // wider vector type is legal.
4580 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4581                                              SelectionDAG &DAG) const {
4582   unsigned Opc = Op.getOpcode();
4583   EVT VT = Op.getValueType();
4584   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4585 
4586   SDValue Lo, Hi;
4587   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4588 
4589   SDLoc SL(Op);
4590   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4591                              Op->getFlags());
4592   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4593                              Op->getFlags());
4594 
4595   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4596 }
4597 
4598 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4599 // wider vector type is legal.
4600 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4601                                               SelectionDAG &DAG) const {
4602   unsigned Opc = Op.getOpcode();
4603   EVT VT = Op.getValueType();
4604   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4605          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4606 
4607   SDValue Lo0, Hi0;
4608   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4609   SDValue Lo1, Hi1;
4610   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4611 
4612   SDLoc SL(Op);
4613 
4614   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4615                              Op->getFlags());
4616   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4617                              Op->getFlags());
4618 
4619   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4620 }
4621 
4622 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4623                                               SelectionDAG &DAG) const {
4624   unsigned Opc = Op.getOpcode();
4625   EVT VT = Op.getValueType();
4626   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4627          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4628 
4629   SDValue Lo0, Hi0;
4630   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4631   SDValue Lo1, Hi1;
4632   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4633   SDValue Lo2, Hi2;
4634   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4635 
4636   SDLoc SL(Op);
4637 
4638   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4639                              Op->getFlags());
4640   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4641                              Op->getFlags());
4642 
4643   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4644 }
4645 
4646 
4647 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4648   switch (Op.getOpcode()) {
4649   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4650   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4651   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4652   case ISD::LOAD: {
4653     SDValue Result = LowerLOAD(Op, DAG);
4654     assert((!Result.getNode() ||
4655             Result.getNode()->getNumValues() == 2) &&
4656            "Load should return a value and a chain");
4657     return Result;
4658   }
4659 
4660   case ISD::FSIN:
4661   case ISD::FCOS:
4662     return LowerTrig(Op, DAG);
4663   case ISD::SELECT: return LowerSELECT(Op, DAG);
4664   case ISD::FDIV: return LowerFDIV(Op, DAG);
4665   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4666   case ISD::STORE: return LowerSTORE(Op, DAG);
4667   case ISD::GlobalAddress: {
4668     MachineFunction &MF = DAG.getMachineFunction();
4669     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4670     return LowerGlobalAddress(MFI, Op, DAG);
4671   }
4672   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4673   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4674   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4675   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4676   case ISD::INSERT_SUBVECTOR:
4677     return lowerINSERT_SUBVECTOR(Op, DAG);
4678   case ISD::INSERT_VECTOR_ELT:
4679     return lowerINSERT_VECTOR_ELT(Op, DAG);
4680   case ISD::EXTRACT_VECTOR_ELT:
4681     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4682   case ISD::VECTOR_SHUFFLE:
4683     return lowerVECTOR_SHUFFLE(Op, DAG);
4684   case ISD::BUILD_VECTOR:
4685     return lowerBUILD_VECTOR(Op, DAG);
4686   case ISD::FP_ROUND:
4687     return lowerFP_ROUND(Op, DAG);
4688   case ISD::TRAP:
4689     return lowerTRAP(Op, DAG);
4690   case ISD::DEBUGTRAP:
4691     return lowerDEBUGTRAP(Op, DAG);
4692   case ISD::FABS:
4693   case ISD::FNEG:
4694   case ISD::FCANONICALIZE:
4695   case ISD::BSWAP:
4696     return splitUnaryVectorOp(Op, DAG);
4697   case ISD::FMINNUM:
4698   case ISD::FMAXNUM:
4699     return lowerFMINNUM_FMAXNUM(Op, DAG);
4700   case ISD::FMA:
4701     return splitTernaryVectorOp(Op, DAG);
4702   case ISD::FP_TO_SINT:
4703   case ISD::FP_TO_UINT:
4704     return LowerFP_TO_INT(Op, DAG);
4705   case ISD::SHL:
4706   case ISD::SRA:
4707   case ISD::SRL:
4708   case ISD::ADD:
4709   case ISD::SUB:
4710   case ISD::MUL:
4711   case ISD::SMIN:
4712   case ISD::SMAX:
4713   case ISD::UMIN:
4714   case ISD::UMAX:
4715   case ISD::FADD:
4716   case ISD::FMUL:
4717   case ISD::FMINNUM_IEEE:
4718   case ISD::FMAXNUM_IEEE:
4719   case ISD::UADDSAT:
4720   case ISD::USUBSAT:
4721   case ISD::SADDSAT:
4722   case ISD::SSUBSAT:
4723     return splitBinaryVectorOp(Op, DAG);
4724   case ISD::SMULO:
4725   case ISD::UMULO:
4726     return lowerXMULO(Op, DAG);
4727   case ISD::SMUL_LOHI:
4728   case ISD::UMUL_LOHI:
4729     return lowerXMUL_LOHI(Op, DAG);
4730   case ISD::DYNAMIC_STACKALLOC:
4731     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4732   }
4733   return SDValue();
4734 }
4735 
4736 // Used for D16: Casts the result of an instruction into the right vector,
4737 // packs values if loads return unpacked values.
4738 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4739                                        const SDLoc &DL,
4740                                        SelectionDAG &DAG, bool Unpacked) {
4741   if (!LoadVT.isVector())
4742     return Result;
4743 
4744   // Cast back to the original packed type or to a larger type that is a
4745   // multiple of 32 bit for D16. Widening the return type is a required for
4746   // legalization.
4747   EVT FittingLoadVT = LoadVT;
4748   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4749     FittingLoadVT =
4750         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4751                          LoadVT.getVectorNumElements() + 1);
4752   }
4753 
4754   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4755     // Truncate to v2i16/v4i16.
4756     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4757 
4758     // Workaround legalizer not scalarizing truncate after vector op
4759     // legalization but not creating intermediate vector trunc.
4760     SmallVector<SDValue, 4> Elts;
4761     DAG.ExtractVectorElements(Result, Elts);
4762     for (SDValue &Elt : Elts)
4763       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4764 
4765     // Pad illegal v1i16/v3fi6 to v4i16
4766     if ((LoadVT.getVectorNumElements() % 2) == 1)
4767       Elts.push_back(DAG.getUNDEF(MVT::i16));
4768 
4769     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4770 
4771     // Bitcast to original type (v2f16/v4f16).
4772     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4773   }
4774 
4775   // Cast back to the original packed type.
4776   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4777 }
4778 
4779 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4780                                               MemSDNode *M,
4781                                               SelectionDAG &DAG,
4782                                               ArrayRef<SDValue> Ops,
4783                                               bool IsIntrinsic) const {
4784   SDLoc DL(M);
4785 
4786   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4787   EVT LoadVT = M->getValueType(0);
4788 
4789   EVT EquivLoadVT = LoadVT;
4790   if (LoadVT.isVector()) {
4791     if (Unpacked) {
4792       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4793                                      LoadVT.getVectorNumElements());
4794     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4795       // Widen v3f16 to legal type
4796       EquivLoadVT =
4797           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4798                            LoadVT.getVectorNumElements() + 1);
4799     }
4800   }
4801 
4802   // Change from v4f16/v2f16 to EquivLoadVT.
4803   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4804 
4805   SDValue Load
4806     = DAG.getMemIntrinsicNode(
4807       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4808       VTList, Ops, M->getMemoryVT(),
4809       M->getMemOperand());
4810 
4811   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4812 
4813   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4814 }
4815 
4816 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4817                                              SelectionDAG &DAG,
4818                                              ArrayRef<SDValue> Ops) const {
4819   SDLoc DL(M);
4820   EVT LoadVT = M->getValueType(0);
4821   EVT EltType = LoadVT.getScalarType();
4822   EVT IntVT = LoadVT.changeTypeToInteger();
4823 
4824   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4825 
4826   unsigned Opc =
4827       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4828 
4829   if (IsD16) {
4830     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4831   }
4832 
4833   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4834   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4835     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4836 
4837   if (isTypeLegal(LoadVT)) {
4838     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4839                                M->getMemOperand(), DAG);
4840   }
4841 
4842   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4843   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4844   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4845                                         M->getMemOperand(), DAG);
4846   return DAG.getMergeValues(
4847       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4848       DL);
4849 }
4850 
4851 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4852                                   SDNode *N, SelectionDAG &DAG) {
4853   EVT VT = N->getValueType(0);
4854   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4855   unsigned CondCode = CD->getZExtValue();
4856   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4857     return DAG.getUNDEF(VT);
4858 
4859   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4860 
4861   SDValue LHS = N->getOperand(1);
4862   SDValue RHS = N->getOperand(2);
4863 
4864   SDLoc DL(N);
4865 
4866   EVT CmpVT = LHS.getValueType();
4867   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4868     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4869       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4870     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4871     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4872   }
4873 
4874   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4875 
4876   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4877   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4878 
4879   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4880                               DAG.getCondCode(CCOpcode));
4881   if (VT.bitsEq(CCVT))
4882     return SetCC;
4883   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4884 }
4885 
4886 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4887                                   SDNode *N, SelectionDAG &DAG) {
4888   EVT VT = N->getValueType(0);
4889   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4890 
4891   unsigned CondCode = CD->getZExtValue();
4892   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4893     return DAG.getUNDEF(VT);
4894 
4895   SDValue Src0 = N->getOperand(1);
4896   SDValue Src1 = N->getOperand(2);
4897   EVT CmpVT = Src0.getValueType();
4898   SDLoc SL(N);
4899 
4900   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4901     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4902     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4903   }
4904 
4905   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4906   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4907   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4908   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4909   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4910                               Src1, DAG.getCondCode(CCOpcode));
4911   if (VT.bitsEq(CCVT))
4912     return SetCC;
4913   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4914 }
4915 
4916 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4917                                     SelectionDAG &DAG) {
4918   EVT VT = N->getValueType(0);
4919   SDValue Src = N->getOperand(1);
4920   SDLoc SL(N);
4921 
4922   if (Src.getOpcode() == ISD::SETCC) {
4923     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4924     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4925                        Src.getOperand(1), Src.getOperand(2));
4926   }
4927   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4928     // (ballot 0) -> 0
4929     if (Arg->isZero())
4930       return DAG.getConstant(0, SL, VT);
4931 
4932     // (ballot 1) -> EXEC/EXEC_LO
4933     if (Arg->isOne()) {
4934       Register Exec;
4935       if (VT.getScalarSizeInBits() == 32)
4936         Exec = AMDGPU::EXEC_LO;
4937       else if (VT.getScalarSizeInBits() == 64)
4938         Exec = AMDGPU::EXEC;
4939       else
4940         return SDValue();
4941 
4942       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4943     }
4944   }
4945 
4946   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4947   // ISD::SETNE)
4948   return DAG.getNode(
4949       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4950       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4951 }
4952 
4953 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4954                                           SmallVectorImpl<SDValue> &Results,
4955                                           SelectionDAG &DAG) const {
4956   switch (N->getOpcode()) {
4957   case ISD::INSERT_VECTOR_ELT: {
4958     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4959       Results.push_back(Res);
4960     return;
4961   }
4962   case ISD::EXTRACT_VECTOR_ELT: {
4963     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4964       Results.push_back(Res);
4965     return;
4966   }
4967   case ISD::INTRINSIC_WO_CHAIN: {
4968     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4969     switch (IID) {
4970     case Intrinsic::amdgcn_cvt_pkrtz: {
4971       SDValue Src0 = N->getOperand(1);
4972       SDValue Src1 = N->getOperand(2);
4973       SDLoc SL(N);
4974       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4975                                 Src0, Src1);
4976       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4977       return;
4978     }
4979     case Intrinsic::amdgcn_cvt_pknorm_i16:
4980     case Intrinsic::amdgcn_cvt_pknorm_u16:
4981     case Intrinsic::amdgcn_cvt_pk_i16:
4982     case Intrinsic::amdgcn_cvt_pk_u16: {
4983       SDValue Src0 = N->getOperand(1);
4984       SDValue Src1 = N->getOperand(2);
4985       SDLoc SL(N);
4986       unsigned Opcode;
4987 
4988       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4989         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4990       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4991         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4992       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4993         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4994       else
4995         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4996 
4997       EVT VT = N->getValueType(0);
4998       if (isTypeLegal(VT))
4999         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5000       else {
5001         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5002         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5003       }
5004       return;
5005     }
5006     }
5007     break;
5008   }
5009   case ISD::INTRINSIC_W_CHAIN: {
5010     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5011       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5012         // FIXME: Hacky
5013         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5014           Results.push_back(Res.getOperand(I));
5015         }
5016       } else {
5017         Results.push_back(Res);
5018         Results.push_back(Res.getValue(1));
5019       }
5020       return;
5021     }
5022 
5023     break;
5024   }
5025   case ISD::SELECT: {
5026     SDLoc SL(N);
5027     EVT VT = N->getValueType(0);
5028     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5029     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5030     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5031 
5032     EVT SelectVT = NewVT;
5033     if (NewVT.bitsLT(MVT::i32)) {
5034       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5035       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5036       SelectVT = MVT::i32;
5037     }
5038 
5039     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5040                                     N->getOperand(0), LHS, RHS);
5041 
5042     if (NewVT != SelectVT)
5043       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5044     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5045     return;
5046   }
5047   case ISD::FNEG: {
5048     if (N->getValueType(0) != MVT::v2f16)
5049       break;
5050 
5051     SDLoc SL(N);
5052     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5053 
5054     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5055                              BC,
5056                              DAG.getConstant(0x80008000, SL, MVT::i32));
5057     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5058     return;
5059   }
5060   case ISD::FABS: {
5061     if (N->getValueType(0) != MVT::v2f16)
5062       break;
5063 
5064     SDLoc SL(N);
5065     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5066 
5067     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5068                              BC,
5069                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5070     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5071     return;
5072   }
5073   default:
5074     break;
5075   }
5076 }
5077 
5078 /// Helper function for LowerBRCOND
5079 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5080 
5081   SDNode *Parent = Value.getNode();
5082   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5083        I != E; ++I) {
5084 
5085     if (I.getUse().get() != Value)
5086       continue;
5087 
5088     if (I->getOpcode() == Opcode)
5089       return *I;
5090   }
5091   return nullptr;
5092 }
5093 
5094 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5095   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5096     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5097     case Intrinsic::amdgcn_if:
5098       return AMDGPUISD::IF;
5099     case Intrinsic::amdgcn_else:
5100       return AMDGPUISD::ELSE;
5101     case Intrinsic::amdgcn_loop:
5102       return AMDGPUISD::LOOP;
5103     case Intrinsic::amdgcn_end_cf:
5104       llvm_unreachable("should not occur");
5105     default:
5106       return 0;
5107     }
5108   }
5109 
5110   // break, if_break, else_break are all only used as inputs to loop, not
5111   // directly as branch conditions.
5112   return 0;
5113 }
5114 
5115 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5116   const Triple &TT = getTargetMachine().getTargetTriple();
5117   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5118           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5119          AMDGPU::shouldEmitConstantsToTextSection(TT);
5120 }
5121 
5122 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5123   // FIXME: Either avoid relying on address space here or change the default
5124   // address space for functions to avoid the explicit check.
5125   return (GV->getValueType()->isFunctionTy() ||
5126           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5127          !shouldEmitFixup(GV) &&
5128          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5129 }
5130 
5131 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5132   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5133 }
5134 
5135 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5136   if (!GV->hasExternalLinkage())
5137     return true;
5138 
5139   const auto OS = getTargetMachine().getTargetTriple().getOS();
5140   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5141 }
5142 
5143 /// This transforms the control flow intrinsics to get the branch destination as
5144 /// last parameter, also switches branch target with BR if the need arise
5145 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5146                                       SelectionDAG &DAG) const {
5147   SDLoc DL(BRCOND);
5148 
5149   SDNode *Intr = BRCOND.getOperand(1).getNode();
5150   SDValue Target = BRCOND.getOperand(2);
5151   SDNode *BR = nullptr;
5152   SDNode *SetCC = nullptr;
5153 
5154   if (Intr->getOpcode() == ISD::SETCC) {
5155     // As long as we negate the condition everything is fine
5156     SetCC = Intr;
5157     Intr = SetCC->getOperand(0).getNode();
5158 
5159   } else {
5160     // Get the target from BR if we don't negate the condition
5161     BR = findUser(BRCOND, ISD::BR);
5162     assert(BR && "brcond missing unconditional branch user");
5163     Target = BR->getOperand(1);
5164   }
5165 
5166   unsigned CFNode = isCFIntrinsic(Intr);
5167   if (CFNode == 0) {
5168     // This is a uniform branch so we don't need to legalize.
5169     return BRCOND;
5170   }
5171 
5172   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5173                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5174 
5175   assert(!SetCC ||
5176         (SetCC->getConstantOperandVal(1) == 1 &&
5177          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5178                                                              ISD::SETNE));
5179 
5180   // operands of the new intrinsic call
5181   SmallVector<SDValue, 4> Ops;
5182   if (HaveChain)
5183     Ops.push_back(BRCOND.getOperand(0));
5184 
5185   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5186   Ops.push_back(Target);
5187 
5188   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5189 
5190   // build the new intrinsic call
5191   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5192 
5193   if (!HaveChain) {
5194     SDValue Ops[] =  {
5195       SDValue(Result, 0),
5196       BRCOND.getOperand(0)
5197     };
5198 
5199     Result = DAG.getMergeValues(Ops, DL).getNode();
5200   }
5201 
5202   if (BR) {
5203     // Give the branch instruction our target
5204     SDValue Ops[] = {
5205       BR->getOperand(0),
5206       BRCOND.getOperand(2)
5207     };
5208     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5209     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5210   }
5211 
5212   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5213 
5214   // Copy the intrinsic results to registers
5215   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5216     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5217     if (!CopyToReg)
5218       continue;
5219 
5220     Chain = DAG.getCopyToReg(
5221       Chain, DL,
5222       CopyToReg->getOperand(1),
5223       SDValue(Result, i - 1),
5224       SDValue());
5225 
5226     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5227   }
5228 
5229   // Remove the old intrinsic from the chain
5230   DAG.ReplaceAllUsesOfValueWith(
5231     SDValue(Intr, Intr->getNumValues() - 1),
5232     Intr->getOperand(0));
5233 
5234   return Chain;
5235 }
5236 
5237 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5238                                           SelectionDAG &DAG) const {
5239   MVT VT = Op.getSimpleValueType();
5240   SDLoc DL(Op);
5241   // Checking the depth
5242   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5243     return DAG.getConstant(0, DL, VT);
5244 
5245   MachineFunction &MF = DAG.getMachineFunction();
5246   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5247   // Check for kernel and shader functions
5248   if (Info->isEntryFunction())
5249     return DAG.getConstant(0, DL, VT);
5250 
5251   MachineFrameInfo &MFI = MF.getFrameInfo();
5252   // There is a call to @llvm.returnaddress in this function
5253   MFI.setReturnAddressIsTaken(true);
5254 
5255   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5256   // Get the return address reg and mark it as an implicit live-in
5257   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5258 
5259   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5260 }
5261 
5262 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5263                                             SDValue Op,
5264                                             const SDLoc &DL,
5265                                             EVT VT) const {
5266   return Op.getValueType().bitsLE(VT) ?
5267       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5268     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5269                 DAG.getTargetConstant(0, DL, MVT::i32));
5270 }
5271 
5272 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5273   assert(Op.getValueType() == MVT::f16 &&
5274          "Do not know how to custom lower FP_ROUND for non-f16 type");
5275 
5276   SDValue Src = Op.getOperand(0);
5277   EVT SrcVT = Src.getValueType();
5278   if (SrcVT != MVT::f64)
5279     return Op;
5280 
5281   SDLoc DL(Op);
5282 
5283   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5284   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5285   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5286 }
5287 
5288 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5289                                                SelectionDAG &DAG) const {
5290   EVT VT = Op.getValueType();
5291   const MachineFunction &MF = DAG.getMachineFunction();
5292   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5293   bool IsIEEEMode = Info->getMode().IEEE;
5294 
5295   // FIXME: Assert during selection that this is only selected for
5296   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5297   // mode functions, but this happens to be OK since it's only done in cases
5298   // where there is known no sNaN.
5299   if (IsIEEEMode)
5300     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5301 
5302   if (VT == MVT::v4f16)
5303     return splitBinaryVectorOp(Op, DAG);
5304   return Op;
5305 }
5306 
5307 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5308   EVT VT = Op.getValueType();
5309   SDLoc SL(Op);
5310   SDValue LHS = Op.getOperand(0);
5311   SDValue RHS = Op.getOperand(1);
5312   bool isSigned = Op.getOpcode() == ISD::SMULO;
5313 
5314   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5315     const APInt &C = RHSC->getAPIntValue();
5316     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5317     if (C.isPowerOf2()) {
5318       // smulo(x, signed_min) is same as umulo(x, signed_min).
5319       bool UseArithShift = isSigned && !C.isMinSignedValue();
5320       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5321       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5322       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5323           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5324                       SL, VT, Result, ShiftAmt),
5325           LHS, ISD::SETNE);
5326       return DAG.getMergeValues({ Result, Overflow }, SL);
5327     }
5328   }
5329 
5330   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5331   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5332                             SL, VT, LHS, RHS);
5333 
5334   SDValue Sign = isSigned
5335     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5336                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5337     : DAG.getConstant(0, SL, VT);
5338   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5339 
5340   return DAG.getMergeValues({ Result, Overflow }, SL);
5341 }
5342 
5343 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5344   if (Op->isDivergent()) {
5345     // Select to V_MAD_[IU]64_[IU]32.
5346     return Op;
5347   }
5348   if (Subtarget->hasSMulHi()) {
5349     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5350     return SDValue();
5351   }
5352   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5353   // calculate the high part, so we might as well do the whole thing with
5354   // V_MAD_[IU]64_[IU]32.
5355   return Op;
5356 }
5357 
5358 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5359   if (!Subtarget->isTrapHandlerEnabled() ||
5360       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5361     return lowerTrapEndpgm(Op, DAG);
5362 
5363   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5364     switch (*HsaAbiVer) {
5365     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5366     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5367       return lowerTrapHsaQueuePtr(Op, DAG);
5368     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5369       return Subtarget->supportsGetDoorbellID() ?
5370           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5371     }
5372   }
5373 
5374   llvm_unreachable("Unknown trap handler");
5375 }
5376 
5377 SDValue SITargetLowering::lowerTrapEndpgm(
5378     SDValue Op, SelectionDAG &DAG) const {
5379   SDLoc SL(Op);
5380   SDValue Chain = Op.getOperand(0);
5381   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5382 }
5383 
5384 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5385     SDValue Op, SelectionDAG &DAG) const {
5386   SDLoc SL(Op);
5387   SDValue Chain = Op.getOperand(0);
5388 
5389   MachineFunction &MF = DAG.getMachineFunction();
5390   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5391   Register UserSGPR = Info->getQueuePtrUserSGPR();
5392 
5393   SDValue QueuePtr;
5394   if (UserSGPR == AMDGPU::NoRegister) {
5395     // We probably are in a function incorrectly marked with
5396     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5397     // so just use a null pointer.
5398     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5399   } else {
5400     QueuePtr = CreateLiveInRegister(
5401       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5402   }
5403 
5404   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5405   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5406                                    QueuePtr, SDValue());
5407 
5408   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5409   SDValue Ops[] = {
5410     ToReg,
5411     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5412     SGPR01,
5413     ToReg.getValue(1)
5414   };
5415   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5416 }
5417 
5418 SDValue SITargetLowering::lowerTrapHsa(
5419     SDValue Op, SelectionDAG &DAG) const {
5420   SDLoc SL(Op);
5421   SDValue Chain = Op.getOperand(0);
5422 
5423   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5424   SDValue Ops[] = {
5425     Chain,
5426     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5427   };
5428   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5429 }
5430 
5431 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5432   SDLoc SL(Op);
5433   SDValue Chain = Op.getOperand(0);
5434   MachineFunction &MF = DAG.getMachineFunction();
5435 
5436   if (!Subtarget->isTrapHandlerEnabled() ||
5437       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5438     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5439                                      "debugtrap handler not supported",
5440                                      Op.getDebugLoc(),
5441                                      DS_Warning);
5442     LLVMContext &Ctx = MF.getFunction().getContext();
5443     Ctx.diagnose(NoTrap);
5444     return Chain;
5445   }
5446 
5447   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5448   SDValue Ops[] = {
5449     Chain,
5450     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5451   };
5452   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5453 }
5454 
5455 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5456                                              SelectionDAG &DAG) const {
5457   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5458   if (Subtarget->hasApertureRegs()) {
5459     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5460         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5461         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5462     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5463         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5464         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5465     unsigned Encoding =
5466         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5467         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5468         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5469 
5470     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5471     SDValue ApertureReg = SDValue(
5472         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5473     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5474     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5475   }
5476 
5477   MachineFunction &MF = DAG.getMachineFunction();
5478   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5479   Register UserSGPR = Info->getQueuePtrUserSGPR();
5480   if (UserSGPR == AMDGPU::NoRegister) {
5481     // We probably are in a function incorrectly marked with
5482     // amdgpu-no-queue-ptr. This is undefined.
5483     return DAG.getUNDEF(MVT::i32);
5484   }
5485 
5486   SDValue QueuePtr = CreateLiveInRegister(
5487     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5488 
5489   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5490   // private_segment_aperture_base_hi.
5491   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5492 
5493   SDValue Ptr =
5494       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5495 
5496   // TODO: Use custom target PseudoSourceValue.
5497   // TODO: We should use the value from the IR intrinsic call, but it might not
5498   // be available and how do we get it?
5499   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5500   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5501                      commonAlignment(Align(64), StructOffset),
5502                      MachineMemOperand::MODereferenceable |
5503                          MachineMemOperand::MOInvariant);
5504 }
5505 
5506 /// Return true if the value is a known valid address, such that a null check is
5507 /// not necessary.
5508 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5509                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5510   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5511       isa<BasicBlockSDNode>(Val))
5512     return true;
5513 
5514   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5515     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5516 
5517   // TODO: Search through arithmetic, handle arguments and loads
5518   // marked nonnull.
5519   return false;
5520 }
5521 
5522 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5523                                              SelectionDAG &DAG) const {
5524   SDLoc SL(Op);
5525   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5526 
5527   SDValue Src = ASC->getOperand(0);
5528   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5529   unsigned SrcAS = ASC->getSrcAddressSpace();
5530 
5531   const AMDGPUTargetMachine &TM =
5532     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5533 
5534   // flat -> local/private
5535   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5536     unsigned DestAS = ASC->getDestAddressSpace();
5537 
5538     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5539         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5540       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5541 
5542       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5543         return Ptr;
5544 
5545       unsigned NullVal = TM.getNullPointerValue(DestAS);
5546       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5547       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5548 
5549       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5550                          SegmentNullPtr);
5551     }
5552   }
5553 
5554   // local/private -> flat
5555   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5556     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5557         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5558 
5559       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5560       SDValue CvtPtr =
5561           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5562       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5563 
5564       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5565         return CvtPtr;
5566 
5567       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5568       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5569 
5570       SDValue NonNull
5571         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5572 
5573       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5574                          FlatNullPtr);
5575     }
5576   }
5577 
5578   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5579       Src.getValueType() == MVT::i64)
5580     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5581 
5582   // global <-> flat are no-ops and never emitted.
5583 
5584   const MachineFunction &MF = DAG.getMachineFunction();
5585   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5586     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5587   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5588 
5589   return DAG.getUNDEF(ASC->getValueType(0));
5590 }
5591 
5592 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5593 // the small vector and inserting them into the big vector. That is better than
5594 // the default expansion of doing it via a stack slot. Even though the use of
5595 // the stack slot would be optimized away afterwards, the stack slot itself
5596 // remains.
5597 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5598                                                 SelectionDAG &DAG) const {
5599   SDValue Vec = Op.getOperand(0);
5600   SDValue Ins = Op.getOperand(1);
5601   SDValue Idx = Op.getOperand(2);
5602   EVT VecVT = Vec.getValueType();
5603   EVT InsVT = Ins.getValueType();
5604   EVT EltVT = VecVT.getVectorElementType();
5605   unsigned InsNumElts = InsVT.getVectorNumElements();
5606   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5607   SDLoc SL(Op);
5608 
5609   for (unsigned I = 0; I != InsNumElts; ++I) {
5610     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5611                               DAG.getConstant(I, SL, MVT::i32));
5612     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5613                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5614   }
5615   return Vec;
5616 }
5617 
5618 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5619                                                  SelectionDAG &DAG) const {
5620   SDValue Vec = Op.getOperand(0);
5621   SDValue InsVal = Op.getOperand(1);
5622   SDValue Idx = Op.getOperand(2);
5623   EVT VecVT = Vec.getValueType();
5624   EVT EltVT = VecVT.getVectorElementType();
5625   unsigned VecSize = VecVT.getSizeInBits();
5626   unsigned EltSize = EltVT.getSizeInBits();
5627 
5628 
5629   assert(VecSize <= 64);
5630 
5631   unsigned NumElts = VecVT.getVectorNumElements();
5632   SDLoc SL(Op);
5633   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5634 
5635   if (NumElts == 4 && EltSize == 16 && KIdx) {
5636     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5637 
5638     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5639                                  DAG.getConstant(0, SL, MVT::i32));
5640     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5641                                  DAG.getConstant(1, SL, MVT::i32));
5642 
5643     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5644     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5645 
5646     unsigned Idx = KIdx->getZExtValue();
5647     bool InsertLo = Idx < 2;
5648     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5649       InsertLo ? LoVec : HiVec,
5650       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5651       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5652 
5653     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5654 
5655     SDValue Concat = InsertLo ?
5656       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5657       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5658 
5659     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5660   }
5661 
5662   if (isa<ConstantSDNode>(Idx))
5663     return SDValue();
5664 
5665   MVT IntVT = MVT::getIntegerVT(VecSize);
5666 
5667   // Avoid stack access for dynamic indexing.
5668   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5669 
5670   // Create a congruent vector with the target value in each element so that
5671   // the required element can be masked and ORed into the target vector.
5672   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5673                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5674 
5675   assert(isPowerOf2_32(EltSize));
5676   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5677 
5678   // Convert vector index to bit-index.
5679   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5680 
5681   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5682   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5683                             DAG.getConstant(0xffff, SL, IntVT),
5684                             ScaledIdx);
5685 
5686   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5687   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5688                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5689 
5690   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5691   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5692 }
5693 
5694 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5695                                                   SelectionDAG &DAG) const {
5696   SDLoc SL(Op);
5697 
5698   EVT ResultVT = Op.getValueType();
5699   SDValue Vec = Op.getOperand(0);
5700   SDValue Idx = Op.getOperand(1);
5701   EVT VecVT = Vec.getValueType();
5702   unsigned VecSize = VecVT.getSizeInBits();
5703   EVT EltVT = VecVT.getVectorElementType();
5704   assert(VecSize <= 64);
5705 
5706   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5707 
5708   // Make sure we do any optimizations that will make it easier to fold
5709   // source modifiers before obscuring it with bit operations.
5710 
5711   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5712   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5713     return Combined;
5714 
5715   unsigned EltSize = EltVT.getSizeInBits();
5716   assert(isPowerOf2_32(EltSize));
5717 
5718   MVT IntVT = MVT::getIntegerVT(VecSize);
5719   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5720 
5721   // Convert vector index to bit-index (* EltSize)
5722   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5723 
5724   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5725   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5726 
5727   if (ResultVT == MVT::f16) {
5728     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5729     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5730   }
5731 
5732   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5733 }
5734 
5735 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5736   assert(Elt % 2 == 0);
5737   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5738 }
5739 
5740 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5741                                               SelectionDAG &DAG) const {
5742   SDLoc SL(Op);
5743   EVT ResultVT = Op.getValueType();
5744   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5745 
5746   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5747   EVT EltVT = PackVT.getVectorElementType();
5748   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5749 
5750   // vector_shuffle <0,1,6,7> lhs, rhs
5751   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5752   //
5753   // vector_shuffle <6,7,2,3> lhs, rhs
5754   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5755   //
5756   // vector_shuffle <6,7,0,1> lhs, rhs
5757   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5758 
5759   // Avoid scalarizing when both halves are reading from consecutive elements.
5760   SmallVector<SDValue, 4> Pieces;
5761   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5762     if (elementPairIsContiguous(SVN->getMask(), I)) {
5763       const int Idx = SVN->getMaskElt(I);
5764       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5765       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5766       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5767                                     PackVT, SVN->getOperand(VecIdx),
5768                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5769       Pieces.push_back(SubVec);
5770     } else {
5771       const int Idx0 = SVN->getMaskElt(I);
5772       const int Idx1 = SVN->getMaskElt(I + 1);
5773       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5774       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5775       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5776       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5777 
5778       SDValue Vec0 = SVN->getOperand(VecIdx0);
5779       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5780                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5781 
5782       SDValue Vec1 = SVN->getOperand(VecIdx1);
5783       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5784                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5785       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5786     }
5787   }
5788 
5789   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5790 }
5791 
5792 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5793                                             SelectionDAG &DAG) const {
5794   SDLoc SL(Op);
5795   EVT VT = Op.getValueType();
5796 
5797   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5798     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5799 
5800     // Turn into pair of packed build_vectors.
5801     // TODO: Special case for constants that can be materialized with s_mov_b64.
5802     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5803                                     { Op.getOperand(0), Op.getOperand(1) });
5804     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5805                                     { Op.getOperand(2), Op.getOperand(3) });
5806 
5807     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5808     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5809 
5810     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5811     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5812   }
5813 
5814   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5815   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5816 
5817   SDValue Lo = Op.getOperand(0);
5818   SDValue Hi = Op.getOperand(1);
5819 
5820   // Avoid adding defined bits with the zero_extend.
5821   if (Hi.isUndef()) {
5822     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5823     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5824     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5825   }
5826 
5827   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5828   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5829 
5830   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5831                               DAG.getConstant(16, SL, MVT::i32));
5832   if (Lo.isUndef())
5833     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5834 
5835   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5836   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5837 
5838   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5839   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5840 }
5841 
5842 bool
5843 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5844   // We can fold offsets for anything that doesn't require a GOT relocation.
5845   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5846           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5847           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5848          !shouldEmitGOTReloc(GA->getGlobal());
5849 }
5850 
5851 static SDValue
5852 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5853                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5854                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5855   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5856   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5857   // lowered to the following code sequence:
5858   //
5859   // For constant address space:
5860   //   s_getpc_b64 s[0:1]
5861   //   s_add_u32 s0, s0, $symbol
5862   //   s_addc_u32 s1, s1, 0
5863   //
5864   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5865   //   a fixup or relocation is emitted to replace $symbol with a literal
5866   //   constant, which is a pc-relative offset from the encoding of the $symbol
5867   //   operand to the global variable.
5868   //
5869   // For global address space:
5870   //   s_getpc_b64 s[0:1]
5871   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5872   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5873   //
5874   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5875   //   fixups or relocations are emitted to replace $symbol@*@lo and
5876   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5877   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5878   //   operand to the global variable.
5879   //
5880   // What we want here is an offset from the value returned by s_getpc
5881   // (which is the address of the s_add_u32 instruction) to the global
5882   // variable, but since the encoding of $symbol starts 4 bytes after the start
5883   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5884   // small. This requires us to add 4 to the global variable offset in order to
5885   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5886   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5887   // instruction.
5888   SDValue PtrLo =
5889       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5890   SDValue PtrHi;
5891   if (GAFlags == SIInstrInfo::MO_NONE) {
5892     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5893   } else {
5894     PtrHi =
5895         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5896   }
5897   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5898 }
5899 
5900 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5901                                              SDValue Op,
5902                                              SelectionDAG &DAG) const {
5903   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5904   SDLoc DL(GSD);
5905   EVT PtrVT = Op.getValueType();
5906 
5907   const GlobalValue *GV = GSD->getGlobal();
5908   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5909        shouldUseLDSConstAddress(GV)) ||
5910       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5911       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5912     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5913         GV->hasExternalLinkage()) {
5914       Type *Ty = GV->getValueType();
5915       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5916       // zero-sized type in other languages to declare the dynamic shared
5917       // memory which size is not known at the compile time. They will be
5918       // allocated by the runtime and placed directly after the static
5919       // allocated ones. They all share the same offset.
5920       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5921         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5922         // Adjust alignment for that dynamic shared memory array.
5923         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5924         return SDValue(
5925             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5926       }
5927     }
5928     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5929   }
5930 
5931   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5932     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5933                                             SIInstrInfo::MO_ABS32_LO);
5934     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5935   }
5936 
5937   if (shouldEmitFixup(GV))
5938     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5939   else if (shouldEmitPCReloc(GV))
5940     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5941                                    SIInstrInfo::MO_REL32);
5942 
5943   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5944                                             SIInstrInfo::MO_GOTPCREL32);
5945 
5946   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5947   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5948   const DataLayout &DataLayout = DAG.getDataLayout();
5949   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5950   MachinePointerInfo PtrInfo
5951     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5952 
5953   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5954                      MachineMemOperand::MODereferenceable |
5955                          MachineMemOperand::MOInvariant);
5956 }
5957 
5958 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5959                                    const SDLoc &DL, SDValue V) const {
5960   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5961   // the destination register.
5962   //
5963   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5964   // so we will end up with redundant moves to m0.
5965   //
5966   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5967 
5968   // A Null SDValue creates a glue result.
5969   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5970                                   V, Chain);
5971   return SDValue(M0, 0);
5972 }
5973 
5974 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5975                                                  SDValue Op,
5976                                                  MVT VT,
5977                                                  unsigned Offset) const {
5978   SDLoc SL(Op);
5979   SDValue Param = lowerKernargMemParameter(
5980       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5981   // The local size values will have the hi 16-bits as zero.
5982   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5983                      DAG.getValueType(VT));
5984 }
5985 
5986 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5987                                         EVT VT) {
5988   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5989                                       "non-hsa intrinsic with hsa target",
5990                                       DL.getDebugLoc());
5991   DAG.getContext()->diagnose(BadIntrin);
5992   return DAG.getUNDEF(VT);
5993 }
5994 
5995 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5996                                          EVT VT) {
5997   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5998                                       "intrinsic not supported on subtarget",
5999                                       DL.getDebugLoc());
6000   DAG.getContext()->diagnose(BadIntrin);
6001   return DAG.getUNDEF(VT);
6002 }
6003 
6004 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6005                                     ArrayRef<SDValue> Elts) {
6006   assert(!Elts.empty());
6007   MVT Type;
6008   unsigned NumElts = Elts.size();
6009 
6010   if (NumElts <= 8) {
6011     Type = MVT::getVectorVT(MVT::f32, NumElts);
6012   } else {
6013     assert(Elts.size() <= 16);
6014     Type = MVT::v16f32;
6015     NumElts = 16;
6016   }
6017 
6018   SmallVector<SDValue, 16> VecElts(NumElts);
6019   for (unsigned i = 0; i < Elts.size(); ++i) {
6020     SDValue Elt = Elts[i];
6021     if (Elt.getValueType() != MVT::f32)
6022       Elt = DAG.getBitcast(MVT::f32, Elt);
6023     VecElts[i] = Elt;
6024   }
6025   for (unsigned i = Elts.size(); i < NumElts; ++i)
6026     VecElts[i] = DAG.getUNDEF(MVT::f32);
6027 
6028   if (NumElts == 1)
6029     return VecElts[0];
6030   return DAG.getBuildVector(Type, DL, VecElts);
6031 }
6032 
6033 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6034                               SDValue Src, int ExtraElts) {
6035   EVT SrcVT = Src.getValueType();
6036 
6037   SmallVector<SDValue, 8> Elts;
6038 
6039   if (SrcVT.isVector())
6040     DAG.ExtractVectorElements(Src, Elts);
6041   else
6042     Elts.push_back(Src);
6043 
6044   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6045   while (ExtraElts--)
6046     Elts.push_back(Undef);
6047 
6048   return DAG.getBuildVector(CastVT, DL, Elts);
6049 }
6050 
6051 // Re-construct the required return value for a image load intrinsic.
6052 // This is more complicated due to the optional use TexFailCtrl which means the required
6053 // return type is an aggregate
6054 static SDValue constructRetValue(SelectionDAG &DAG,
6055                                  MachineSDNode *Result,
6056                                  ArrayRef<EVT> ResultTypes,
6057                                  bool IsTexFail, bool Unpacked, bool IsD16,
6058                                  int DMaskPop, int NumVDataDwords,
6059                                  const SDLoc &DL) {
6060   // Determine the required return type. This is the same regardless of IsTexFail flag
6061   EVT ReqRetVT = ResultTypes[0];
6062   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6063   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6064     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6065 
6066   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6067     DMaskPop : (DMaskPop + 1) / 2;
6068 
6069   MVT DataDwordVT = NumDataDwords == 1 ?
6070     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6071 
6072   MVT MaskPopVT = MaskPopDwords == 1 ?
6073     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6074 
6075   SDValue Data(Result, 0);
6076   SDValue TexFail;
6077 
6078   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6079     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6080     if (MaskPopVT.isVector()) {
6081       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6082                          SDValue(Result, 0), ZeroIdx);
6083     } else {
6084       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6085                          SDValue(Result, 0), ZeroIdx);
6086     }
6087   }
6088 
6089   if (DataDwordVT.isVector())
6090     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6091                           NumDataDwords - MaskPopDwords);
6092 
6093   if (IsD16)
6094     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6095 
6096   EVT LegalReqRetVT = ReqRetVT;
6097   if (!ReqRetVT.isVector()) {
6098     if (!Data.getValueType().isInteger())
6099       Data = DAG.getNode(ISD::BITCAST, DL,
6100                          Data.getValueType().changeTypeToInteger(), Data);
6101     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6102   } else {
6103     // We need to widen the return vector to a legal type
6104     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6105         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6106       LegalReqRetVT =
6107           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6108                            ReqRetVT.getVectorNumElements() + 1);
6109     }
6110   }
6111   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6112 
6113   if (IsTexFail) {
6114     TexFail =
6115         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6116                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6117 
6118     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6119   }
6120 
6121   if (Result->getNumValues() == 1)
6122     return Data;
6123 
6124   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6125 }
6126 
6127 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6128                          SDValue *LWE, bool &IsTexFail) {
6129   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6130 
6131   uint64_t Value = TexFailCtrlConst->getZExtValue();
6132   if (Value) {
6133     IsTexFail = true;
6134   }
6135 
6136   SDLoc DL(TexFailCtrlConst);
6137   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6138   Value &= ~(uint64_t)0x1;
6139   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6140   Value &= ~(uint64_t)0x2;
6141 
6142   return Value == 0;
6143 }
6144 
6145 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6146                                       MVT PackVectorVT,
6147                                       SmallVectorImpl<SDValue> &PackedAddrs,
6148                                       unsigned DimIdx, unsigned EndIdx,
6149                                       unsigned NumGradients) {
6150   SDLoc DL(Op);
6151   for (unsigned I = DimIdx; I < EndIdx; I++) {
6152     SDValue Addr = Op.getOperand(I);
6153 
6154     // Gradients are packed with undef for each coordinate.
6155     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6156     // 1D: undef,dx/dh; undef,dx/dv
6157     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6158     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6159     if (((I + 1) >= EndIdx) ||
6160         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6161                                          I == DimIdx + NumGradients - 1))) {
6162       if (Addr.getValueType() != MVT::i16)
6163         Addr = DAG.getBitcast(MVT::i16, Addr);
6164       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6165     } else {
6166       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6167       I++;
6168     }
6169     Addr = DAG.getBitcast(MVT::f32, Addr);
6170     PackedAddrs.push_back(Addr);
6171   }
6172 }
6173 
6174 SDValue SITargetLowering::lowerImage(SDValue Op,
6175                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6176                                      SelectionDAG &DAG, bool WithChain) const {
6177   SDLoc DL(Op);
6178   MachineFunction &MF = DAG.getMachineFunction();
6179   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6180   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6181       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6182   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6183   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6184       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6185   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6186       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6187   unsigned IntrOpcode = Intr->BaseOpcode;
6188   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6189 
6190   SmallVector<EVT, 3> ResultTypes(Op->values());
6191   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6192   bool IsD16 = false;
6193   bool IsG16 = false;
6194   bool IsA16 = false;
6195   SDValue VData;
6196   int NumVDataDwords;
6197   bool AdjustRetType = false;
6198 
6199   // Offset of intrinsic arguments
6200   const unsigned ArgOffset = WithChain ? 2 : 1;
6201 
6202   unsigned DMask;
6203   unsigned DMaskLanes = 0;
6204 
6205   if (BaseOpcode->Atomic) {
6206     VData = Op.getOperand(2);
6207 
6208     bool Is64Bit = VData.getValueType() == MVT::i64;
6209     if (BaseOpcode->AtomicX2) {
6210       SDValue VData2 = Op.getOperand(3);
6211       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6212                                  {VData, VData2});
6213       if (Is64Bit)
6214         VData = DAG.getBitcast(MVT::v4i32, VData);
6215 
6216       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6217       DMask = Is64Bit ? 0xf : 0x3;
6218       NumVDataDwords = Is64Bit ? 4 : 2;
6219     } else {
6220       DMask = Is64Bit ? 0x3 : 0x1;
6221       NumVDataDwords = Is64Bit ? 2 : 1;
6222     }
6223   } else {
6224     auto *DMaskConst =
6225         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6226     DMask = DMaskConst->getZExtValue();
6227     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6228 
6229     if (BaseOpcode->Store) {
6230       VData = Op.getOperand(2);
6231 
6232       MVT StoreVT = VData.getSimpleValueType();
6233       if (StoreVT.getScalarType() == MVT::f16) {
6234         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6235           return Op; // D16 is unsupported for this instruction
6236 
6237         IsD16 = true;
6238         VData = handleD16VData(VData, DAG, true);
6239       }
6240 
6241       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6242     } else {
6243       // Work out the num dwords based on the dmask popcount and underlying type
6244       // and whether packing is supported.
6245       MVT LoadVT = ResultTypes[0].getSimpleVT();
6246       if (LoadVT.getScalarType() == MVT::f16) {
6247         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6248           return Op; // D16 is unsupported for this instruction
6249 
6250         IsD16 = true;
6251       }
6252 
6253       // Confirm that the return type is large enough for the dmask specified
6254       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6255           (!LoadVT.isVector() && DMaskLanes > 1))
6256           return Op;
6257 
6258       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6259       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6260       // instructions.
6261       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6262           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6263         NumVDataDwords = (DMaskLanes + 1) / 2;
6264       else
6265         NumVDataDwords = DMaskLanes;
6266 
6267       AdjustRetType = true;
6268     }
6269   }
6270 
6271   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6272   SmallVector<SDValue, 4> VAddrs;
6273 
6274   // Optimize _L to _LZ when _L is zero
6275   if (LZMappingInfo) {
6276     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6277             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6278       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6279         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6280         VAddrEnd--;                      // remove 'lod'
6281       }
6282     }
6283   }
6284 
6285   // Optimize _mip away, when 'lod' is zero
6286   if (MIPMappingInfo) {
6287     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6288             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6289       if (ConstantLod->isZero()) {
6290         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6291         VAddrEnd--;                           // remove 'mip'
6292       }
6293     }
6294   }
6295 
6296   // Check for 16 bit addresses or derivatives and pack if true.
6297   MVT VAddrVT =
6298       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6299   MVT VAddrScalarVT = VAddrVT.getScalarType();
6300   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6301   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6302 
6303   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6304   VAddrScalarVT = VAddrVT.getScalarType();
6305   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6306   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6307 
6308   // Push back extra arguments.
6309   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6310     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6311       // Special handling of bias when A16 is on. Bias is of type half but
6312       // occupies full 32-bit.
6313       SDValue bias = DAG.getBuildVector( MVT::v2f16, DL, {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6314       VAddrs.push_back(bias);
6315     } else
6316       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6317   }
6318 
6319   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6320     // 16 bit gradients are supported, but are tied to the A16 control
6321     // so both gradients and addresses must be 16 bit
6322     LLVM_DEBUG(
6323         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6324                   "require 16 bit args for both gradients and addresses");
6325     return Op;
6326   }
6327 
6328   if (IsA16) {
6329     if (!ST->hasA16()) {
6330       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6331                            "support 16 bit addresses\n");
6332       return Op;
6333     }
6334   }
6335 
6336   // We've dealt with incorrect input so we know that if IsA16, IsG16
6337   // are set then we have to compress/pack operands (either address,
6338   // gradient or both)
6339   // In the case where a16 and gradients are tied (no G16 support) then we
6340   // have already verified that both IsA16 and IsG16 are true
6341   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6342     // Activate g16
6343     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6344         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6345     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6346   }
6347 
6348   // Add gradients (packed or unpacked)
6349   if (IsG16) {
6350     // Pack the gradients
6351     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6352     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6353                               ArgOffset + Intr->GradientStart,
6354                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6355   } else {
6356     for (unsigned I = ArgOffset + Intr->GradientStart;
6357          I < ArgOffset + Intr->CoordStart; I++)
6358       VAddrs.push_back(Op.getOperand(I));
6359   }
6360 
6361   // Add addresses (packed or unpacked)
6362   if (IsA16) {
6363     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6364                               ArgOffset + Intr->CoordStart, VAddrEnd,
6365                               0 /* No gradients */);
6366   } else {
6367     // Add uncompressed address
6368     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6369       VAddrs.push_back(Op.getOperand(I));
6370   }
6371 
6372   // If the register allocator cannot place the address registers contiguously
6373   // without introducing moves, then using the non-sequential address encoding
6374   // is always preferable, since it saves VALU instructions and is usually a
6375   // wash in terms of code size or even better.
6376   //
6377   // However, we currently have no way of hinting to the register allocator that
6378   // MIMG addresses should be placed contiguously when it is possible to do so,
6379   // so force non-NSA for the common 2-address case as a heuristic.
6380   //
6381   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6382   // allocation when possible.
6383   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6384                 VAddrs.size() >= 3 &&
6385                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6386   SDValue VAddr;
6387   if (!UseNSA)
6388     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6389 
6390   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6391   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6392   SDValue Unorm;
6393   if (!BaseOpcode->Sampler) {
6394     Unorm = True;
6395   } else {
6396     auto UnormConst =
6397         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6398 
6399     Unorm = UnormConst->getZExtValue() ? True : False;
6400   }
6401 
6402   SDValue TFE;
6403   SDValue LWE;
6404   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6405   bool IsTexFail = false;
6406   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6407     return Op;
6408 
6409   if (IsTexFail) {
6410     if (!DMaskLanes) {
6411       // Expecting to get an error flag since TFC is on - and dmask is 0
6412       // Force dmask to be at least 1 otherwise the instruction will fail
6413       DMask = 0x1;
6414       DMaskLanes = 1;
6415       NumVDataDwords = 1;
6416     }
6417     NumVDataDwords += 1;
6418     AdjustRetType = true;
6419   }
6420 
6421   // Has something earlier tagged that the return type needs adjusting
6422   // This happens if the instruction is a load or has set TexFailCtrl flags
6423   if (AdjustRetType) {
6424     // NumVDataDwords reflects the true number of dwords required in the return type
6425     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6426       // This is a no-op load. This can be eliminated
6427       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6428       if (isa<MemSDNode>(Op))
6429         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6430       return Undef;
6431     }
6432 
6433     EVT NewVT = NumVDataDwords > 1 ?
6434                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6435                 : MVT::i32;
6436 
6437     ResultTypes[0] = NewVT;
6438     if (ResultTypes.size() == 3) {
6439       // Original result was aggregate type used for TexFailCtrl results
6440       // The actual instruction returns as a vector type which has now been
6441       // created. Remove the aggregate result.
6442       ResultTypes.erase(&ResultTypes[1]);
6443     }
6444   }
6445 
6446   unsigned CPol = cast<ConstantSDNode>(
6447       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6448   if (BaseOpcode->Atomic)
6449     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6450   if (CPol & ~AMDGPU::CPol::ALL)
6451     return Op;
6452 
6453   SmallVector<SDValue, 26> Ops;
6454   if (BaseOpcode->Store || BaseOpcode->Atomic)
6455     Ops.push_back(VData); // vdata
6456   if (UseNSA)
6457     append_range(Ops, VAddrs);
6458   else
6459     Ops.push_back(VAddr);
6460   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6461   if (BaseOpcode->Sampler)
6462     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6463   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6464   if (IsGFX10Plus)
6465     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6466   Ops.push_back(Unorm);
6467   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6468   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6469                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6470   if (IsGFX10Plus)
6471     Ops.push_back(IsA16 ? True : False);
6472   if (!Subtarget->hasGFX90AInsts()) {
6473     Ops.push_back(TFE); //tfe
6474   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6475     report_fatal_error("TFE is not supported on this GPU");
6476   }
6477   Ops.push_back(LWE); // lwe
6478   if (!IsGFX10Plus)
6479     Ops.push_back(DimInfo->DA ? True : False);
6480   if (BaseOpcode->HasD16)
6481     Ops.push_back(IsD16 ? True : False);
6482   if (isa<MemSDNode>(Op))
6483     Ops.push_back(Op.getOperand(0)); // chain
6484 
6485   int NumVAddrDwords =
6486       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6487   int Opcode = -1;
6488 
6489   if (IsGFX10Plus) {
6490     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6491                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6492                                           : AMDGPU::MIMGEncGfx10Default,
6493                                    NumVDataDwords, NumVAddrDwords);
6494   } else {
6495     if (Subtarget->hasGFX90AInsts()) {
6496       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6497                                      NumVDataDwords, NumVAddrDwords);
6498       if (Opcode == -1)
6499         report_fatal_error(
6500             "requested image instruction is not supported on this GPU");
6501     }
6502     if (Opcode == -1 &&
6503         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6504       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6505                                      NumVDataDwords, NumVAddrDwords);
6506     if (Opcode == -1)
6507       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6508                                      NumVDataDwords, NumVAddrDwords);
6509   }
6510   assert(Opcode != -1);
6511 
6512   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6513   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6514     MachineMemOperand *MemRef = MemOp->getMemOperand();
6515     DAG.setNodeMemRefs(NewNode, {MemRef});
6516   }
6517 
6518   if (BaseOpcode->AtomicX2) {
6519     SmallVector<SDValue, 1> Elt;
6520     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6521     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6522   }
6523   if (BaseOpcode->Store)
6524     return SDValue(NewNode, 0);
6525   return constructRetValue(DAG, NewNode,
6526                            OrigResultTypes, IsTexFail,
6527                            Subtarget->hasUnpackedD16VMem(), IsD16,
6528                            DMaskLanes, NumVDataDwords, DL);
6529 }
6530 
6531 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6532                                        SDValue Offset, SDValue CachePolicy,
6533                                        SelectionDAG &DAG) const {
6534   MachineFunction &MF = DAG.getMachineFunction();
6535 
6536   const DataLayout &DataLayout = DAG.getDataLayout();
6537   Align Alignment =
6538       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6539 
6540   MachineMemOperand *MMO = MF.getMachineMemOperand(
6541       MachinePointerInfo(),
6542       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6543           MachineMemOperand::MOInvariant,
6544       VT.getStoreSize(), Alignment);
6545 
6546   if (!Offset->isDivergent()) {
6547     SDValue Ops[] = {
6548         Rsrc,
6549         Offset, // Offset
6550         CachePolicy
6551     };
6552 
6553     // Widen vec3 load to vec4.
6554     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6555       EVT WidenedVT =
6556           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6557       auto WidenedOp = DAG.getMemIntrinsicNode(
6558           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6559           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6560       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6561                                    DAG.getVectorIdxConstant(0, DL));
6562       return Subvector;
6563     }
6564 
6565     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6566                                    DAG.getVTList(VT), Ops, VT, MMO);
6567   }
6568 
6569   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6570   // assume that the buffer is unswizzled.
6571   SmallVector<SDValue, 4> Loads;
6572   unsigned NumLoads = 1;
6573   MVT LoadVT = VT.getSimpleVT();
6574   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6575   assert((LoadVT.getScalarType() == MVT::i32 ||
6576           LoadVT.getScalarType() == MVT::f32));
6577 
6578   if (NumElts == 8 || NumElts == 16) {
6579     NumLoads = NumElts / 4;
6580     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6581   }
6582 
6583   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6584   SDValue Ops[] = {
6585       DAG.getEntryNode(),                               // Chain
6586       Rsrc,                                             // rsrc
6587       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6588       {},                                               // voffset
6589       {},                                               // soffset
6590       {},                                               // offset
6591       CachePolicy,                                      // cachepolicy
6592       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6593   };
6594 
6595   // Use the alignment to ensure that the required offsets will fit into the
6596   // immediate offsets.
6597   setBufferOffsets(Offset, DAG, &Ops[3],
6598                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6599 
6600   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6601   for (unsigned i = 0; i < NumLoads; ++i) {
6602     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6603     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6604                                         LoadVT, MMO, DAG));
6605   }
6606 
6607   if (NumElts == 8 || NumElts == 16)
6608     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6609 
6610   return Loads[0];
6611 }
6612 
6613 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6614                                                   SelectionDAG &DAG) const {
6615   MachineFunction &MF = DAG.getMachineFunction();
6616   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6617 
6618   EVT VT = Op.getValueType();
6619   SDLoc DL(Op);
6620   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6621 
6622   // TODO: Should this propagate fast-math-flags?
6623 
6624   switch (IntrinsicID) {
6625   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6626     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6627       return emitNonHSAIntrinsicError(DAG, DL, VT);
6628     return getPreloadedValue(DAG, *MFI, VT,
6629                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6630   }
6631   case Intrinsic::amdgcn_dispatch_ptr:
6632   case Intrinsic::amdgcn_queue_ptr: {
6633     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6634       DiagnosticInfoUnsupported BadIntrin(
6635           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6636           DL.getDebugLoc());
6637       DAG.getContext()->diagnose(BadIntrin);
6638       return DAG.getUNDEF(VT);
6639     }
6640 
6641     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6642       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6643     return getPreloadedValue(DAG, *MFI, VT, RegID);
6644   }
6645   case Intrinsic::amdgcn_implicitarg_ptr: {
6646     if (MFI->isEntryFunction())
6647       return getImplicitArgPtr(DAG, DL);
6648     return getPreloadedValue(DAG, *MFI, VT,
6649                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6650   }
6651   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6652     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6653       // This only makes sense to call in a kernel, so just lower to null.
6654       return DAG.getConstant(0, DL, VT);
6655     }
6656 
6657     return getPreloadedValue(DAG, *MFI, VT,
6658                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6659   }
6660   case Intrinsic::amdgcn_dispatch_id: {
6661     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6662   }
6663   case Intrinsic::amdgcn_rcp:
6664     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6665   case Intrinsic::amdgcn_rsq:
6666     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6667   case Intrinsic::amdgcn_rsq_legacy:
6668     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6669       return emitRemovedIntrinsicError(DAG, DL, VT);
6670     return SDValue();
6671   case Intrinsic::amdgcn_rcp_legacy:
6672     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6673       return emitRemovedIntrinsicError(DAG, DL, VT);
6674     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6675   case Intrinsic::amdgcn_rsq_clamp: {
6676     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6677       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6678 
6679     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6680     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6681     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6682 
6683     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6684     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6685                               DAG.getConstantFP(Max, DL, VT));
6686     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6687                        DAG.getConstantFP(Min, DL, VT));
6688   }
6689   case Intrinsic::r600_read_ngroups_x:
6690     if (Subtarget->isAmdHsaOS())
6691       return emitNonHSAIntrinsicError(DAG, DL, VT);
6692 
6693     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6694                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6695                                     false);
6696   case Intrinsic::r600_read_ngroups_y:
6697     if (Subtarget->isAmdHsaOS())
6698       return emitNonHSAIntrinsicError(DAG, DL, VT);
6699 
6700     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6701                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6702                                     false);
6703   case Intrinsic::r600_read_ngroups_z:
6704     if (Subtarget->isAmdHsaOS())
6705       return emitNonHSAIntrinsicError(DAG, DL, VT);
6706 
6707     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6708                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6709                                     false);
6710   case Intrinsic::r600_read_global_size_x:
6711     if (Subtarget->isAmdHsaOS())
6712       return emitNonHSAIntrinsicError(DAG, DL, VT);
6713 
6714     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6715                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6716                                     Align(4), false);
6717   case Intrinsic::r600_read_global_size_y:
6718     if (Subtarget->isAmdHsaOS())
6719       return emitNonHSAIntrinsicError(DAG, DL, VT);
6720 
6721     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6722                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6723                                     Align(4), false);
6724   case Intrinsic::r600_read_global_size_z:
6725     if (Subtarget->isAmdHsaOS())
6726       return emitNonHSAIntrinsicError(DAG, DL, VT);
6727 
6728     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6729                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6730                                     Align(4), false);
6731   case Intrinsic::r600_read_local_size_x:
6732     if (Subtarget->isAmdHsaOS())
6733       return emitNonHSAIntrinsicError(DAG, DL, VT);
6734 
6735     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6736                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6737   case Intrinsic::r600_read_local_size_y:
6738     if (Subtarget->isAmdHsaOS())
6739       return emitNonHSAIntrinsicError(DAG, DL, VT);
6740 
6741     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6742                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6743   case Intrinsic::r600_read_local_size_z:
6744     if (Subtarget->isAmdHsaOS())
6745       return emitNonHSAIntrinsicError(DAG, DL, VT);
6746 
6747     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6748                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6749   case Intrinsic::amdgcn_workgroup_id_x:
6750     return getPreloadedValue(DAG, *MFI, VT,
6751                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6752   case Intrinsic::amdgcn_workgroup_id_y:
6753     return getPreloadedValue(DAG, *MFI, VT,
6754                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6755   case Intrinsic::amdgcn_workgroup_id_z:
6756     return getPreloadedValue(DAG, *MFI, VT,
6757                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6758   case Intrinsic::amdgcn_workitem_id_x:
6759     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6760       return DAG.getConstant(0, DL, MVT::i32);
6761 
6762     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6763                           SDLoc(DAG.getEntryNode()),
6764                           MFI->getArgInfo().WorkItemIDX);
6765   case Intrinsic::amdgcn_workitem_id_y:
6766     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6767       return DAG.getConstant(0, DL, MVT::i32);
6768 
6769     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6770                           SDLoc(DAG.getEntryNode()),
6771                           MFI->getArgInfo().WorkItemIDY);
6772   case Intrinsic::amdgcn_workitem_id_z:
6773     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6774       return DAG.getConstant(0, DL, MVT::i32);
6775 
6776     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6777                           SDLoc(DAG.getEntryNode()),
6778                           MFI->getArgInfo().WorkItemIDZ);
6779   case Intrinsic::amdgcn_wavefrontsize:
6780     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6781                            SDLoc(Op), MVT::i32);
6782   case Intrinsic::amdgcn_s_buffer_load: {
6783     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6784     if (CPol & ~AMDGPU::CPol::ALL)
6785       return Op;
6786     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6787                         DAG);
6788   }
6789   case Intrinsic::amdgcn_fdiv_fast:
6790     return lowerFDIV_FAST(Op, DAG);
6791   case Intrinsic::amdgcn_sin:
6792     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6793 
6794   case Intrinsic::amdgcn_cos:
6795     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6796 
6797   case Intrinsic::amdgcn_mul_u24:
6798     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6799   case Intrinsic::amdgcn_mul_i24:
6800     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6801 
6802   case Intrinsic::amdgcn_log_clamp: {
6803     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6804       return SDValue();
6805 
6806     return emitRemovedIntrinsicError(DAG, DL, VT);
6807   }
6808   case Intrinsic::amdgcn_ldexp:
6809     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6810                        Op.getOperand(1), Op.getOperand(2));
6811 
6812   case Intrinsic::amdgcn_fract:
6813     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6814 
6815   case Intrinsic::amdgcn_class:
6816     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6817                        Op.getOperand(1), Op.getOperand(2));
6818   case Intrinsic::amdgcn_div_fmas:
6819     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6820                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6821                        Op.getOperand(4));
6822 
6823   case Intrinsic::amdgcn_div_fixup:
6824     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6825                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6826 
6827   case Intrinsic::amdgcn_div_scale: {
6828     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6829 
6830     // Translate to the operands expected by the machine instruction. The
6831     // first parameter must be the same as the first instruction.
6832     SDValue Numerator = Op.getOperand(1);
6833     SDValue Denominator = Op.getOperand(2);
6834 
6835     // Note this order is opposite of the machine instruction's operations,
6836     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6837     // intrinsic has the numerator as the first operand to match a normal
6838     // division operation.
6839 
6840     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6841 
6842     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6843                        Denominator, Numerator);
6844   }
6845   case Intrinsic::amdgcn_icmp: {
6846     // There is a Pat that handles this variant, so return it as-is.
6847     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6848         Op.getConstantOperandVal(2) == 0 &&
6849         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6850       return Op;
6851     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6852   }
6853   case Intrinsic::amdgcn_fcmp: {
6854     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6855   }
6856   case Intrinsic::amdgcn_ballot:
6857     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6858   case Intrinsic::amdgcn_fmed3:
6859     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6860                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6861   case Intrinsic::amdgcn_fdot2:
6862     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6863                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6864                        Op.getOperand(4));
6865   case Intrinsic::amdgcn_fmul_legacy:
6866     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6867                        Op.getOperand(1), Op.getOperand(2));
6868   case Intrinsic::amdgcn_sffbh:
6869     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6870   case Intrinsic::amdgcn_sbfe:
6871     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6872                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6873   case Intrinsic::amdgcn_ubfe:
6874     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6875                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6876   case Intrinsic::amdgcn_cvt_pkrtz:
6877   case Intrinsic::amdgcn_cvt_pknorm_i16:
6878   case Intrinsic::amdgcn_cvt_pknorm_u16:
6879   case Intrinsic::amdgcn_cvt_pk_i16:
6880   case Intrinsic::amdgcn_cvt_pk_u16: {
6881     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6882     EVT VT = Op.getValueType();
6883     unsigned Opcode;
6884 
6885     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6886       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6887     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6888       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6889     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6890       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6891     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6892       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6893     else
6894       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6895 
6896     if (isTypeLegal(VT))
6897       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6898 
6899     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6900                                Op.getOperand(1), Op.getOperand(2));
6901     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6902   }
6903   case Intrinsic::amdgcn_fmad_ftz:
6904     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6905                        Op.getOperand(2), Op.getOperand(3));
6906 
6907   case Intrinsic::amdgcn_if_break:
6908     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6909                                       Op->getOperand(1), Op->getOperand(2)), 0);
6910 
6911   case Intrinsic::amdgcn_groupstaticsize: {
6912     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6913     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6914       return Op;
6915 
6916     const Module *M = MF.getFunction().getParent();
6917     const GlobalValue *GV =
6918         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6919     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6920                                             SIInstrInfo::MO_ABS32_LO);
6921     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6922   }
6923   case Intrinsic::amdgcn_is_shared:
6924   case Intrinsic::amdgcn_is_private: {
6925     SDLoc SL(Op);
6926     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6927       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6928     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6929     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6930                                  Op.getOperand(1));
6931 
6932     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6933                                 DAG.getConstant(1, SL, MVT::i32));
6934     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6935   }
6936   case Intrinsic::amdgcn_alignbit:
6937     return DAG.getNode(ISD::FSHR, DL, VT,
6938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6939   case Intrinsic::amdgcn_perm:
6940     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6941                        Op.getOperand(2), Op.getOperand(3));
6942   case Intrinsic::amdgcn_reloc_constant: {
6943     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6944     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6945     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6946     auto RelocSymbol = cast<GlobalVariable>(
6947         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6948     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6949                                             SIInstrInfo::MO_ABS32_LO);
6950     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6951   }
6952   default:
6953     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6954             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6955       return lowerImage(Op, ImageDimIntr, DAG, false);
6956 
6957     return Op;
6958   }
6959 }
6960 
6961 /// Update \p MMO based on the offset inputs to an intrinsic.
6962 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6963                             SDValue SOffset, SDValue Offset,
6964                             SDValue VIndex = SDValue()) {
6965   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6966       !isa<ConstantSDNode>(Offset)) {
6967     // The combined offset is not known to be constant, so we cannot represent
6968     // it in the MMO. Give up.
6969     MMO->setValue((Value *)nullptr);
6970     return;
6971   }
6972 
6973   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6974                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6975     // The strided index component of the address is not known to be zero, so we
6976     // cannot represent it in the MMO. Give up.
6977     MMO->setValue((Value *)nullptr);
6978     return;
6979   }
6980 
6981   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6982                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6983                  cast<ConstantSDNode>(Offset)->getSExtValue());
6984 }
6985 
6986 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6987                                                      SelectionDAG &DAG,
6988                                                      unsigned NewOpcode) const {
6989   SDLoc DL(Op);
6990 
6991   SDValue VData = Op.getOperand(2);
6992   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6993   SDValue Ops[] = {
6994     Op.getOperand(0), // Chain
6995     VData,            // vdata
6996     Op.getOperand(3), // rsrc
6997     DAG.getConstant(0, DL, MVT::i32), // vindex
6998     Offsets.first,    // voffset
6999     Op.getOperand(5), // soffset
7000     Offsets.second,   // offset
7001     Op.getOperand(6), // cachepolicy
7002     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7003   };
7004 
7005   auto *M = cast<MemSDNode>(Op);
7006   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7007 
7008   EVT MemVT = VData.getValueType();
7009   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7010                                  M->getMemOperand());
7011 }
7012 
7013 // Return a value to use for the idxen operand by examining the vindex operand.
7014 static unsigned getIdxEn(SDValue VIndex) {
7015   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7016     // No need to set idxen if vindex is known to be zero.
7017     return VIndexC->getZExtValue() != 0;
7018   return 1;
7019 }
7020 
7021 SDValue
7022 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7023                                                 unsigned NewOpcode) const {
7024   SDLoc DL(Op);
7025 
7026   SDValue VData = Op.getOperand(2);
7027   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7028   SDValue Ops[] = {
7029     Op.getOperand(0), // Chain
7030     VData,            // vdata
7031     Op.getOperand(3), // rsrc
7032     Op.getOperand(4), // vindex
7033     Offsets.first,    // voffset
7034     Op.getOperand(6), // soffset
7035     Offsets.second,   // offset
7036     Op.getOperand(7), // cachepolicy
7037     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7038   };
7039 
7040   auto *M = cast<MemSDNode>(Op);
7041   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7042 
7043   EVT MemVT = VData.getValueType();
7044   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7045                                  M->getMemOperand());
7046 }
7047 
7048 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7049                                                  SelectionDAG &DAG) const {
7050   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7051   SDLoc DL(Op);
7052 
7053   switch (IntrID) {
7054   case Intrinsic::amdgcn_ds_ordered_add:
7055   case Intrinsic::amdgcn_ds_ordered_swap: {
7056     MemSDNode *M = cast<MemSDNode>(Op);
7057     SDValue Chain = M->getOperand(0);
7058     SDValue M0 = M->getOperand(2);
7059     SDValue Value = M->getOperand(3);
7060     unsigned IndexOperand = M->getConstantOperandVal(7);
7061     unsigned WaveRelease = M->getConstantOperandVal(8);
7062     unsigned WaveDone = M->getConstantOperandVal(9);
7063 
7064     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7065     IndexOperand &= ~0x3f;
7066     unsigned CountDw = 0;
7067 
7068     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7069       CountDw = (IndexOperand >> 24) & 0xf;
7070       IndexOperand &= ~(0xf << 24);
7071 
7072       if (CountDw < 1 || CountDw > 4) {
7073         report_fatal_error(
7074             "ds_ordered_count: dword count must be between 1 and 4");
7075       }
7076     }
7077 
7078     if (IndexOperand)
7079       report_fatal_error("ds_ordered_count: bad index operand");
7080 
7081     if (WaveDone && !WaveRelease)
7082       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7083 
7084     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7085     unsigned ShaderType =
7086         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7087     unsigned Offset0 = OrderedCountIndex << 2;
7088     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7089                        (Instruction << 4);
7090 
7091     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7092       Offset1 |= (CountDw - 1) << 6;
7093 
7094     unsigned Offset = Offset0 | (Offset1 << 8);
7095 
7096     SDValue Ops[] = {
7097       Chain,
7098       Value,
7099       DAG.getTargetConstant(Offset, DL, MVT::i16),
7100       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7101     };
7102     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7103                                    M->getVTList(), Ops, M->getMemoryVT(),
7104                                    M->getMemOperand());
7105   }
7106   case Intrinsic::amdgcn_ds_fadd: {
7107     MemSDNode *M = cast<MemSDNode>(Op);
7108     unsigned Opc;
7109     switch (IntrID) {
7110     case Intrinsic::amdgcn_ds_fadd:
7111       Opc = ISD::ATOMIC_LOAD_FADD;
7112       break;
7113     }
7114 
7115     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7116                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7117                          M->getMemOperand());
7118   }
7119   case Intrinsic::amdgcn_atomic_inc:
7120   case Intrinsic::amdgcn_atomic_dec:
7121   case Intrinsic::amdgcn_ds_fmin:
7122   case Intrinsic::amdgcn_ds_fmax: {
7123     MemSDNode *M = cast<MemSDNode>(Op);
7124     unsigned Opc;
7125     switch (IntrID) {
7126     case Intrinsic::amdgcn_atomic_inc:
7127       Opc = AMDGPUISD::ATOMIC_INC;
7128       break;
7129     case Intrinsic::amdgcn_atomic_dec:
7130       Opc = AMDGPUISD::ATOMIC_DEC;
7131       break;
7132     case Intrinsic::amdgcn_ds_fmin:
7133       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7134       break;
7135     case Intrinsic::amdgcn_ds_fmax:
7136       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7137       break;
7138     default:
7139       llvm_unreachable("Unknown intrinsic!");
7140     }
7141     SDValue Ops[] = {
7142       M->getOperand(0), // Chain
7143       M->getOperand(2), // Ptr
7144       M->getOperand(3)  // Value
7145     };
7146 
7147     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7148                                    M->getMemoryVT(), M->getMemOperand());
7149   }
7150   case Intrinsic::amdgcn_buffer_load:
7151   case Intrinsic::amdgcn_buffer_load_format: {
7152     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7153     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7154     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7155     SDValue Ops[] = {
7156       Op.getOperand(0), // Chain
7157       Op.getOperand(2), // rsrc
7158       Op.getOperand(3), // vindex
7159       SDValue(),        // voffset -- will be set by setBufferOffsets
7160       SDValue(),        // soffset -- will be set by setBufferOffsets
7161       SDValue(),        // offset -- will be set by setBufferOffsets
7162       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7163       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7164     };
7165     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7166 
7167     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7168         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7169 
7170     EVT VT = Op.getValueType();
7171     EVT IntVT = VT.changeTypeToInteger();
7172     auto *M = cast<MemSDNode>(Op);
7173     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7174     EVT LoadVT = Op.getValueType();
7175 
7176     if (LoadVT.getScalarType() == MVT::f16)
7177       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7178                                  M, DAG, Ops);
7179 
7180     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7181     if (LoadVT.getScalarType() == MVT::i8 ||
7182         LoadVT.getScalarType() == MVT::i16)
7183       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7184 
7185     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7186                                M->getMemOperand(), DAG);
7187   }
7188   case Intrinsic::amdgcn_raw_buffer_load:
7189   case Intrinsic::amdgcn_raw_buffer_load_format: {
7190     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7191 
7192     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7193     SDValue Ops[] = {
7194       Op.getOperand(0), // Chain
7195       Op.getOperand(2), // rsrc
7196       DAG.getConstant(0, DL, MVT::i32), // vindex
7197       Offsets.first,    // voffset
7198       Op.getOperand(4), // soffset
7199       Offsets.second,   // offset
7200       Op.getOperand(5), // cachepolicy, swizzled buffer
7201       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7202     };
7203 
7204     auto *M = cast<MemSDNode>(Op);
7205     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7206     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7207   }
7208   case Intrinsic::amdgcn_struct_buffer_load:
7209   case Intrinsic::amdgcn_struct_buffer_load_format: {
7210     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7211 
7212     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7213     SDValue Ops[] = {
7214       Op.getOperand(0), // Chain
7215       Op.getOperand(2), // rsrc
7216       Op.getOperand(3), // vindex
7217       Offsets.first,    // voffset
7218       Op.getOperand(5), // soffset
7219       Offsets.second,   // offset
7220       Op.getOperand(6), // cachepolicy, swizzled buffer
7221       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7222     };
7223 
7224     auto *M = cast<MemSDNode>(Op);
7225     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7226     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7227   }
7228   case Intrinsic::amdgcn_tbuffer_load: {
7229     MemSDNode *M = cast<MemSDNode>(Op);
7230     EVT LoadVT = Op.getValueType();
7231 
7232     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7233     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7234     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7235     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7236     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7237     SDValue Ops[] = {
7238       Op.getOperand(0),  // Chain
7239       Op.getOperand(2),  // rsrc
7240       Op.getOperand(3),  // vindex
7241       Op.getOperand(4),  // voffset
7242       Op.getOperand(5),  // soffset
7243       Op.getOperand(6),  // offset
7244       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7245       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7246       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7247     };
7248 
7249     if (LoadVT.getScalarType() == MVT::f16)
7250       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7251                                  M, DAG, Ops);
7252     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7253                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7254                                DAG);
7255   }
7256   case Intrinsic::amdgcn_raw_tbuffer_load: {
7257     MemSDNode *M = cast<MemSDNode>(Op);
7258     EVT LoadVT = Op.getValueType();
7259     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7260 
7261     SDValue Ops[] = {
7262       Op.getOperand(0),  // Chain
7263       Op.getOperand(2),  // rsrc
7264       DAG.getConstant(0, DL, MVT::i32), // vindex
7265       Offsets.first,     // voffset
7266       Op.getOperand(4),  // soffset
7267       Offsets.second,    // offset
7268       Op.getOperand(5),  // format
7269       Op.getOperand(6),  // cachepolicy, swizzled buffer
7270       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7271     };
7272 
7273     if (LoadVT.getScalarType() == MVT::f16)
7274       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7275                                  M, DAG, Ops);
7276     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7277                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7278                                DAG);
7279   }
7280   case Intrinsic::amdgcn_struct_tbuffer_load: {
7281     MemSDNode *M = cast<MemSDNode>(Op);
7282     EVT LoadVT = Op.getValueType();
7283     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7284 
7285     SDValue Ops[] = {
7286       Op.getOperand(0),  // Chain
7287       Op.getOperand(2),  // rsrc
7288       Op.getOperand(3),  // vindex
7289       Offsets.first,     // voffset
7290       Op.getOperand(5),  // soffset
7291       Offsets.second,    // offset
7292       Op.getOperand(6),  // format
7293       Op.getOperand(7),  // cachepolicy, swizzled buffer
7294       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7295     };
7296 
7297     if (LoadVT.getScalarType() == MVT::f16)
7298       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7299                                  M, DAG, Ops);
7300     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7301                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7302                                DAG);
7303   }
7304   case Intrinsic::amdgcn_buffer_atomic_swap:
7305   case Intrinsic::amdgcn_buffer_atomic_add:
7306   case Intrinsic::amdgcn_buffer_atomic_sub:
7307   case Intrinsic::amdgcn_buffer_atomic_csub:
7308   case Intrinsic::amdgcn_buffer_atomic_smin:
7309   case Intrinsic::amdgcn_buffer_atomic_umin:
7310   case Intrinsic::amdgcn_buffer_atomic_smax:
7311   case Intrinsic::amdgcn_buffer_atomic_umax:
7312   case Intrinsic::amdgcn_buffer_atomic_and:
7313   case Intrinsic::amdgcn_buffer_atomic_or:
7314   case Intrinsic::amdgcn_buffer_atomic_xor:
7315   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7316     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7317     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7318     SDValue Ops[] = {
7319       Op.getOperand(0), // Chain
7320       Op.getOperand(2), // vdata
7321       Op.getOperand(3), // rsrc
7322       Op.getOperand(4), // vindex
7323       SDValue(),        // voffset -- will be set by setBufferOffsets
7324       SDValue(),        // soffset -- will be set by setBufferOffsets
7325       SDValue(),        // offset -- will be set by setBufferOffsets
7326       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7327       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7328     };
7329     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7330 
7331     EVT VT = Op.getValueType();
7332 
7333     auto *M = cast<MemSDNode>(Op);
7334     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7335     unsigned Opcode = 0;
7336 
7337     switch (IntrID) {
7338     case Intrinsic::amdgcn_buffer_atomic_swap:
7339       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7340       break;
7341     case Intrinsic::amdgcn_buffer_atomic_add:
7342       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7343       break;
7344     case Intrinsic::amdgcn_buffer_atomic_sub:
7345       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7346       break;
7347     case Intrinsic::amdgcn_buffer_atomic_csub:
7348       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7349       break;
7350     case Intrinsic::amdgcn_buffer_atomic_smin:
7351       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7352       break;
7353     case Intrinsic::amdgcn_buffer_atomic_umin:
7354       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7355       break;
7356     case Intrinsic::amdgcn_buffer_atomic_smax:
7357       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7358       break;
7359     case Intrinsic::amdgcn_buffer_atomic_umax:
7360       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7361       break;
7362     case Intrinsic::amdgcn_buffer_atomic_and:
7363       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7364       break;
7365     case Intrinsic::amdgcn_buffer_atomic_or:
7366       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7367       break;
7368     case Intrinsic::amdgcn_buffer_atomic_xor:
7369       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7370       break;
7371     case Intrinsic::amdgcn_buffer_atomic_fadd:
7372       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7373         DiagnosticInfoUnsupported
7374           NoFpRet(DAG.getMachineFunction().getFunction(),
7375                   "return versions of fp atomics not supported",
7376                   DL.getDebugLoc(), DS_Error);
7377         DAG.getContext()->diagnose(NoFpRet);
7378         return SDValue();
7379       }
7380       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7381       break;
7382     default:
7383       llvm_unreachable("unhandled atomic opcode");
7384     }
7385 
7386     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7387                                    M->getMemOperand());
7388   }
7389   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7390     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7391   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7392     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7393   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7394     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7395   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7396     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7397   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7398     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7399   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7400     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7401   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7402     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7403   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7404     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7405   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7406     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7407   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7408     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7409   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7410     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7411   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7412     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7413   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7414     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7415   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7416     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7417   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7418     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7419   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7420     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7421   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7422     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7423   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7424     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7425   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7426     return lowerStructBufferAtomicIntrin(Op, DAG,
7427                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7428   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7429     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7430   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7431     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7432   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7433     return lowerStructBufferAtomicIntrin(Op, DAG,
7434                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7435   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7436     return lowerStructBufferAtomicIntrin(Op, DAG,
7437                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7438   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7439     return lowerStructBufferAtomicIntrin(Op, DAG,
7440                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7441   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7442     return lowerStructBufferAtomicIntrin(Op, DAG,
7443                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7444   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7445     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7446   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7447     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7448   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7449     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7450   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7451     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7452   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7453     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7454 
7455   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7456     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7457     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7458     SDValue Ops[] = {
7459       Op.getOperand(0), // Chain
7460       Op.getOperand(2), // src
7461       Op.getOperand(3), // cmp
7462       Op.getOperand(4), // rsrc
7463       Op.getOperand(5), // vindex
7464       SDValue(),        // voffset -- will be set by setBufferOffsets
7465       SDValue(),        // soffset -- will be set by setBufferOffsets
7466       SDValue(),        // offset -- will be set by setBufferOffsets
7467       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7468       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7469     };
7470     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7471 
7472     EVT VT = Op.getValueType();
7473     auto *M = cast<MemSDNode>(Op);
7474     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7475 
7476     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7477                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7478   }
7479   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7480     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7481     SDValue Ops[] = {
7482       Op.getOperand(0), // Chain
7483       Op.getOperand(2), // src
7484       Op.getOperand(3), // cmp
7485       Op.getOperand(4), // rsrc
7486       DAG.getConstant(0, DL, MVT::i32), // vindex
7487       Offsets.first,    // voffset
7488       Op.getOperand(6), // soffset
7489       Offsets.second,   // offset
7490       Op.getOperand(7), // cachepolicy
7491       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7492     };
7493     EVT VT = Op.getValueType();
7494     auto *M = cast<MemSDNode>(Op);
7495     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7496 
7497     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7498                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7499   }
7500   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7501     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7502     SDValue Ops[] = {
7503       Op.getOperand(0), // Chain
7504       Op.getOperand(2), // src
7505       Op.getOperand(3), // cmp
7506       Op.getOperand(4), // rsrc
7507       Op.getOperand(5), // vindex
7508       Offsets.first,    // voffset
7509       Op.getOperand(7), // soffset
7510       Offsets.second,   // offset
7511       Op.getOperand(8), // cachepolicy
7512       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7513     };
7514     EVT VT = Op.getValueType();
7515     auto *M = cast<MemSDNode>(Op);
7516     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7517 
7518     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7519                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7520   }
7521   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7522     MemSDNode *M = cast<MemSDNode>(Op);
7523     SDValue NodePtr = M->getOperand(2);
7524     SDValue RayExtent = M->getOperand(3);
7525     SDValue RayOrigin = M->getOperand(4);
7526     SDValue RayDir = M->getOperand(5);
7527     SDValue RayInvDir = M->getOperand(6);
7528     SDValue TDescr = M->getOperand(7);
7529 
7530     assert(NodePtr.getValueType() == MVT::i32 ||
7531            NodePtr.getValueType() == MVT::i64);
7532     assert(RayDir.getValueType() == MVT::v3f16 ||
7533            RayDir.getValueType() == MVT::v3f32);
7534 
7535     if (!Subtarget->hasGFX10_AEncoding()) {
7536       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7537       return SDValue();
7538     }
7539 
7540     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7541     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7542     const unsigned NumVDataDwords = 4;
7543     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7544     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7545                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7546     const unsigned BaseOpcodes[2][2] = {
7547         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7548         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7549          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7550     int Opcode;
7551     if (UseNSA) {
7552       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7553                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7554                                      NumVAddrDwords);
7555     } else {
7556       Opcode = AMDGPU::getMIMGOpcode(
7557           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7558           PowerOf2Ceil(NumVAddrDwords));
7559     }
7560     assert(Opcode != -1);
7561 
7562     SmallVector<SDValue, 16> Ops;
7563 
7564     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7565       SmallVector<SDValue, 3> Lanes;
7566       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7567       if (Lanes[0].getValueSizeInBits() == 32) {
7568         for (unsigned I = 0; I < 3; ++I)
7569           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7570       } else {
7571         if (IsAligned) {
7572           Ops.push_back(
7573             DAG.getBitcast(MVT::i32,
7574                            DAG.getBuildVector(MVT::v2f16, DL,
7575                                               { Lanes[0], Lanes[1] })));
7576           Ops.push_back(Lanes[2]);
7577         } else {
7578           SDValue Elt0 = Ops.pop_back_val();
7579           Ops.push_back(
7580             DAG.getBitcast(MVT::i32,
7581                            DAG.getBuildVector(MVT::v2f16, DL,
7582                                               { Elt0, Lanes[0] })));
7583           Ops.push_back(
7584             DAG.getBitcast(MVT::i32,
7585                            DAG.getBuildVector(MVT::v2f16, DL,
7586                                               { Lanes[1], Lanes[2] })));
7587         }
7588       }
7589     };
7590 
7591     if (Is64)
7592       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7593     else
7594       Ops.push_back(NodePtr);
7595 
7596     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7597     packLanes(RayOrigin, true);
7598     packLanes(RayDir, true);
7599     packLanes(RayInvDir, false);
7600 
7601     if (!UseNSA) {
7602       // Build a single vector containing all the operands so far prepared.
7603       if (NumVAddrDwords > 8) {
7604         SDValue Undef = DAG.getUNDEF(MVT::i32);
7605         Ops.append(16 - Ops.size(), Undef);
7606       }
7607       assert(Ops.size() == 8 || Ops.size() == 16);
7608       SDValue MergedOps = DAG.getBuildVector(
7609           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7610       Ops.clear();
7611       Ops.push_back(MergedOps);
7612     }
7613 
7614     Ops.push_back(TDescr);
7615     if (IsA16)
7616       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7617     Ops.push_back(M->getChain());
7618 
7619     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7620     MachineMemOperand *MemRef = M->getMemOperand();
7621     DAG.setNodeMemRefs(NewNode, {MemRef});
7622     return SDValue(NewNode, 0);
7623   }
7624   case Intrinsic::amdgcn_global_atomic_fadd:
7625     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7626       DiagnosticInfoUnsupported
7627         NoFpRet(DAG.getMachineFunction().getFunction(),
7628                 "return versions of fp atomics not supported",
7629                 DL.getDebugLoc(), DS_Error);
7630       DAG.getContext()->diagnose(NoFpRet);
7631       return SDValue();
7632     }
7633     LLVM_FALLTHROUGH;
7634   case Intrinsic::amdgcn_global_atomic_fmin:
7635   case Intrinsic::amdgcn_global_atomic_fmax:
7636   case Intrinsic::amdgcn_flat_atomic_fadd:
7637   case Intrinsic::amdgcn_flat_atomic_fmin:
7638   case Intrinsic::amdgcn_flat_atomic_fmax: {
7639     MemSDNode *M = cast<MemSDNode>(Op);
7640     SDValue Ops[] = {
7641       M->getOperand(0), // Chain
7642       M->getOperand(2), // Ptr
7643       M->getOperand(3)  // Value
7644     };
7645     unsigned Opcode = 0;
7646     switch (IntrID) {
7647     case Intrinsic::amdgcn_global_atomic_fadd:
7648     case Intrinsic::amdgcn_flat_atomic_fadd: {
7649       EVT VT = Op.getOperand(3).getValueType();
7650       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7651                            DAG.getVTList(VT, MVT::Other), Ops,
7652                            M->getMemOperand());
7653     }
7654     case Intrinsic::amdgcn_global_atomic_fmin:
7655     case Intrinsic::amdgcn_flat_atomic_fmin: {
7656       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7657       break;
7658     }
7659     case Intrinsic::amdgcn_global_atomic_fmax:
7660     case Intrinsic::amdgcn_flat_atomic_fmax: {
7661       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7662       break;
7663     }
7664     default:
7665       llvm_unreachable("unhandled atomic opcode");
7666     }
7667     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7668                                    M->getVTList(), Ops, M->getMemoryVT(),
7669                                    M->getMemOperand());
7670   }
7671   default:
7672 
7673     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7674             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7675       return lowerImage(Op, ImageDimIntr, DAG, true);
7676 
7677     return SDValue();
7678   }
7679 }
7680 
7681 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7682 // dwordx4 if on SI.
7683 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7684                                               SDVTList VTList,
7685                                               ArrayRef<SDValue> Ops, EVT MemVT,
7686                                               MachineMemOperand *MMO,
7687                                               SelectionDAG &DAG) const {
7688   EVT VT = VTList.VTs[0];
7689   EVT WidenedVT = VT;
7690   EVT WidenedMemVT = MemVT;
7691   if (!Subtarget->hasDwordx3LoadStores() &&
7692       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7693     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7694                                  WidenedVT.getVectorElementType(), 4);
7695     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7696                                     WidenedMemVT.getVectorElementType(), 4);
7697     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7698   }
7699 
7700   assert(VTList.NumVTs == 2);
7701   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7702 
7703   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7704                                        WidenedMemVT, MMO);
7705   if (WidenedVT != VT) {
7706     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7707                                DAG.getVectorIdxConstant(0, DL));
7708     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7709   }
7710   return NewOp;
7711 }
7712 
7713 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7714                                          bool ImageStore) const {
7715   EVT StoreVT = VData.getValueType();
7716 
7717   // No change for f16 and legal vector D16 types.
7718   if (!StoreVT.isVector())
7719     return VData;
7720 
7721   SDLoc DL(VData);
7722   unsigned NumElements = StoreVT.getVectorNumElements();
7723 
7724   if (Subtarget->hasUnpackedD16VMem()) {
7725     // We need to unpack the packed data to store.
7726     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7727     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7728 
7729     EVT EquivStoreVT =
7730         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7731     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7732     return DAG.UnrollVectorOp(ZExt.getNode());
7733   }
7734 
7735   // The sq block of gfx8.1 does not estimate register use correctly for d16
7736   // image store instructions. The data operand is computed as if it were not a
7737   // d16 image instruction.
7738   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7739     // Bitcast to i16
7740     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7741     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7742 
7743     // Decompose into scalars
7744     SmallVector<SDValue, 4> Elts;
7745     DAG.ExtractVectorElements(IntVData, Elts);
7746 
7747     // Group pairs of i16 into v2i16 and bitcast to i32
7748     SmallVector<SDValue, 4> PackedElts;
7749     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7750       SDValue Pair =
7751           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7752       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7753       PackedElts.push_back(IntPair);
7754     }
7755     if ((NumElements % 2) == 1) {
7756       // Handle v3i16
7757       unsigned I = Elts.size() / 2;
7758       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7759                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7760       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7761       PackedElts.push_back(IntPair);
7762     }
7763 
7764     // Pad using UNDEF
7765     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7766 
7767     // Build final vector
7768     EVT VecVT =
7769         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7770     return DAG.getBuildVector(VecVT, DL, PackedElts);
7771   }
7772 
7773   if (NumElements == 3) {
7774     EVT IntStoreVT =
7775         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7776     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7777 
7778     EVT WidenedStoreVT = EVT::getVectorVT(
7779         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7780     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7781                                          WidenedStoreVT.getStoreSizeInBits());
7782     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7783     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7784   }
7785 
7786   assert(isTypeLegal(StoreVT));
7787   return VData;
7788 }
7789 
7790 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7791                                               SelectionDAG &DAG) const {
7792   SDLoc DL(Op);
7793   SDValue Chain = Op.getOperand(0);
7794   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7795   MachineFunction &MF = DAG.getMachineFunction();
7796 
7797   switch (IntrinsicID) {
7798   case Intrinsic::amdgcn_exp_compr: {
7799     SDValue Src0 = Op.getOperand(4);
7800     SDValue Src1 = Op.getOperand(5);
7801     // Hack around illegal type on SI by directly selecting it.
7802     if (isTypeLegal(Src0.getValueType()))
7803       return SDValue();
7804 
7805     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7806     SDValue Undef = DAG.getUNDEF(MVT::f32);
7807     const SDValue Ops[] = {
7808       Op.getOperand(2), // tgt
7809       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7810       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7811       Undef, // src2
7812       Undef, // src3
7813       Op.getOperand(7), // vm
7814       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7815       Op.getOperand(3), // en
7816       Op.getOperand(0) // Chain
7817     };
7818 
7819     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7820     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7821   }
7822   case Intrinsic::amdgcn_s_barrier: {
7823     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7824       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7825       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7826       if (WGSize <= ST.getWavefrontSize())
7827         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7828                                           Op.getOperand(0)), 0);
7829     }
7830     return SDValue();
7831   };
7832   case Intrinsic::amdgcn_tbuffer_store: {
7833     SDValue VData = Op.getOperand(2);
7834     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7835     if (IsD16)
7836       VData = handleD16VData(VData, DAG);
7837     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7838     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7839     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7840     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7841     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7842     SDValue Ops[] = {
7843       Chain,
7844       VData,             // vdata
7845       Op.getOperand(3),  // rsrc
7846       Op.getOperand(4),  // vindex
7847       Op.getOperand(5),  // voffset
7848       Op.getOperand(6),  // soffset
7849       Op.getOperand(7),  // offset
7850       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7851       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7852       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7853     };
7854     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7855                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7856     MemSDNode *M = cast<MemSDNode>(Op);
7857     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7858                                    M->getMemoryVT(), M->getMemOperand());
7859   }
7860 
7861   case Intrinsic::amdgcn_struct_tbuffer_store: {
7862     SDValue VData = Op.getOperand(2);
7863     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7864     if (IsD16)
7865       VData = handleD16VData(VData, DAG);
7866     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7867     SDValue Ops[] = {
7868       Chain,
7869       VData,             // vdata
7870       Op.getOperand(3),  // rsrc
7871       Op.getOperand(4),  // vindex
7872       Offsets.first,     // voffset
7873       Op.getOperand(6),  // soffset
7874       Offsets.second,    // offset
7875       Op.getOperand(7),  // format
7876       Op.getOperand(8),  // cachepolicy, swizzled buffer
7877       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7878     };
7879     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7880                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7881     MemSDNode *M = cast<MemSDNode>(Op);
7882     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7883                                    M->getMemoryVT(), M->getMemOperand());
7884   }
7885 
7886   case Intrinsic::amdgcn_raw_tbuffer_store: {
7887     SDValue VData = Op.getOperand(2);
7888     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7889     if (IsD16)
7890       VData = handleD16VData(VData, DAG);
7891     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7892     SDValue Ops[] = {
7893       Chain,
7894       VData,             // vdata
7895       Op.getOperand(3),  // rsrc
7896       DAG.getConstant(0, DL, MVT::i32), // vindex
7897       Offsets.first,     // voffset
7898       Op.getOperand(5),  // soffset
7899       Offsets.second,    // offset
7900       Op.getOperand(6),  // format
7901       Op.getOperand(7),  // cachepolicy, swizzled buffer
7902       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7903     };
7904     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7905                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7906     MemSDNode *M = cast<MemSDNode>(Op);
7907     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7908                                    M->getMemoryVT(), M->getMemOperand());
7909   }
7910 
7911   case Intrinsic::amdgcn_buffer_store:
7912   case Intrinsic::amdgcn_buffer_store_format: {
7913     SDValue VData = Op.getOperand(2);
7914     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7915     if (IsD16)
7916       VData = handleD16VData(VData, DAG);
7917     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7918     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7919     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7920     SDValue Ops[] = {
7921       Chain,
7922       VData,
7923       Op.getOperand(3), // rsrc
7924       Op.getOperand(4), // vindex
7925       SDValue(), // voffset -- will be set by setBufferOffsets
7926       SDValue(), // soffset -- will be set by setBufferOffsets
7927       SDValue(), // offset -- will be set by setBufferOffsets
7928       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7929       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7930     };
7931     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7932 
7933     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7934                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7935     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7936     MemSDNode *M = cast<MemSDNode>(Op);
7937     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7938 
7939     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7940     EVT VDataType = VData.getValueType().getScalarType();
7941     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7942       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7943 
7944     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7945                                    M->getMemoryVT(), M->getMemOperand());
7946   }
7947 
7948   case Intrinsic::amdgcn_raw_buffer_store:
7949   case Intrinsic::amdgcn_raw_buffer_store_format: {
7950     const bool IsFormat =
7951         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7952 
7953     SDValue VData = Op.getOperand(2);
7954     EVT VDataVT = VData.getValueType();
7955     EVT EltType = VDataVT.getScalarType();
7956     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7957     if (IsD16) {
7958       VData = handleD16VData(VData, DAG);
7959       VDataVT = VData.getValueType();
7960     }
7961 
7962     if (!isTypeLegal(VDataVT)) {
7963       VData =
7964           DAG.getNode(ISD::BITCAST, DL,
7965                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7966     }
7967 
7968     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7969     SDValue Ops[] = {
7970       Chain,
7971       VData,
7972       Op.getOperand(3), // rsrc
7973       DAG.getConstant(0, DL, MVT::i32), // vindex
7974       Offsets.first,    // voffset
7975       Op.getOperand(5), // soffset
7976       Offsets.second,   // offset
7977       Op.getOperand(6), // cachepolicy, swizzled buffer
7978       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7979     };
7980     unsigned Opc =
7981         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7982     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7983     MemSDNode *M = cast<MemSDNode>(Op);
7984     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7985 
7986     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7987     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7988       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7989 
7990     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7991                                    M->getMemoryVT(), M->getMemOperand());
7992   }
7993 
7994   case Intrinsic::amdgcn_struct_buffer_store:
7995   case Intrinsic::amdgcn_struct_buffer_store_format: {
7996     const bool IsFormat =
7997         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7998 
7999     SDValue VData = Op.getOperand(2);
8000     EVT VDataVT = VData.getValueType();
8001     EVT EltType = VDataVT.getScalarType();
8002     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8003 
8004     if (IsD16) {
8005       VData = handleD16VData(VData, DAG);
8006       VDataVT = VData.getValueType();
8007     }
8008 
8009     if (!isTypeLegal(VDataVT)) {
8010       VData =
8011           DAG.getNode(ISD::BITCAST, DL,
8012                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8013     }
8014 
8015     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8016     SDValue Ops[] = {
8017       Chain,
8018       VData,
8019       Op.getOperand(3), // rsrc
8020       Op.getOperand(4), // vindex
8021       Offsets.first,    // voffset
8022       Op.getOperand(6), // soffset
8023       Offsets.second,   // offset
8024       Op.getOperand(7), // cachepolicy, swizzled buffer
8025       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8026     };
8027     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8028                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8029     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8030     MemSDNode *M = cast<MemSDNode>(Op);
8031     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8032 
8033     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8034     EVT VDataType = VData.getValueType().getScalarType();
8035     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8036       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8037 
8038     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8039                                    M->getMemoryVT(), M->getMemOperand());
8040   }
8041   case Intrinsic::amdgcn_end_cf:
8042     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8043                                       Op->getOperand(2), Chain), 0);
8044 
8045   default: {
8046     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8047             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8048       return lowerImage(Op, ImageDimIntr, DAG, true);
8049 
8050     return Op;
8051   }
8052   }
8053 }
8054 
8055 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8056 // offset (the offset that is included in bounds checking and swizzling, to be
8057 // split between the instruction's voffset and immoffset fields) and soffset
8058 // (the offset that is excluded from bounds checking and swizzling, to go in
8059 // the instruction's soffset field).  This function takes the first kind of
8060 // offset and figures out how to split it between voffset and immoffset.
8061 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8062     SDValue Offset, SelectionDAG &DAG) const {
8063   SDLoc DL(Offset);
8064   const unsigned MaxImm = 4095;
8065   SDValue N0 = Offset;
8066   ConstantSDNode *C1 = nullptr;
8067 
8068   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8069     N0 = SDValue();
8070   else if (DAG.isBaseWithConstantOffset(N0)) {
8071     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8072     N0 = N0.getOperand(0);
8073   }
8074 
8075   if (C1) {
8076     unsigned ImmOffset = C1->getZExtValue();
8077     // If the immediate value is too big for the immoffset field, put the value
8078     // and -4096 into the immoffset field so that the value that is copied/added
8079     // for the voffset field is a multiple of 4096, and it stands more chance
8080     // of being CSEd with the copy/add for another similar load/store.
8081     // However, do not do that rounding down to a multiple of 4096 if that is a
8082     // negative number, as it appears to be illegal to have a negative offset
8083     // in the vgpr, even if adding the immediate offset makes it positive.
8084     unsigned Overflow = ImmOffset & ~MaxImm;
8085     ImmOffset -= Overflow;
8086     if ((int32_t)Overflow < 0) {
8087       Overflow += ImmOffset;
8088       ImmOffset = 0;
8089     }
8090     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8091     if (Overflow) {
8092       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8093       if (!N0)
8094         N0 = OverflowVal;
8095       else {
8096         SDValue Ops[] = { N0, OverflowVal };
8097         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8098       }
8099     }
8100   }
8101   if (!N0)
8102     N0 = DAG.getConstant(0, DL, MVT::i32);
8103   if (!C1)
8104     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8105   return {N0, SDValue(C1, 0)};
8106 }
8107 
8108 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8109 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8110 // pointed to by Offsets.
8111 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8112                                         SelectionDAG &DAG, SDValue *Offsets,
8113                                         Align Alignment) const {
8114   SDLoc DL(CombinedOffset);
8115   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8116     uint32_t Imm = C->getZExtValue();
8117     uint32_t SOffset, ImmOffset;
8118     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8119                                  Alignment)) {
8120       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8121       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8122       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8123       return;
8124     }
8125   }
8126   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8127     SDValue N0 = CombinedOffset.getOperand(0);
8128     SDValue N1 = CombinedOffset.getOperand(1);
8129     uint32_t SOffset, ImmOffset;
8130     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8131     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8132                                                 Subtarget, Alignment)) {
8133       Offsets[0] = N0;
8134       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8135       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8136       return;
8137     }
8138   }
8139   Offsets[0] = CombinedOffset;
8140   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8141   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8142 }
8143 
8144 // Handle 8 bit and 16 bit buffer loads
8145 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8146                                                      EVT LoadVT, SDLoc DL,
8147                                                      ArrayRef<SDValue> Ops,
8148                                                      MemSDNode *M) const {
8149   EVT IntVT = LoadVT.changeTypeToInteger();
8150   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8151          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8152 
8153   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8154   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8155                                                Ops, IntVT,
8156                                                M->getMemOperand());
8157   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8158   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8159 
8160   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8161 }
8162 
8163 // Handle 8 bit and 16 bit buffer stores
8164 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8165                                                       EVT VDataType, SDLoc DL,
8166                                                       SDValue Ops[],
8167                                                       MemSDNode *M) const {
8168   if (VDataType == MVT::f16)
8169     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8170 
8171   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8172   Ops[1] = BufferStoreExt;
8173   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8174                                  AMDGPUISD::BUFFER_STORE_SHORT;
8175   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8176   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8177                                      M->getMemOperand());
8178 }
8179 
8180 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8181                                  ISD::LoadExtType ExtType, SDValue Op,
8182                                  const SDLoc &SL, EVT VT) {
8183   if (VT.bitsLT(Op.getValueType()))
8184     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8185 
8186   switch (ExtType) {
8187   case ISD::SEXTLOAD:
8188     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8189   case ISD::ZEXTLOAD:
8190     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8191   case ISD::EXTLOAD:
8192     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8193   case ISD::NON_EXTLOAD:
8194     return Op;
8195   }
8196 
8197   llvm_unreachable("invalid ext type");
8198 }
8199 
8200 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8201   SelectionDAG &DAG = DCI.DAG;
8202   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8203     return SDValue();
8204 
8205   // FIXME: Constant loads should all be marked invariant.
8206   unsigned AS = Ld->getAddressSpace();
8207   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8208       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8209       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8210     return SDValue();
8211 
8212   // Don't do this early, since it may interfere with adjacent load merging for
8213   // illegal types. We can avoid losing alignment information for exotic types
8214   // pre-legalize.
8215   EVT MemVT = Ld->getMemoryVT();
8216   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8217       MemVT.getSizeInBits() >= 32)
8218     return SDValue();
8219 
8220   SDLoc SL(Ld);
8221 
8222   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8223          "unexpected vector extload");
8224 
8225   // TODO: Drop only high part of range.
8226   SDValue Ptr = Ld->getBasePtr();
8227   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8228                                 MVT::i32, SL, Ld->getChain(), Ptr,
8229                                 Ld->getOffset(),
8230                                 Ld->getPointerInfo(), MVT::i32,
8231                                 Ld->getAlignment(),
8232                                 Ld->getMemOperand()->getFlags(),
8233                                 Ld->getAAInfo(),
8234                                 nullptr); // Drop ranges
8235 
8236   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8237   if (MemVT.isFloatingPoint()) {
8238     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8239            "unexpected fp extload");
8240     TruncVT = MemVT.changeTypeToInteger();
8241   }
8242 
8243   SDValue Cvt = NewLoad;
8244   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8245     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8246                       DAG.getValueType(TruncVT));
8247   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8248              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8249     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8250   } else {
8251     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8252   }
8253 
8254   EVT VT = Ld->getValueType(0);
8255   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8256 
8257   DCI.AddToWorklist(Cvt.getNode());
8258 
8259   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8260   // the appropriate extension from the 32-bit load.
8261   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8262   DCI.AddToWorklist(Cvt.getNode());
8263 
8264   // Handle conversion back to floating point if necessary.
8265   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8266 
8267   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8268 }
8269 
8270 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8271   SDLoc DL(Op);
8272   LoadSDNode *Load = cast<LoadSDNode>(Op);
8273   ISD::LoadExtType ExtType = Load->getExtensionType();
8274   EVT MemVT = Load->getMemoryVT();
8275 
8276   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8277     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8278       return SDValue();
8279 
8280     // FIXME: Copied from PPC
8281     // First, load into 32 bits, then truncate to 1 bit.
8282 
8283     SDValue Chain = Load->getChain();
8284     SDValue BasePtr = Load->getBasePtr();
8285     MachineMemOperand *MMO = Load->getMemOperand();
8286 
8287     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8288 
8289     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8290                                    BasePtr, RealMemVT, MMO);
8291 
8292     if (!MemVT.isVector()) {
8293       SDValue Ops[] = {
8294         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8295         NewLD.getValue(1)
8296       };
8297 
8298       return DAG.getMergeValues(Ops, DL);
8299     }
8300 
8301     SmallVector<SDValue, 3> Elts;
8302     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8303       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8304                                 DAG.getConstant(I, DL, MVT::i32));
8305 
8306       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8307     }
8308 
8309     SDValue Ops[] = {
8310       DAG.getBuildVector(MemVT, DL, Elts),
8311       NewLD.getValue(1)
8312     };
8313 
8314     return DAG.getMergeValues(Ops, DL);
8315   }
8316 
8317   if (!MemVT.isVector())
8318     return SDValue();
8319 
8320   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8321          "Custom lowering for non-i32 vectors hasn't been implemented.");
8322 
8323   unsigned Alignment = Load->getAlignment();
8324   unsigned AS = Load->getAddressSpace();
8325   if (Subtarget->hasLDSMisalignedBug() &&
8326       AS == AMDGPUAS::FLAT_ADDRESS &&
8327       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8328     return SplitVectorLoad(Op, DAG);
8329   }
8330 
8331   MachineFunction &MF = DAG.getMachineFunction();
8332   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8333   // If there is a possibilty that flat instruction access scratch memory
8334   // then we need to use the same legalization rules we use for private.
8335   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8336       !Subtarget->hasMultiDwordFlatScratchAddressing())
8337     AS = MFI->hasFlatScratchInit() ?
8338          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8339 
8340   unsigned NumElements = MemVT.getVectorNumElements();
8341 
8342   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8343       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8344     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8345       if (MemVT.isPow2VectorType())
8346         return SDValue();
8347       return WidenOrSplitVectorLoad(Op, DAG);
8348     }
8349     // Non-uniform loads will be selected to MUBUF instructions, so they
8350     // have the same legalization requirements as global and private
8351     // loads.
8352     //
8353   }
8354 
8355   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8356       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8357       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8358     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8359         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8360         Alignment >= 4 && NumElements < 32) {
8361       if (MemVT.isPow2VectorType())
8362         return SDValue();
8363       return WidenOrSplitVectorLoad(Op, DAG);
8364     }
8365     // Non-uniform loads will be selected to MUBUF instructions, so they
8366     // have the same legalization requirements as global and private
8367     // loads.
8368     //
8369   }
8370   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8371       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8372       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8373       AS == AMDGPUAS::FLAT_ADDRESS) {
8374     if (NumElements > 4)
8375       return SplitVectorLoad(Op, DAG);
8376     // v3 loads not supported on SI.
8377     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8378       return WidenOrSplitVectorLoad(Op, DAG);
8379 
8380     // v3 and v4 loads are supported for private and global memory.
8381     return SDValue();
8382   }
8383   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8384     // Depending on the setting of the private_element_size field in the
8385     // resource descriptor, we can only make private accesses up to a certain
8386     // size.
8387     switch (Subtarget->getMaxPrivateElementSize()) {
8388     case 4: {
8389       SDValue Ops[2];
8390       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8391       return DAG.getMergeValues(Ops, DL);
8392     }
8393     case 8:
8394       if (NumElements > 2)
8395         return SplitVectorLoad(Op, DAG);
8396       return SDValue();
8397     case 16:
8398       // Same as global/flat
8399       if (NumElements > 4)
8400         return SplitVectorLoad(Op, DAG);
8401       // v3 loads not supported on SI.
8402       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8403         return WidenOrSplitVectorLoad(Op, DAG);
8404 
8405       return SDValue();
8406     default:
8407       llvm_unreachable("unsupported private_element_size");
8408     }
8409   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8410     // Use ds_read_b128 or ds_read_b96 when possible.
8411     if (Subtarget->hasDS96AndDS128() &&
8412         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8413          MemVT.getStoreSize() == 12) &&
8414         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8415                                            Load->getAlign()))
8416       return SDValue();
8417 
8418     if (NumElements > 2)
8419       return SplitVectorLoad(Op, DAG);
8420 
8421     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8422     // address is negative, then the instruction is incorrectly treated as
8423     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8424     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8425     // load later in the SILoadStoreOptimizer.
8426     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8427         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8428         Load->getAlignment() < 8) {
8429       return SplitVectorLoad(Op, DAG);
8430     }
8431   }
8432 
8433   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8434                                       MemVT, *Load->getMemOperand())) {
8435     SDValue Ops[2];
8436     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8437     return DAG.getMergeValues(Ops, DL);
8438   }
8439 
8440   return SDValue();
8441 }
8442 
8443 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8444   EVT VT = Op.getValueType();
8445   assert(VT.getSizeInBits() == 64);
8446 
8447   SDLoc DL(Op);
8448   SDValue Cond = Op.getOperand(0);
8449 
8450   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8451   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8452 
8453   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8454   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8455 
8456   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8457   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8458 
8459   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8460 
8461   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8462   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8463 
8464   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8465 
8466   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8467   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8468 }
8469 
8470 // Catch division cases where we can use shortcuts with rcp and rsq
8471 // instructions.
8472 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8473                                               SelectionDAG &DAG) const {
8474   SDLoc SL(Op);
8475   SDValue LHS = Op.getOperand(0);
8476   SDValue RHS = Op.getOperand(1);
8477   EVT VT = Op.getValueType();
8478   const SDNodeFlags Flags = Op->getFlags();
8479 
8480   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8481 
8482   // Without !fpmath accuracy information, we can't do more because we don't
8483   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8484   if (!AllowInaccurateRcp)
8485     return SDValue();
8486 
8487   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8488     if (CLHS->isExactlyValue(1.0)) {
8489       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8490       // the CI documentation has a worst case error of 1 ulp.
8491       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8492       // use it as long as we aren't trying to use denormals.
8493       //
8494       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8495 
8496       // 1.0 / sqrt(x) -> rsq(x)
8497 
8498       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8499       // error seems really high at 2^29 ULP.
8500       if (RHS.getOpcode() == ISD::FSQRT)
8501         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8502 
8503       // 1.0 / x -> rcp(x)
8504       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8505     }
8506 
8507     // Same as for 1.0, but expand the sign out of the constant.
8508     if (CLHS->isExactlyValue(-1.0)) {
8509       // -1.0 / x -> rcp (fneg x)
8510       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8511       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8512     }
8513   }
8514 
8515   // Turn into multiply by the reciprocal.
8516   // x / y -> x * (1.0 / y)
8517   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8518   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8519 }
8520 
8521 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8522                                                 SelectionDAG &DAG) const {
8523   SDLoc SL(Op);
8524   SDValue X = Op.getOperand(0);
8525   SDValue Y = Op.getOperand(1);
8526   EVT VT = Op.getValueType();
8527   const SDNodeFlags Flags = Op->getFlags();
8528 
8529   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8530                             DAG.getTarget().Options.UnsafeFPMath;
8531   if (!AllowInaccurateDiv)
8532     return SDValue();
8533 
8534   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8535   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8536 
8537   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8538   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8539 
8540   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8541   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8542   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8543   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8544   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8545   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8546 }
8547 
8548 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8549                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8550                           SDNodeFlags Flags) {
8551   if (GlueChain->getNumValues() <= 1) {
8552     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8553   }
8554 
8555   assert(GlueChain->getNumValues() == 3);
8556 
8557   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8558   switch (Opcode) {
8559   default: llvm_unreachable("no chain equivalent for opcode");
8560   case ISD::FMUL:
8561     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8562     break;
8563   }
8564 
8565   return DAG.getNode(Opcode, SL, VTList,
8566                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8567                      Flags);
8568 }
8569 
8570 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8571                            EVT VT, SDValue A, SDValue B, SDValue C,
8572                            SDValue GlueChain, SDNodeFlags Flags) {
8573   if (GlueChain->getNumValues() <= 1) {
8574     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8575   }
8576 
8577   assert(GlueChain->getNumValues() == 3);
8578 
8579   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8580   switch (Opcode) {
8581   default: llvm_unreachable("no chain equivalent for opcode");
8582   case ISD::FMA:
8583     Opcode = AMDGPUISD::FMA_W_CHAIN;
8584     break;
8585   }
8586 
8587   return DAG.getNode(Opcode, SL, VTList,
8588                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8589                      Flags);
8590 }
8591 
8592 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8593   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8594     return FastLowered;
8595 
8596   SDLoc SL(Op);
8597   SDValue Src0 = Op.getOperand(0);
8598   SDValue Src1 = Op.getOperand(1);
8599 
8600   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8601   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8602 
8603   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8604   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8605 
8606   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8607   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8608 
8609   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8610 }
8611 
8612 // Faster 2.5 ULP division that does not support denormals.
8613 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8614   SDLoc SL(Op);
8615   SDValue LHS = Op.getOperand(1);
8616   SDValue RHS = Op.getOperand(2);
8617 
8618   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8619 
8620   const APFloat K0Val(BitsToFloat(0x6f800000));
8621   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8622 
8623   const APFloat K1Val(BitsToFloat(0x2f800000));
8624   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8625 
8626   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8627 
8628   EVT SetCCVT =
8629     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8630 
8631   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8632 
8633   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8634 
8635   // TODO: Should this propagate fast-math-flags?
8636   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8637 
8638   // rcp does not support denormals.
8639   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8640 
8641   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8642 
8643   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8644 }
8645 
8646 // Returns immediate value for setting the F32 denorm mode when using the
8647 // S_DENORM_MODE instruction.
8648 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8649                                     const SDLoc &SL, const GCNSubtarget *ST) {
8650   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8651   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8652                                 ? FP_DENORM_FLUSH_NONE
8653                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8654 
8655   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8656   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8657 }
8658 
8659 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8660   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8661     return FastLowered;
8662 
8663   // The selection matcher assumes anything with a chain selecting to a
8664   // mayRaiseFPException machine instruction. Since we're introducing a chain
8665   // here, we need to explicitly report nofpexcept for the regular fdiv
8666   // lowering.
8667   SDNodeFlags Flags = Op->getFlags();
8668   Flags.setNoFPExcept(true);
8669 
8670   SDLoc SL(Op);
8671   SDValue LHS = Op.getOperand(0);
8672   SDValue RHS = Op.getOperand(1);
8673 
8674   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8675 
8676   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8677 
8678   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8679                                           {RHS, RHS, LHS}, Flags);
8680   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8681                                         {LHS, RHS, LHS}, Flags);
8682 
8683   // Denominator is scaled to not be denormal, so using rcp is ok.
8684   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8685                                   DenominatorScaled, Flags);
8686   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8687                                      DenominatorScaled, Flags);
8688 
8689   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8690                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8691                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8692   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8693 
8694   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8695 
8696   if (!HasFP32Denormals) {
8697     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8698     // lowering. The chain dependence is insufficient, and we need glue. We do
8699     // not need the glue variants in a strictfp function.
8700 
8701     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8702 
8703     SDNode *EnableDenorm;
8704     if (Subtarget->hasDenormModeInst()) {
8705       const SDValue EnableDenormValue =
8706           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8707 
8708       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8709                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8710     } else {
8711       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8712                                                         SL, MVT::i32);
8713       EnableDenorm =
8714           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8715                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8716     }
8717 
8718     SDValue Ops[3] = {
8719       NegDivScale0,
8720       SDValue(EnableDenorm, 0),
8721       SDValue(EnableDenorm, 1)
8722     };
8723 
8724     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8725   }
8726 
8727   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8728                              ApproxRcp, One, NegDivScale0, Flags);
8729 
8730   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8731                              ApproxRcp, Fma0, Flags);
8732 
8733   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8734                            Fma1, Fma1, Flags);
8735 
8736   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8737                              NumeratorScaled, Mul, Flags);
8738 
8739   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8740                              Fma2, Fma1, Mul, Fma2, Flags);
8741 
8742   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8743                              NumeratorScaled, Fma3, Flags);
8744 
8745   if (!HasFP32Denormals) {
8746     SDNode *DisableDenorm;
8747     if (Subtarget->hasDenormModeInst()) {
8748       const SDValue DisableDenormValue =
8749           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8750 
8751       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8752                                   Fma4.getValue(1), DisableDenormValue,
8753                                   Fma4.getValue(2)).getNode();
8754     } else {
8755       const SDValue DisableDenormValue =
8756           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8757 
8758       DisableDenorm = DAG.getMachineNode(
8759           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8760           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8761     }
8762 
8763     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8764                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8765     DAG.setRoot(OutputChain);
8766   }
8767 
8768   SDValue Scale = NumeratorScaled.getValue(1);
8769   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8770                              {Fma4, Fma1, Fma3, Scale}, Flags);
8771 
8772   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8773 }
8774 
8775 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8776   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8777     return FastLowered;
8778 
8779   SDLoc SL(Op);
8780   SDValue X = Op.getOperand(0);
8781   SDValue Y = Op.getOperand(1);
8782 
8783   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8784 
8785   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8786 
8787   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8788 
8789   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8790 
8791   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8792 
8793   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8794 
8795   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8796 
8797   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8798 
8799   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8800 
8801   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8802   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8803 
8804   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8805                              NegDivScale0, Mul, DivScale1);
8806 
8807   SDValue Scale;
8808 
8809   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8810     // Workaround a hardware bug on SI where the condition output from div_scale
8811     // is not usable.
8812 
8813     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8814 
8815     // Figure out if the scale to use for div_fmas.
8816     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8817     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8818     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8819     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8820 
8821     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8822     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8823 
8824     SDValue Scale0Hi
8825       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8826     SDValue Scale1Hi
8827       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8828 
8829     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8830     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8831     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8832   } else {
8833     Scale = DivScale1.getValue(1);
8834   }
8835 
8836   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8837                              Fma4, Fma3, Mul, Scale);
8838 
8839   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8840 }
8841 
8842 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8843   EVT VT = Op.getValueType();
8844 
8845   if (VT == MVT::f32)
8846     return LowerFDIV32(Op, DAG);
8847 
8848   if (VT == MVT::f64)
8849     return LowerFDIV64(Op, DAG);
8850 
8851   if (VT == MVT::f16)
8852     return LowerFDIV16(Op, DAG);
8853 
8854   llvm_unreachable("Unexpected type for fdiv");
8855 }
8856 
8857 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8858   SDLoc DL(Op);
8859   StoreSDNode *Store = cast<StoreSDNode>(Op);
8860   EVT VT = Store->getMemoryVT();
8861 
8862   if (VT == MVT::i1) {
8863     return DAG.getTruncStore(Store->getChain(), DL,
8864        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8865        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8866   }
8867 
8868   assert(VT.isVector() &&
8869          Store->getValue().getValueType().getScalarType() == MVT::i32);
8870 
8871   unsigned AS = Store->getAddressSpace();
8872   if (Subtarget->hasLDSMisalignedBug() &&
8873       AS == AMDGPUAS::FLAT_ADDRESS &&
8874       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8875     return SplitVectorStore(Op, DAG);
8876   }
8877 
8878   MachineFunction &MF = DAG.getMachineFunction();
8879   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8880   // If there is a possibilty that flat instruction access scratch memory
8881   // then we need to use the same legalization rules we use for private.
8882   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8883       !Subtarget->hasMultiDwordFlatScratchAddressing())
8884     AS = MFI->hasFlatScratchInit() ?
8885          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8886 
8887   unsigned NumElements = VT.getVectorNumElements();
8888   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8889       AS == AMDGPUAS::FLAT_ADDRESS) {
8890     if (NumElements > 4)
8891       return SplitVectorStore(Op, DAG);
8892     // v3 stores not supported on SI.
8893     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8894       return SplitVectorStore(Op, DAG);
8895 
8896     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8897                                         VT, *Store->getMemOperand()))
8898       return expandUnalignedStore(Store, DAG);
8899 
8900     return SDValue();
8901   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8902     switch (Subtarget->getMaxPrivateElementSize()) {
8903     case 4:
8904       return scalarizeVectorStore(Store, DAG);
8905     case 8:
8906       if (NumElements > 2)
8907         return SplitVectorStore(Op, DAG);
8908       return SDValue();
8909     case 16:
8910       if (NumElements > 4 ||
8911           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8912         return SplitVectorStore(Op, DAG);
8913       return SDValue();
8914     default:
8915       llvm_unreachable("unsupported private_element_size");
8916     }
8917   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8918     // Use ds_write_b128 or ds_write_b96 when possible.
8919     if (Subtarget->hasDS96AndDS128() &&
8920         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8921          (VT.getStoreSize() == 12)) &&
8922         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8923                                            Store->getAlign()))
8924       return SDValue();
8925 
8926     if (NumElements > 2)
8927       return SplitVectorStore(Op, DAG);
8928 
8929     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8930     // address is negative, then the instruction is incorrectly treated as
8931     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8932     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8933     // store later in the SILoadStoreOptimizer.
8934     if (!Subtarget->hasUsableDSOffset() &&
8935         NumElements == 2 && VT.getStoreSize() == 8 &&
8936         Store->getAlignment() < 8) {
8937       return SplitVectorStore(Op, DAG);
8938     }
8939 
8940     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8941                                         VT, *Store->getMemOperand())) {
8942       if (VT.isVector())
8943         return SplitVectorStore(Op, DAG);
8944       return expandUnalignedStore(Store, DAG);
8945     }
8946 
8947     return SDValue();
8948   } else {
8949     llvm_unreachable("unhandled address space");
8950   }
8951 }
8952 
8953 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8954   SDLoc DL(Op);
8955   EVT VT = Op.getValueType();
8956   SDValue Arg = Op.getOperand(0);
8957   SDValue TrigVal;
8958 
8959   // Propagate fast-math flags so that the multiply we introduce can be folded
8960   // if Arg is already the result of a multiply by constant.
8961   auto Flags = Op->getFlags();
8962 
8963   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8964 
8965   if (Subtarget->hasTrigReducedRange()) {
8966     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8967     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8968   } else {
8969     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8970   }
8971 
8972   switch (Op.getOpcode()) {
8973   case ISD::FCOS:
8974     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8975   case ISD::FSIN:
8976     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8977   default:
8978     llvm_unreachable("Wrong trig opcode");
8979   }
8980 }
8981 
8982 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8983   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8984   assert(AtomicNode->isCompareAndSwap());
8985   unsigned AS = AtomicNode->getAddressSpace();
8986 
8987   // No custom lowering required for local address space
8988   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8989     return Op;
8990 
8991   // Non-local address space requires custom lowering for atomic compare
8992   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8993   SDLoc DL(Op);
8994   SDValue ChainIn = Op.getOperand(0);
8995   SDValue Addr = Op.getOperand(1);
8996   SDValue Old = Op.getOperand(2);
8997   SDValue New = Op.getOperand(3);
8998   EVT VT = Op.getValueType();
8999   MVT SimpleVT = VT.getSimpleVT();
9000   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9001 
9002   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9003   SDValue Ops[] = { ChainIn, Addr, NewOld };
9004 
9005   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9006                                  Ops, VT, AtomicNode->getMemOperand());
9007 }
9008 
9009 //===----------------------------------------------------------------------===//
9010 // Custom DAG optimizations
9011 //===----------------------------------------------------------------------===//
9012 
9013 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9014                                                      DAGCombinerInfo &DCI) const {
9015   EVT VT = N->getValueType(0);
9016   EVT ScalarVT = VT.getScalarType();
9017   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9018     return SDValue();
9019 
9020   SelectionDAG &DAG = DCI.DAG;
9021   SDLoc DL(N);
9022 
9023   SDValue Src = N->getOperand(0);
9024   EVT SrcVT = Src.getValueType();
9025 
9026   // TODO: We could try to match extracting the higher bytes, which would be
9027   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9028   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9029   // about in practice.
9030   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9031     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9032       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9033       DCI.AddToWorklist(Cvt.getNode());
9034 
9035       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9036       if (ScalarVT != MVT::f32) {
9037         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9038                           DAG.getTargetConstant(0, DL, MVT::i32));
9039       }
9040       return Cvt;
9041     }
9042   }
9043 
9044   return SDValue();
9045 }
9046 
9047 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9048 
9049 // This is a variant of
9050 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9051 //
9052 // The normal DAG combiner will do this, but only if the add has one use since
9053 // that would increase the number of instructions.
9054 //
9055 // This prevents us from seeing a constant offset that can be folded into a
9056 // memory instruction's addressing mode. If we know the resulting add offset of
9057 // a pointer can be folded into an addressing offset, we can replace the pointer
9058 // operand with the add of new constant offset. This eliminates one of the uses,
9059 // and may allow the remaining use to also be simplified.
9060 //
9061 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9062                                                unsigned AddrSpace,
9063                                                EVT MemVT,
9064                                                DAGCombinerInfo &DCI) const {
9065   SDValue N0 = N->getOperand(0);
9066   SDValue N1 = N->getOperand(1);
9067 
9068   // We only do this to handle cases where it's profitable when there are
9069   // multiple uses of the add, so defer to the standard combine.
9070   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9071       N0->hasOneUse())
9072     return SDValue();
9073 
9074   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9075   if (!CN1)
9076     return SDValue();
9077 
9078   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9079   if (!CAdd)
9080     return SDValue();
9081 
9082   // If the resulting offset is too large, we can't fold it into the addressing
9083   // mode offset.
9084   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9085   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9086 
9087   AddrMode AM;
9088   AM.HasBaseReg = true;
9089   AM.BaseOffs = Offset.getSExtValue();
9090   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9091     return SDValue();
9092 
9093   SelectionDAG &DAG = DCI.DAG;
9094   SDLoc SL(N);
9095   EVT VT = N->getValueType(0);
9096 
9097   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9098   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9099 
9100   SDNodeFlags Flags;
9101   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9102                           (N0.getOpcode() == ISD::OR ||
9103                            N0->getFlags().hasNoUnsignedWrap()));
9104 
9105   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9106 }
9107 
9108 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9109 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9110 /// specific intrinsic, but they all place the pointer operand first.
9111 static unsigned getBasePtrIndex(const MemSDNode *N) {
9112   switch (N->getOpcode()) {
9113   case ISD::STORE:
9114   case ISD::INTRINSIC_W_CHAIN:
9115   case ISD::INTRINSIC_VOID:
9116     return 2;
9117   default:
9118     return 1;
9119   }
9120 }
9121 
9122 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9123                                                   DAGCombinerInfo &DCI) const {
9124   SelectionDAG &DAG = DCI.DAG;
9125   SDLoc SL(N);
9126 
9127   unsigned PtrIdx = getBasePtrIndex(N);
9128   SDValue Ptr = N->getOperand(PtrIdx);
9129 
9130   // TODO: We could also do this for multiplies.
9131   if (Ptr.getOpcode() == ISD::SHL) {
9132     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9133                                           N->getMemoryVT(), DCI);
9134     if (NewPtr) {
9135       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9136 
9137       NewOps[PtrIdx] = NewPtr;
9138       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9139     }
9140   }
9141 
9142   return SDValue();
9143 }
9144 
9145 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9146   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9147          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9148          (Opc == ISD::XOR && Val == 0);
9149 }
9150 
9151 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9152 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9153 // integer combine opportunities since most 64-bit operations are decomposed
9154 // this way.  TODO: We won't want this for SALU especially if it is an inline
9155 // immediate.
9156 SDValue SITargetLowering::splitBinaryBitConstantOp(
9157   DAGCombinerInfo &DCI,
9158   const SDLoc &SL,
9159   unsigned Opc, SDValue LHS,
9160   const ConstantSDNode *CRHS) const {
9161   uint64_t Val = CRHS->getZExtValue();
9162   uint32_t ValLo = Lo_32(Val);
9163   uint32_t ValHi = Hi_32(Val);
9164   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9165 
9166     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9167          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9168         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9169     // If we need to materialize a 64-bit immediate, it will be split up later
9170     // anyway. Avoid creating the harder to understand 64-bit immediate
9171     // materialization.
9172     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9173   }
9174 
9175   return SDValue();
9176 }
9177 
9178 // Returns true if argument is a boolean value which is not serialized into
9179 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9180 static bool isBoolSGPR(SDValue V) {
9181   if (V.getValueType() != MVT::i1)
9182     return false;
9183   switch (V.getOpcode()) {
9184   default:
9185     break;
9186   case ISD::SETCC:
9187   case AMDGPUISD::FP_CLASS:
9188     return true;
9189   case ISD::AND:
9190   case ISD::OR:
9191   case ISD::XOR:
9192     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9193   }
9194   return false;
9195 }
9196 
9197 // If a constant has all zeroes or all ones within each byte return it.
9198 // Otherwise return 0.
9199 static uint32_t getConstantPermuteMask(uint32_t C) {
9200   // 0xff for any zero byte in the mask
9201   uint32_t ZeroByteMask = 0;
9202   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9203   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9204   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9205   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9206   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9207   if ((NonZeroByteMask & C) != NonZeroByteMask)
9208     return 0; // Partial bytes selected.
9209   return C;
9210 }
9211 
9212 // Check if a node selects whole bytes from its operand 0 starting at a byte
9213 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9214 // or -1 if not succeeded.
9215 // Note byte select encoding:
9216 // value 0-3 selects corresponding source byte;
9217 // value 0xc selects zero;
9218 // value 0xff selects 0xff.
9219 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9220   assert(V.getValueSizeInBits() == 32);
9221 
9222   if (V.getNumOperands() != 2)
9223     return ~0;
9224 
9225   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9226   if (!N1)
9227     return ~0;
9228 
9229   uint32_t C = N1->getZExtValue();
9230 
9231   switch (V.getOpcode()) {
9232   default:
9233     break;
9234   case ISD::AND:
9235     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9236       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9237     }
9238     break;
9239 
9240   case ISD::OR:
9241     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9242       return (0x03020100 & ~ConstMask) | ConstMask;
9243     }
9244     break;
9245 
9246   case ISD::SHL:
9247     if (C % 8)
9248       return ~0;
9249 
9250     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9251 
9252   case ISD::SRL:
9253     if (C % 8)
9254       return ~0;
9255 
9256     return uint32_t(0x0c0c0c0c03020100ull >> C);
9257   }
9258 
9259   return ~0;
9260 }
9261 
9262 SDValue SITargetLowering::performAndCombine(SDNode *N,
9263                                             DAGCombinerInfo &DCI) const {
9264   if (DCI.isBeforeLegalize())
9265     return SDValue();
9266 
9267   SelectionDAG &DAG = DCI.DAG;
9268   EVT VT = N->getValueType(0);
9269   SDValue LHS = N->getOperand(0);
9270   SDValue RHS = N->getOperand(1);
9271 
9272 
9273   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9274   if (VT == MVT::i64 && CRHS) {
9275     if (SDValue Split
9276         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9277       return Split;
9278   }
9279 
9280   if (CRHS && VT == MVT::i32) {
9281     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9282     // nb = number of trailing zeroes in mask
9283     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9284     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9285     uint64_t Mask = CRHS->getZExtValue();
9286     unsigned Bits = countPopulation(Mask);
9287     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9288         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9289       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9290         unsigned Shift = CShift->getZExtValue();
9291         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9292         unsigned Offset = NB + Shift;
9293         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9294           SDLoc SL(N);
9295           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9296                                     LHS->getOperand(0),
9297                                     DAG.getConstant(Offset, SL, MVT::i32),
9298                                     DAG.getConstant(Bits, SL, MVT::i32));
9299           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9300           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9301                                     DAG.getValueType(NarrowVT));
9302           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9303                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9304           return Shl;
9305         }
9306       }
9307     }
9308 
9309     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9310     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9311         isa<ConstantSDNode>(LHS.getOperand(2))) {
9312       uint32_t Sel = getConstantPermuteMask(Mask);
9313       if (!Sel)
9314         return SDValue();
9315 
9316       // Select 0xc for all zero bytes
9317       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9318       SDLoc DL(N);
9319       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9320                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9321     }
9322   }
9323 
9324   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9325   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9326   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9327     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9328     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9329 
9330     SDValue X = LHS.getOperand(0);
9331     SDValue Y = RHS.getOperand(0);
9332     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9333       return SDValue();
9334 
9335     if (LCC == ISD::SETO) {
9336       if (X != LHS.getOperand(1))
9337         return SDValue();
9338 
9339       if (RCC == ISD::SETUNE) {
9340         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9341         if (!C1 || !C1->isInfinity() || C1->isNegative())
9342           return SDValue();
9343 
9344         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9345                               SIInstrFlags::N_SUBNORMAL |
9346                               SIInstrFlags::N_ZERO |
9347                               SIInstrFlags::P_ZERO |
9348                               SIInstrFlags::P_SUBNORMAL |
9349                               SIInstrFlags::P_NORMAL;
9350 
9351         static_assert(((~(SIInstrFlags::S_NAN |
9352                           SIInstrFlags::Q_NAN |
9353                           SIInstrFlags::N_INFINITY |
9354                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9355                       "mask not equal");
9356 
9357         SDLoc DL(N);
9358         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9359                            X, DAG.getConstant(Mask, DL, MVT::i32));
9360       }
9361     }
9362   }
9363 
9364   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9365     std::swap(LHS, RHS);
9366 
9367   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9368       RHS.hasOneUse()) {
9369     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9370     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9371     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9372     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9373     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9374         (RHS.getOperand(0) == LHS.getOperand(0) &&
9375          LHS.getOperand(0) == LHS.getOperand(1))) {
9376       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9377       unsigned NewMask = LCC == ISD::SETO ?
9378         Mask->getZExtValue() & ~OrdMask :
9379         Mask->getZExtValue() & OrdMask;
9380 
9381       SDLoc DL(N);
9382       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9383                          DAG.getConstant(NewMask, DL, MVT::i32));
9384     }
9385   }
9386 
9387   if (VT == MVT::i32 &&
9388       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9389     // and x, (sext cc from i1) => select cc, x, 0
9390     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9391       std::swap(LHS, RHS);
9392     if (isBoolSGPR(RHS.getOperand(0)))
9393       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9394                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9395   }
9396 
9397   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9398   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9399   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9400       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9401     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9402     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9403     if (LHSMask != ~0u && RHSMask != ~0u) {
9404       // Canonicalize the expression in an attempt to have fewer unique masks
9405       // and therefore fewer registers used to hold the masks.
9406       if (LHSMask > RHSMask) {
9407         std::swap(LHSMask, RHSMask);
9408         std::swap(LHS, RHS);
9409       }
9410 
9411       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9412       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9413       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9414       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9415 
9416       // Check of we need to combine values from two sources within a byte.
9417       if (!(LHSUsedLanes & RHSUsedLanes) &&
9418           // If we select high and lower word keep it for SDWA.
9419           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9420           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9421         // Each byte in each mask is either selector mask 0-3, or has higher
9422         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9423         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9424         // mask which is not 0xff wins. By anding both masks we have a correct
9425         // result except that 0x0c shall be corrected to give 0x0c only.
9426         uint32_t Mask = LHSMask & RHSMask;
9427         for (unsigned I = 0; I < 32; I += 8) {
9428           uint32_t ByteSel = 0xff << I;
9429           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9430             Mask &= (0x0c << I) & 0xffffffff;
9431         }
9432 
9433         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9434         // or 0x0c.
9435         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9436         SDLoc DL(N);
9437 
9438         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9439                            LHS.getOperand(0), RHS.getOperand(0),
9440                            DAG.getConstant(Sel, DL, MVT::i32));
9441       }
9442     }
9443   }
9444 
9445   return SDValue();
9446 }
9447 
9448 SDValue SITargetLowering::performOrCombine(SDNode *N,
9449                                            DAGCombinerInfo &DCI) const {
9450   SelectionDAG &DAG = DCI.DAG;
9451   SDValue LHS = N->getOperand(0);
9452   SDValue RHS = N->getOperand(1);
9453 
9454   EVT VT = N->getValueType(0);
9455   if (VT == MVT::i1) {
9456     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9457     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9458         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9459       SDValue Src = LHS.getOperand(0);
9460       if (Src != RHS.getOperand(0))
9461         return SDValue();
9462 
9463       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9464       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9465       if (!CLHS || !CRHS)
9466         return SDValue();
9467 
9468       // Only 10 bits are used.
9469       static const uint32_t MaxMask = 0x3ff;
9470 
9471       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9472       SDLoc DL(N);
9473       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9474                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9475     }
9476 
9477     return SDValue();
9478   }
9479 
9480   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9481   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9482       LHS.getOpcode() == AMDGPUISD::PERM &&
9483       isa<ConstantSDNode>(LHS.getOperand(2))) {
9484     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9485     if (!Sel)
9486       return SDValue();
9487 
9488     Sel |= LHS.getConstantOperandVal(2);
9489     SDLoc DL(N);
9490     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9491                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9492   }
9493 
9494   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9495   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9496   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9497       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9498     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9499     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9500     if (LHSMask != ~0u && RHSMask != ~0u) {
9501       // Canonicalize the expression in an attempt to have fewer unique masks
9502       // and therefore fewer registers used to hold the masks.
9503       if (LHSMask > RHSMask) {
9504         std::swap(LHSMask, RHSMask);
9505         std::swap(LHS, RHS);
9506       }
9507 
9508       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9509       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9510       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9511       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9512 
9513       // Check of we need to combine values from two sources within a byte.
9514       if (!(LHSUsedLanes & RHSUsedLanes) &&
9515           // If we select high and lower word keep it for SDWA.
9516           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9517           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9518         // Kill zero bytes selected by other mask. Zero value is 0xc.
9519         LHSMask &= ~RHSUsedLanes;
9520         RHSMask &= ~LHSUsedLanes;
9521         // Add 4 to each active LHS lane
9522         LHSMask |= LHSUsedLanes & 0x04040404;
9523         // Combine masks
9524         uint32_t Sel = LHSMask | RHSMask;
9525         SDLoc DL(N);
9526 
9527         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9528                            LHS.getOperand(0), RHS.getOperand(0),
9529                            DAG.getConstant(Sel, DL, MVT::i32));
9530       }
9531     }
9532   }
9533 
9534   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9535     return SDValue();
9536 
9537   // TODO: This could be a generic combine with a predicate for extracting the
9538   // high half of an integer being free.
9539 
9540   // (or i64:x, (zero_extend i32:y)) ->
9541   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9542   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9543       RHS.getOpcode() != ISD::ZERO_EXTEND)
9544     std::swap(LHS, RHS);
9545 
9546   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9547     SDValue ExtSrc = RHS.getOperand(0);
9548     EVT SrcVT = ExtSrc.getValueType();
9549     if (SrcVT == MVT::i32) {
9550       SDLoc SL(N);
9551       SDValue LowLHS, HiBits;
9552       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9553       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9554 
9555       DCI.AddToWorklist(LowOr.getNode());
9556       DCI.AddToWorklist(HiBits.getNode());
9557 
9558       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9559                                 LowOr, HiBits);
9560       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9561     }
9562   }
9563 
9564   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9565   if (CRHS) {
9566     if (SDValue Split
9567           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9568                                      N->getOperand(0), CRHS))
9569       return Split;
9570   }
9571 
9572   return SDValue();
9573 }
9574 
9575 SDValue SITargetLowering::performXorCombine(SDNode *N,
9576                                             DAGCombinerInfo &DCI) const {
9577   EVT VT = N->getValueType(0);
9578   if (VT != MVT::i64)
9579     return SDValue();
9580 
9581   SDValue LHS = N->getOperand(0);
9582   SDValue RHS = N->getOperand(1);
9583 
9584   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9585   if (CRHS) {
9586     if (SDValue Split
9587           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9588       return Split;
9589   }
9590 
9591   return SDValue();
9592 }
9593 
9594 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9595                                                    DAGCombinerInfo &DCI) const {
9596   if (!Subtarget->has16BitInsts() ||
9597       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9598     return SDValue();
9599 
9600   EVT VT = N->getValueType(0);
9601   if (VT != MVT::i32)
9602     return SDValue();
9603 
9604   SDValue Src = N->getOperand(0);
9605   if (Src.getValueType() != MVT::i16)
9606     return SDValue();
9607 
9608   return SDValue();
9609 }
9610 
9611 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9612                                                         DAGCombinerInfo &DCI)
9613                                                         const {
9614   SDValue Src = N->getOperand(0);
9615   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9616 
9617   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9618       VTSign->getVT() == MVT::i8) ||
9619       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9620       VTSign->getVT() == MVT::i16)) &&
9621       Src.hasOneUse()) {
9622     auto *M = cast<MemSDNode>(Src);
9623     SDValue Ops[] = {
9624       Src.getOperand(0), // Chain
9625       Src.getOperand(1), // rsrc
9626       Src.getOperand(2), // vindex
9627       Src.getOperand(3), // voffset
9628       Src.getOperand(4), // soffset
9629       Src.getOperand(5), // offset
9630       Src.getOperand(6),
9631       Src.getOperand(7)
9632     };
9633     // replace with BUFFER_LOAD_BYTE/SHORT
9634     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9635                                          Src.getOperand(0).getValueType());
9636     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9637                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9638     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9639                                                           ResList,
9640                                                           Ops, M->getMemoryVT(),
9641                                                           M->getMemOperand());
9642     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9643                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9644   }
9645   return SDValue();
9646 }
9647 
9648 SDValue SITargetLowering::performClassCombine(SDNode *N,
9649                                               DAGCombinerInfo &DCI) const {
9650   SelectionDAG &DAG = DCI.DAG;
9651   SDValue Mask = N->getOperand(1);
9652 
9653   // fp_class x, 0 -> false
9654   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9655     if (CMask->isZero())
9656       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9657   }
9658 
9659   if (N->getOperand(0).isUndef())
9660     return DAG.getUNDEF(MVT::i1);
9661 
9662   return SDValue();
9663 }
9664 
9665 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9666                                             DAGCombinerInfo &DCI) const {
9667   EVT VT = N->getValueType(0);
9668   SDValue N0 = N->getOperand(0);
9669 
9670   if (N0.isUndef())
9671     return N0;
9672 
9673   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9674                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9675     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9676                            N->getFlags());
9677   }
9678 
9679   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9680     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9681                            N0.getOperand(0), N->getFlags());
9682   }
9683 
9684   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9685 }
9686 
9687 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9688                                        unsigned MaxDepth) const {
9689   unsigned Opcode = Op.getOpcode();
9690   if (Opcode == ISD::FCANONICALIZE)
9691     return true;
9692 
9693   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9694     auto F = CFP->getValueAPF();
9695     if (F.isNaN() && F.isSignaling())
9696       return false;
9697     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9698   }
9699 
9700   // If source is a result of another standard FP operation it is already in
9701   // canonical form.
9702   if (MaxDepth == 0)
9703     return false;
9704 
9705   switch (Opcode) {
9706   // These will flush denorms if required.
9707   case ISD::FADD:
9708   case ISD::FSUB:
9709   case ISD::FMUL:
9710   case ISD::FCEIL:
9711   case ISD::FFLOOR:
9712   case ISD::FMA:
9713   case ISD::FMAD:
9714   case ISD::FSQRT:
9715   case ISD::FDIV:
9716   case ISD::FREM:
9717   case ISD::FP_ROUND:
9718   case ISD::FP_EXTEND:
9719   case AMDGPUISD::FMUL_LEGACY:
9720   case AMDGPUISD::FMAD_FTZ:
9721   case AMDGPUISD::RCP:
9722   case AMDGPUISD::RSQ:
9723   case AMDGPUISD::RSQ_CLAMP:
9724   case AMDGPUISD::RCP_LEGACY:
9725   case AMDGPUISD::RCP_IFLAG:
9726   case AMDGPUISD::DIV_SCALE:
9727   case AMDGPUISD::DIV_FMAS:
9728   case AMDGPUISD::DIV_FIXUP:
9729   case AMDGPUISD::FRACT:
9730   case AMDGPUISD::LDEXP:
9731   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9732   case AMDGPUISD::CVT_F32_UBYTE0:
9733   case AMDGPUISD::CVT_F32_UBYTE1:
9734   case AMDGPUISD::CVT_F32_UBYTE2:
9735   case AMDGPUISD::CVT_F32_UBYTE3:
9736     return true;
9737 
9738   // It can/will be lowered or combined as a bit operation.
9739   // Need to check their input recursively to handle.
9740   case ISD::FNEG:
9741   case ISD::FABS:
9742   case ISD::FCOPYSIGN:
9743     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9744 
9745   case ISD::FSIN:
9746   case ISD::FCOS:
9747   case ISD::FSINCOS:
9748     return Op.getValueType().getScalarType() != MVT::f16;
9749 
9750   case ISD::FMINNUM:
9751   case ISD::FMAXNUM:
9752   case ISD::FMINNUM_IEEE:
9753   case ISD::FMAXNUM_IEEE:
9754   case AMDGPUISD::CLAMP:
9755   case AMDGPUISD::FMED3:
9756   case AMDGPUISD::FMAX3:
9757   case AMDGPUISD::FMIN3: {
9758     // FIXME: Shouldn't treat the generic operations different based these.
9759     // However, we aren't really required to flush the result from
9760     // minnum/maxnum..
9761 
9762     // snans will be quieted, so we only need to worry about denormals.
9763     if (Subtarget->supportsMinMaxDenormModes() ||
9764         denormalsEnabledForType(DAG, Op.getValueType()))
9765       return true;
9766 
9767     // Flushing may be required.
9768     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9769     // targets need to check their input recursively.
9770 
9771     // FIXME: Does this apply with clamp? It's implemented with max.
9772     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9773       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9774         return false;
9775     }
9776 
9777     return true;
9778   }
9779   case ISD::SELECT: {
9780     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9781            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9782   }
9783   case ISD::BUILD_VECTOR: {
9784     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9785       SDValue SrcOp = Op.getOperand(i);
9786       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9787         return false;
9788     }
9789 
9790     return true;
9791   }
9792   case ISD::EXTRACT_VECTOR_ELT:
9793   case ISD::EXTRACT_SUBVECTOR: {
9794     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9795   }
9796   case ISD::INSERT_VECTOR_ELT: {
9797     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9798            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9799   }
9800   case ISD::UNDEF:
9801     // Could be anything.
9802     return false;
9803 
9804   case ISD::BITCAST:
9805     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9806   case ISD::TRUNCATE: {
9807     // Hack round the mess we make when legalizing extract_vector_elt
9808     if (Op.getValueType() == MVT::i16) {
9809       SDValue TruncSrc = Op.getOperand(0);
9810       if (TruncSrc.getValueType() == MVT::i32 &&
9811           TruncSrc.getOpcode() == ISD::BITCAST &&
9812           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9813         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9814       }
9815     }
9816     return false;
9817   }
9818   case ISD::INTRINSIC_WO_CHAIN: {
9819     unsigned IntrinsicID
9820       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9821     // TODO: Handle more intrinsics
9822     switch (IntrinsicID) {
9823     case Intrinsic::amdgcn_cvt_pkrtz:
9824     case Intrinsic::amdgcn_cubeid:
9825     case Intrinsic::amdgcn_frexp_mant:
9826     case Intrinsic::amdgcn_fdot2:
9827     case Intrinsic::amdgcn_rcp:
9828     case Intrinsic::amdgcn_rsq:
9829     case Intrinsic::amdgcn_rsq_clamp:
9830     case Intrinsic::amdgcn_rcp_legacy:
9831     case Intrinsic::amdgcn_rsq_legacy:
9832     case Intrinsic::amdgcn_trig_preop:
9833       return true;
9834     default:
9835       break;
9836     }
9837 
9838     LLVM_FALLTHROUGH;
9839   }
9840   default:
9841     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9842            DAG.isKnownNeverSNaN(Op);
9843   }
9844 
9845   llvm_unreachable("invalid operation");
9846 }
9847 
9848 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9849                                        unsigned MaxDepth) const {
9850   MachineRegisterInfo &MRI = MF.getRegInfo();
9851   MachineInstr *MI = MRI.getVRegDef(Reg);
9852   unsigned Opcode = MI->getOpcode();
9853 
9854   if (Opcode == AMDGPU::G_FCANONICALIZE)
9855     return true;
9856 
9857   Optional<FPValueAndVReg> FCR;
9858   // Constant splat (can be padded with undef) or scalar constant.
9859   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9860     if (FCR->Value.isSignaling())
9861       return false;
9862     return !FCR->Value.isDenormal() ||
9863            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9864   }
9865 
9866   if (MaxDepth == 0)
9867     return false;
9868 
9869   switch (Opcode) {
9870   case AMDGPU::G_FMINNUM_IEEE:
9871   case AMDGPU::G_FMAXNUM_IEEE: {
9872     if (Subtarget->supportsMinMaxDenormModes() ||
9873         denormalsEnabledForType(MRI.getType(Reg), MF))
9874       return true;
9875     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9876       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9877         return false;
9878     return true;
9879   }
9880   default:
9881     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9882            isKnownNeverSNaN(Reg, MRI);
9883   }
9884 
9885   llvm_unreachable("invalid operation");
9886 }
9887 
9888 // Constant fold canonicalize.
9889 SDValue SITargetLowering::getCanonicalConstantFP(
9890   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9891   // Flush denormals to 0 if not enabled.
9892   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9893     return DAG.getConstantFP(0.0, SL, VT);
9894 
9895   if (C.isNaN()) {
9896     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9897     if (C.isSignaling()) {
9898       // Quiet a signaling NaN.
9899       // FIXME: Is this supposed to preserve payload bits?
9900       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9901     }
9902 
9903     // Make sure it is the canonical NaN bitpattern.
9904     //
9905     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9906     // immediate?
9907     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9908       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9909   }
9910 
9911   // Already canonical.
9912   return DAG.getConstantFP(C, SL, VT);
9913 }
9914 
9915 static bool vectorEltWillFoldAway(SDValue Op) {
9916   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9917 }
9918 
9919 SDValue SITargetLowering::performFCanonicalizeCombine(
9920   SDNode *N,
9921   DAGCombinerInfo &DCI) const {
9922   SelectionDAG &DAG = DCI.DAG;
9923   SDValue N0 = N->getOperand(0);
9924   EVT VT = N->getValueType(0);
9925 
9926   // fcanonicalize undef -> qnan
9927   if (N0.isUndef()) {
9928     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9929     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9930   }
9931 
9932   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9933     EVT VT = N->getValueType(0);
9934     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9935   }
9936 
9937   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9938   //                                                   (fcanonicalize k)
9939   //
9940   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9941 
9942   // TODO: This could be better with wider vectors that will be split to v2f16,
9943   // and to consider uses since there aren't that many packed operations.
9944   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9945       isTypeLegal(MVT::v2f16)) {
9946     SDLoc SL(N);
9947     SDValue NewElts[2];
9948     SDValue Lo = N0.getOperand(0);
9949     SDValue Hi = N0.getOperand(1);
9950     EVT EltVT = Lo.getValueType();
9951 
9952     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9953       for (unsigned I = 0; I != 2; ++I) {
9954         SDValue Op = N0.getOperand(I);
9955         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9956           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9957                                               CFP->getValueAPF());
9958         } else if (Op.isUndef()) {
9959           // Handled below based on what the other operand is.
9960           NewElts[I] = Op;
9961         } else {
9962           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9963         }
9964       }
9965 
9966       // If one half is undef, and one is constant, perfer a splat vector rather
9967       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9968       // cheaper to use and may be free with a packed operation.
9969       if (NewElts[0].isUndef()) {
9970         if (isa<ConstantFPSDNode>(NewElts[1]))
9971           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9972             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9973       }
9974 
9975       if (NewElts[1].isUndef()) {
9976         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9977           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9978       }
9979 
9980       return DAG.getBuildVector(VT, SL, NewElts);
9981     }
9982   }
9983 
9984   unsigned SrcOpc = N0.getOpcode();
9985 
9986   // If it's free to do so, push canonicalizes further up the source, which may
9987   // find a canonical source.
9988   //
9989   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9990   // sNaNs.
9991   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9992     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9993     if (CRHS && N0.hasOneUse()) {
9994       SDLoc SL(N);
9995       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9996                                    N0.getOperand(0));
9997       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9998       DCI.AddToWorklist(Canon0.getNode());
9999 
10000       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10001     }
10002   }
10003 
10004   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10005 }
10006 
10007 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10008   switch (Opc) {
10009   case ISD::FMAXNUM:
10010   case ISD::FMAXNUM_IEEE:
10011     return AMDGPUISD::FMAX3;
10012   case ISD::SMAX:
10013     return AMDGPUISD::SMAX3;
10014   case ISD::UMAX:
10015     return AMDGPUISD::UMAX3;
10016   case ISD::FMINNUM:
10017   case ISD::FMINNUM_IEEE:
10018     return AMDGPUISD::FMIN3;
10019   case ISD::SMIN:
10020     return AMDGPUISD::SMIN3;
10021   case ISD::UMIN:
10022     return AMDGPUISD::UMIN3;
10023   default:
10024     llvm_unreachable("Not a min/max opcode");
10025   }
10026 }
10027 
10028 SDValue SITargetLowering::performIntMed3ImmCombine(
10029   SelectionDAG &DAG, const SDLoc &SL,
10030   SDValue Op0, SDValue Op1, bool Signed) const {
10031   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10032   if (!K1)
10033     return SDValue();
10034 
10035   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10036   if (!K0)
10037     return SDValue();
10038 
10039   if (Signed) {
10040     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10041       return SDValue();
10042   } else {
10043     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10044       return SDValue();
10045   }
10046 
10047   EVT VT = K0->getValueType(0);
10048   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10049   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10050     return DAG.getNode(Med3Opc, SL, VT,
10051                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10052   }
10053 
10054   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10055   if (VT == MVT::i16) {
10056     MVT NVT = MVT::i32;
10057     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10058 
10059     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10060     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10061     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10062 
10063     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10064     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10065   }
10066 
10067   return SDValue();
10068 }
10069 
10070 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10071   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10072     return C;
10073 
10074   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10075     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10076       return C;
10077   }
10078 
10079   return nullptr;
10080 }
10081 
10082 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10083                                                   const SDLoc &SL,
10084                                                   SDValue Op0,
10085                                                   SDValue Op1) const {
10086   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10087   if (!K1)
10088     return SDValue();
10089 
10090   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10091   if (!K0)
10092     return SDValue();
10093 
10094   // Ordered >= (although NaN inputs should have folded away by now).
10095   if (K0->getValueAPF() > K1->getValueAPF())
10096     return SDValue();
10097 
10098   const MachineFunction &MF = DAG.getMachineFunction();
10099   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10100 
10101   // TODO: Check IEEE bit enabled?
10102   EVT VT = Op0.getValueType();
10103   if (Info->getMode().DX10Clamp) {
10104     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10105     // hardware fmed3 behavior converting to a min.
10106     // FIXME: Should this be allowing -0.0?
10107     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10108       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10109   }
10110 
10111   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10112   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10113     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10114     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10115     // then give the other result, which is different from med3 with a NaN
10116     // input.
10117     SDValue Var = Op0.getOperand(0);
10118     if (!DAG.isKnownNeverSNaN(Var))
10119       return SDValue();
10120 
10121     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10122 
10123     if ((!K0->hasOneUse() ||
10124          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10125         (!K1->hasOneUse() ||
10126          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10127       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10128                          Var, SDValue(K0, 0), SDValue(K1, 0));
10129     }
10130   }
10131 
10132   return SDValue();
10133 }
10134 
10135 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10136                                                DAGCombinerInfo &DCI) const {
10137   SelectionDAG &DAG = DCI.DAG;
10138 
10139   EVT VT = N->getValueType(0);
10140   unsigned Opc = N->getOpcode();
10141   SDValue Op0 = N->getOperand(0);
10142   SDValue Op1 = N->getOperand(1);
10143 
10144   // Only do this if the inner op has one use since this will just increases
10145   // register pressure for no benefit.
10146 
10147   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10148       !VT.isVector() &&
10149       (VT == MVT::i32 || VT == MVT::f32 ||
10150        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10151     // max(max(a, b), c) -> max3(a, b, c)
10152     // min(min(a, b), c) -> min3(a, b, c)
10153     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10154       SDLoc DL(N);
10155       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10156                          DL,
10157                          N->getValueType(0),
10158                          Op0.getOperand(0),
10159                          Op0.getOperand(1),
10160                          Op1);
10161     }
10162 
10163     // Try commuted.
10164     // max(a, max(b, c)) -> max3(a, b, c)
10165     // min(a, min(b, c)) -> min3(a, b, c)
10166     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10167       SDLoc DL(N);
10168       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10169                          DL,
10170                          N->getValueType(0),
10171                          Op0,
10172                          Op1.getOperand(0),
10173                          Op1.getOperand(1));
10174     }
10175   }
10176 
10177   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10178   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10179     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10180       return Med3;
10181   }
10182 
10183   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10184     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10185       return Med3;
10186   }
10187 
10188   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10189   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10190        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10191        (Opc == AMDGPUISD::FMIN_LEGACY &&
10192         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10193       (VT == MVT::f32 || VT == MVT::f64 ||
10194        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10195        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10196       Op0.hasOneUse()) {
10197     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10198       return Res;
10199   }
10200 
10201   return SDValue();
10202 }
10203 
10204 static bool isClampZeroToOne(SDValue A, SDValue B) {
10205   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10206     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10207       // FIXME: Should this be allowing -0.0?
10208       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10209              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10210     }
10211   }
10212 
10213   return false;
10214 }
10215 
10216 // FIXME: Should only worry about snans for version with chain.
10217 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10218                                               DAGCombinerInfo &DCI) const {
10219   EVT VT = N->getValueType(0);
10220   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10221   // NaNs. With a NaN input, the order of the operands may change the result.
10222 
10223   SelectionDAG &DAG = DCI.DAG;
10224   SDLoc SL(N);
10225 
10226   SDValue Src0 = N->getOperand(0);
10227   SDValue Src1 = N->getOperand(1);
10228   SDValue Src2 = N->getOperand(2);
10229 
10230   if (isClampZeroToOne(Src0, Src1)) {
10231     // const_a, const_b, x -> clamp is safe in all cases including signaling
10232     // nans.
10233     // FIXME: Should this be allowing -0.0?
10234     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10235   }
10236 
10237   const MachineFunction &MF = DAG.getMachineFunction();
10238   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10239 
10240   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10241   // handling no dx10-clamp?
10242   if (Info->getMode().DX10Clamp) {
10243     // If NaNs is clamped to 0, we are free to reorder the inputs.
10244 
10245     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10246       std::swap(Src0, Src1);
10247 
10248     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10249       std::swap(Src1, Src2);
10250 
10251     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10252       std::swap(Src0, Src1);
10253 
10254     if (isClampZeroToOne(Src1, Src2))
10255       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10256   }
10257 
10258   return SDValue();
10259 }
10260 
10261 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10262                                                  DAGCombinerInfo &DCI) const {
10263   SDValue Src0 = N->getOperand(0);
10264   SDValue Src1 = N->getOperand(1);
10265   if (Src0.isUndef() && Src1.isUndef())
10266     return DCI.DAG.getUNDEF(N->getValueType(0));
10267   return SDValue();
10268 }
10269 
10270 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10271 // expanded into a set of cmp/select instructions.
10272 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10273                                                 unsigned NumElem,
10274                                                 bool IsDivergentIdx) {
10275   if (UseDivergentRegisterIndexing)
10276     return false;
10277 
10278   unsigned VecSize = EltSize * NumElem;
10279 
10280   // Sub-dword vectors of size 2 dword or less have better implementation.
10281   if (VecSize <= 64 && EltSize < 32)
10282     return false;
10283 
10284   // Always expand the rest of sub-dword instructions, otherwise it will be
10285   // lowered via memory.
10286   if (EltSize < 32)
10287     return true;
10288 
10289   // Always do this if var-idx is divergent, otherwise it will become a loop.
10290   if (IsDivergentIdx)
10291     return true;
10292 
10293   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10294   unsigned NumInsts = NumElem /* Number of compares */ +
10295                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10296   return NumInsts <= 16;
10297 }
10298 
10299 static bool shouldExpandVectorDynExt(SDNode *N) {
10300   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10301   if (isa<ConstantSDNode>(Idx))
10302     return false;
10303 
10304   SDValue Vec = N->getOperand(0);
10305   EVT VecVT = Vec.getValueType();
10306   EVT EltVT = VecVT.getVectorElementType();
10307   unsigned EltSize = EltVT.getSizeInBits();
10308   unsigned NumElem = VecVT.getVectorNumElements();
10309 
10310   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10311                                                     Idx->isDivergent());
10312 }
10313 
10314 SDValue SITargetLowering::performExtractVectorEltCombine(
10315   SDNode *N, DAGCombinerInfo &DCI) const {
10316   SDValue Vec = N->getOperand(0);
10317   SelectionDAG &DAG = DCI.DAG;
10318 
10319   EVT VecVT = Vec.getValueType();
10320   EVT EltVT = VecVT.getVectorElementType();
10321 
10322   if ((Vec.getOpcode() == ISD::FNEG ||
10323        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10324     SDLoc SL(N);
10325     EVT EltVT = N->getValueType(0);
10326     SDValue Idx = N->getOperand(1);
10327     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10328                               Vec.getOperand(0), Idx);
10329     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10330   }
10331 
10332   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10333   //    =>
10334   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10335   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10336   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10337   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10338     SDLoc SL(N);
10339     EVT EltVT = N->getValueType(0);
10340     SDValue Idx = N->getOperand(1);
10341     unsigned Opc = Vec.getOpcode();
10342 
10343     switch(Opc) {
10344     default:
10345       break;
10346       // TODO: Support other binary operations.
10347     case ISD::FADD:
10348     case ISD::FSUB:
10349     case ISD::FMUL:
10350     case ISD::ADD:
10351     case ISD::UMIN:
10352     case ISD::UMAX:
10353     case ISD::SMIN:
10354     case ISD::SMAX:
10355     case ISD::FMAXNUM:
10356     case ISD::FMINNUM:
10357     case ISD::FMAXNUM_IEEE:
10358     case ISD::FMINNUM_IEEE: {
10359       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10360                                  Vec.getOperand(0), Idx);
10361       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10362                                  Vec.getOperand(1), Idx);
10363 
10364       DCI.AddToWorklist(Elt0.getNode());
10365       DCI.AddToWorklist(Elt1.getNode());
10366       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10367     }
10368     }
10369   }
10370 
10371   unsigned VecSize = VecVT.getSizeInBits();
10372   unsigned EltSize = EltVT.getSizeInBits();
10373 
10374   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10375   if (::shouldExpandVectorDynExt(N)) {
10376     SDLoc SL(N);
10377     SDValue Idx = N->getOperand(1);
10378     SDValue V;
10379     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10380       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10381       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10382       if (I == 0)
10383         V = Elt;
10384       else
10385         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10386     }
10387     return V;
10388   }
10389 
10390   if (!DCI.isBeforeLegalize())
10391     return SDValue();
10392 
10393   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10394   // elements. This exposes more load reduction opportunities by replacing
10395   // multiple small extract_vector_elements with a single 32-bit extract.
10396   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10397   if (isa<MemSDNode>(Vec) &&
10398       EltSize <= 16 &&
10399       EltVT.isByteSized() &&
10400       VecSize > 32 &&
10401       VecSize % 32 == 0 &&
10402       Idx) {
10403     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10404 
10405     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10406     unsigned EltIdx = BitIndex / 32;
10407     unsigned LeftoverBitIdx = BitIndex % 32;
10408     SDLoc SL(N);
10409 
10410     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10411     DCI.AddToWorklist(Cast.getNode());
10412 
10413     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10414                               DAG.getConstant(EltIdx, SL, MVT::i32));
10415     DCI.AddToWorklist(Elt.getNode());
10416     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10417                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10418     DCI.AddToWorklist(Srl.getNode());
10419 
10420     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10421     DCI.AddToWorklist(Trunc.getNode());
10422     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10423   }
10424 
10425   return SDValue();
10426 }
10427 
10428 SDValue
10429 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10430                                                 DAGCombinerInfo &DCI) const {
10431   SDValue Vec = N->getOperand(0);
10432   SDValue Idx = N->getOperand(2);
10433   EVT VecVT = Vec.getValueType();
10434   EVT EltVT = VecVT.getVectorElementType();
10435 
10436   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10437   // => BUILD_VECTOR n x select (e, const-idx)
10438   if (!::shouldExpandVectorDynExt(N))
10439     return SDValue();
10440 
10441   SelectionDAG &DAG = DCI.DAG;
10442   SDLoc SL(N);
10443   SDValue Ins = N->getOperand(1);
10444   EVT IdxVT = Idx.getValueType();
10445 
10446   SmallVector<SDValue, 16> Ops;
10447   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10448     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10449     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10450     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10451     Ops.push_back(V);
10452   }
10453 
10454   return DAG.getBuildVector(VecVT, SL, Ops);
10455 }
10456 
10457 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10458                                           const SDNode *N0,
10459                                           const SDNode *N1) const {
10460   EVT VT = N0->getValueType(0);
10461 
10462   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10463   // support denormals ever.
10464   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10465        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10466         getSubtarget()->hasMadF16())) &&
10467        isOperationLegal(ISD::FMAD, VT))
10468     return ISD::FMAD;
10469 
10470   const TargetOptions &Options = DAG.getTarget().Options;
10471   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10472        (N0->getFlags().hasAllowContract() &&
10473         N1->getFlags().hasAllowContract())) &&
10474       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10475     return ISD::FMA;
10476   }
10477 
10478   return 0;
10479 }
10480 
10481 // For a reassociatable opcode perform:
10482 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10483 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10484                                                SelectionDAG &DAG) const {
10485   EVT VT = N->getValueType(0);
10486   if (VT != MVT::i32 && VT != MVT::i64)
10487     return SDValue();
10488 
10489   unsigned Opc = N->getOpcode();
10490   SDValue Op0 = N->getOperand(0);
10491   SDValue Op1 = N->getOperand(1);
10492 
10493   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10494     return SDValue();
10495 
10496   if (Op0->isDivergent())
10497     std::swap(Op0, Op1);
10498 
10499   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10500     return SDValue();
10501 
10502   SDValue Op2 = Op1.getOperand(1);
10503   Op1 = Op1.getOperand(0);
10504   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10505     return SDValue();
10506 
10507   if (Op1->isDivergent())
10508     std::swap(Op1, Op2);
10509 
10510   // If either operand is constant this will conflict with
10511   // DAGCombiner::ReassociateOps().
10512   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10513       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10514     return SDValue();
10515 
10516   SDLoc SL(N);
10517   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10518   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10519 }
10520 
10521 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10522                            EVT VT,
10523                            SDValue N0, SDValue N1, SDValue N2,
10524                            bool Signed) {
10525   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10526   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10527   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10528   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10529 }
10530 
10531 SDValue SITargetLowering::performAddCombine(SDNode *N,
10532                                             DAGCombinerInfo &DCI) const {
10533   SelectionDAG &DAG = DCI.DAG;
10534   EVT VT = N->getValueType(0);
10535   SDLoc SL(N);
10536   SDValue LHS = N->getOperand(0);
10537   SDValue RHS = N->getOperand(1);
10538 
10539   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10540       && Subtarget->hasMad64_32() &&
10541       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10542       VT.getScalarSizeInBits() <= 64) {
10543     if (LHS.getOpcode() != ISD::MUL)
10544       std::swap(LHS, RHS);
10545 
10546     SDValue MulLHS = LHS.getOperand(0);
10547     SDValue MulRHS = LHS.getOperand(1);
10548     SDValue AddRHS = RHS;
10549 
10550     // TODO: Maybe restrict if SGPR inputs.
10551     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10552         numBitsUnsigned(MulRHS, DAG) <= 32) {
10553       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10554       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10555       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10556       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10557     }
10558 
10559     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10560       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10561       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10562       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10563       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10564     }
10565 
10566     return SDValue();
10567   }
10568 
10569   if (SDValue V = reassociateScalarOps(N, DAG)) {
10570     return V;
10571   }
10572 
10573   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10574     return SDValue();
10575 
10576   // add x, zext (setcc) => addcarry x, 0, setcc
10577   // add x, sext (setcc) => subcarry x, 0, setcc
10578   unsigned Opc = LHS.getOpcode();
10579   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10580       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10581     std::swap(RHS, LHS);
10582 
10583   Opc = RHS.getOpcode();
10584   switch (Opc) {
10585   default: break;
10586   case ISD::ZERO_EXTEND:
10587   case ISD::SIGN_EXTEND:
10588   case ISD::ANY_EXTEND: {
10589     auto Cond = RHS.getOperand(0);
10590     // If this won't be a real VOPC output, we would still need to insert an
10591     // extra instruction anyway.
10592     if (!isBoolSGPR(Cond))
10593       break;
10594     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10595     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10596     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10597     return DAG.getNode(Opc, SL, VTList, Args);
10598   }
10599   case ISD::ADDCARRY: {
10600     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10601     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10602     if (!C || C->getZExtValue() != 0) break;
10603     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10604     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10605   }
10606   }
10607   return SDValue();
10608 }
10609 
10610 SDValue SITargetLowering::performSubCombine(SDNode *N,
10611                                             DAGCombinerInfo &DCI) const {
10612   SelectionDAG &DAG = DCI.DAG;
10613   EVT VT = N->getValueType(0);
10614 
10615   if (VT != MVT::i32)
10616     return SDValue();
10617 
10618   SDLoc SL(N);
10619   SDValue LHS = N->getOperand(0);
10620   SDValue RHS = N->getOperand(1);
10621 
10622   // sub x, zext (setcc) => subcarry x, 0, setcc
10623   // sub x, sext (setcc) => addcarry x, 0, setcc
10624   unsigned Opc = RHS.getOpcode();
10625   switch (Opc) {
10626   default: break;
10627   case ISD::ZERO_EXTEND:
10628   case ISD::SIGN_EXTEND:
10629   case ISD::ANY_EXTEND: {
10630     auto Cond = RHS.getOperand(0);
10631     // If this won't be a real VOPC output, we would still need to insert an
10632     // extra instruction anyway.
10633     if (!isBoolSGPR(Cond))
10634       break;
10635     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10636     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10637     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10638     return DAG.getNode(Opc, SL, VTList, Args);
10639   }
10640   }
10641 
10642   if (LHS.getOpcode() == ISD::SUBCARRY) {
10643     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10644     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10645     if (!C || !C->isZero())
10646       return SDValue();
10647     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10648     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10649   }
10650   return SDValue();
10651 }
10652 
10653 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10654   DAGCombinerInfo &DCI) const {
10655 
10656   if (N->getValueType(0) != MVT::i32)
10657     return SDValue();
10658 
10659   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10660   if (!C || C->getZExtValue() != 0)
10661     return SDValue();
10662 
10663   SelectionDAG &DAG = DCI.DAG;
10664   SDValue LHS = N->getOperand(0);
10665 
10666   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10667   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10668   unsigned LHSOpc = LHS.getOpcode();
10669   unsigned Opc = N->getOpcode();
10670   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10671       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10672     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10673     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10674   }
10675   return SDValue();
10676 }
10677 
10678 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10679                                              DAGCombinerInfo &DCI) const {
10680   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10681     return SDValue();
10682 
10683   SelectionDAG &DAG = DCI.DAG;
10684   EVT VT = N->getValueType(0);
10685 
10686   SDLoc SL(N);
10687   SDValue LHS = N->getOperand(0);
10688   SDValue RHS = N->getOperand(1);
10689 
10690   // These should really be instruction patterns, but writing patterns with
10691   // source modiifiers is a pain.
10692 
10693   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10694   if (LHS.getOpcode() == ISD::FADD) {
10695     SDValue A = LHS.getOperand(0);
10696     if (A == LHS.getOperand(1)) {
10697       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10698       if (FusedOp != 0) {
10699         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10700         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10701       }
10702     }
10703   }
10704 
10705   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10706   if (RHS.getOpcode() == ISD::FADD) {
10707     SDValue A = RHS.getOperand(0);
10708     if (A == RHS.getOperand(1)) {
10709       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10710       if (FusedOp != 0) {
10711         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10712         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10713       }
10714     }
10715   }
10716 
10717   return SDValue();
10718 }
10719 
10720 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10721                                              DAGCombinerInfo &DCI) const {
10722   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10723     return SDValue();
10724 
10725   SelectionDAG &DAG = DCI.DAG;
10726   SDLoc SL(N);
10727   EVT VT = N->getValueType(0);
10728   assert(!VT.isVector());
10729 
10730   // Try to get the fneg to fold into the source modifier. This undoes generic
10731   // DAG combines and folds them into the mad.
10732   //
10733   // Only do this if we are not trying to support denormals. v_mad_f32 does
10734   // not support denormals ever.
10735   SDValue LHS = N->getOperand(0);
10736   SDValue RHS = N->getOperand(1);
10737   if (LHS.getOpcode() == ISD::FADD) {
10738     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10739     SDValue A = LHS.getOperand(0);
10740     if (A == LHS.getOperand(1)) {
10741       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10742       if (FusedOp != 0){
10743         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10744         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10745 
10746         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10747       }
10748     }
10749   }
10750 
10751   if (RHS.getOpcode() == ISD::FADD) {
10752     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10753 
10754     SDValue A = RHS.getOperand(0);
10755     if (A == RHS.getOperand(1)) {
10756       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10757       if (FusedOp != 0){
10758         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10759         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10760       }
10761     }
10762   }
10763 
10764   return SDValue();
10765 }
10766 
10767 SDValue SITargetLowering::performFMACombine(SDNode *N,
10768                                             DAGCombinerInfo &DCI) const {
10769   SelectionDAG &DAG = DCI.DAG;
10770   EVT VT = N->getValueType(0);
10771   SDLoc SL(N);
10772 
10773   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10774     return SDValue();
10775 
10776   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10777   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10778   SDValue Op1 = N->getOperand(0);
10779   SDValue Op2 = N->getOperand(1);
10780   SDValue FMA = N->getOperand(2);
10781 
10782   if (FMA.getOpcode() != ISD::FMA ||
10783       Op1.getOpcode() != ISD::FP_EXTEND ||
10784       Op2.getOpcode() != ISD::FP_EXTEND)
10785     return SDValue();
10786 
10787   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10788   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10789   // is sufficient to allow generaing fdot2.
10790   const TargetOptions &Options = DAG.getTarget().Options;
10791   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10792       (N->getFlags().hasAllowContract() &&
10793        FMA->getFlags().hasAllowContract())) {
10794     Op1 = Op1.getOperand(0);
10795     Op2 = Op2.getOperand(0);
10796     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10797         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10798       return SDValue();
10799 
10800     SDValue Vec1 = Op1.getOperand(0);
10801     SDValue Idx1 = Op1.getOperand(1);
10802     SDValue Vec2 = Op2.getOperand(0);
10803 
10804     SDValue FMAOp1 = FMA.getOperand(0);
10805     SDValue FMAOp2 = FMA.getOperand(1);
10806     SDValue FMAAcc = FMA.getOperand(2);
10807 
10808     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10809         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10810       return SDValue();
10811 
10812     FMAOp1 = FMAOp1.getOperand(0);
10813     FMAOp2 = FMAOp2.getOperand(0);
10814     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10815         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10816       return SDValue();
10817 
10818     SDValue Vec3 = FMAOp1.getOperand(0);
10819     SDValue Vec4 = FMAOp2.getOperand(0);
10820     SDValue Idx2 = FMAOp1.getOperand(1);
10821 
10822     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10823         // Idx1 and Idx2 cannot be the same.
10824         Idx1 == Idx2)
10825       return SDValue();
10826 
10827     if (Vec1 == Vec2 || Vec3 == Vec4)
10828       return SDValue();
10829 
10830     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10831       return SDValue();
10832 
10833     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10834         (Vec1 == Vec4 && Vec2 == Vec3)) {
10835       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10836                          DAG.getTargetConstant(0, SL, MVT::i1));
10837     }
10838   }
10839   return SDValue();
10840 }
10841 
10842 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10843                                               DAGCombinerInfo &DCI) const {
10844   SelectionDAG &DAG = DCI.DAG;
10845   SDLoc SL(N);
10846 
10847   SDValue LHS = N->getOperand(0);
10848   SDValue RHS = N->getOperand(1);
10849   EVT VT = LHS.getValueType();
10850   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10851 
10852   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10853   if (!CRHS) {
10854     CRHS = dyn_cast<ConstantSDNode>(LHS);
10855     if (CRHS) {
10856       std::swap(LHS, RHS);
10857       CC = getSetCCSwappedOperands(CC);
10858     }
10859   }
10860 
10861   if (CRHS) {
10862     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10863         isBoolSGPR(LHS.getOperand(0))) {
10864       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10865       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10866       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10867       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10868       if ((CRHS->isAllOnes() &&
10869            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10870           (CRHS->isZero() &&
10871            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10872         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10873                            DAG.getConstant(-1, SL, MVT::i1));
10874       if ((CRHS->isAllOnes() &&
10875            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10876           (CRHS->isZero() &&
10877            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10878         return LHS.getOperand(0);
10879     }
10880 
10881     const APInt &CRHSVal = CRHS->getAPIntValue();
10882     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10883         LHS.getOpcode() == ISD::SELECT &&
10884         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10885         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10886         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10887         isBoolSGPR(LHS.getOperand(0))) {
10888       // Given CT != FT:
10889       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10890       // setcc (select cc, CT, CF), CF, ne => cc
10891       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10892       // setcc (select cc, CT, CF), CT, eq => cc
10893       const APInt &CT = LHS.getConstantOperandAPInt(1);
10894       const APInt &CF = LHS.getConstantOperandAPInt(2);
10895 
10896       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10897           (CT == CRHSVal && CC == ISD::SETNE))
10898         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10899                            DAG.getConstant(-1, SL, MVT::i1));
10900       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10901           (CT == CRHSVal && CC == ISD::SETEQ))
10902         return LHS.getOperand(0);
10903     }
10904   }
10905 
10906   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10907                                            VT != MVT::f16))
10908     return SDValue();
10909 
10910   // Match isinf/isfinite pattern
10911   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10912   // (fcmp one (fabs x), inf) -> (fp_class x,
10913   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10914   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10915     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10916     if (!CRHS)
10917       return SDValue();
10918 
10919     const APFloat &APF = CRHS->getValueAPF();
10920     if (APF.isInfinity() && !APF.isNegative()) {
10921       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10922                                  SIInstrFlags::N_INFINITY;
10923       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10924                                     SIInstrFlags::P_ZERO |
10925                                     SIInstrFlags::N_NORMAL |
10926                                     SIInstrFlags::P_NORMAL |
10927                                     SIInstrFlags::N_SUBNORMAL |
10928                                     SIInstrFlags::P_SUBNORMAL;
10929       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10930       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10931                          DAG.getConstant(Mask, SL, MVT::i32));
10932     }
10933   }
10934 
10935   return SDValue();
10936 }
10937 
10938 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10939                                                      DAGCombinerInfo &DCI) const {
10940   SelectionDAG &DAG = DCI.DAG;
10941   SDLoc SL(N);
10942   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10943 
10944   SDValue Src = N->getOperand(0);
10945   SDValue Shift = N->getOperand(0);
10946 
10947   // TODO: Extend type shouldn't matter (assuming legal types).
10948   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10949     Shift = Shift.getOperand(0);
10950 
10951   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10952     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10953     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10954     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10955     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10956     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10957     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10958       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
10959                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10960 
10961       unsigned ShiftOffset = 8 * Offset;
10962       if (Shift.getOpcode() == ISD::SHL)
10963         ShiftOffset -= C->getZExtValue();
10964       else
10965         ShiftOffset += C->getZExtValue();
10966 
10967       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10968         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10969                            MVT::f32, Shifted);
10970       }
10971     }
10972   }
10973 
10974   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10975   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10976   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10977     // We simplified Src. If this node is not dead, visit it again so it is
10978     // folded properly.
10979     if (N->getOpcode() != ISD::DELETED_NODE)
10980       DCI.AddToWorklist(N);
10981     return SDValue(N, 0);
10982   }
10983 
10984   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10985   if (SDValue DemandedSrc =
10986           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10987     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10988 
10989   return SDValue();
10990 }
10991 
10992 SDValue SITargetLowering::performClampCombine(SDNode *N,
10993                                               DAGCombinerInfo &DCI) const {
10994   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10995   if (!CSrc)
10996     return SDValue();
10997 
10998   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10999   const APFloat &F = CSrc->getValueAPF();
11000   APFloat Zero = APFloat::getZero(F.getSemantics());
11001   if (F < Zero ||
11002       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11003     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11004   }
11005 
11006   APFloat One(F.getSemantics(), "1.0");
11007   if (F > One)
11008     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11009 
11010   return SDValue(CSrc, 0);
11011 }
11012 
11013 
11014 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11015                                             DAGCombinerInfo &DCI) const {
11016   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11017     return SDValue();
11018   switch (N->getOpcode()) {
11019   case ISD::ADD:
11020     return performAddCombine(N, DCI);
11021   case ISD::SUB:
11022     return performSubCombine(N, DCI);
11023   case ISD::ADDCARRY:
11024   case ISD::SUBCARRY:
11025     return performAddCarrySubCarryCombine(N, DCI);
11026   case ISD::FADD:
11027     return performFAddCombine(N, DCI);
11028   case ISD::FSUB:
11029     return performFSubCombine(N, DCI);
11030   case ISD::SETCC:
11031     return performSetCCCombine(N, DCI);
11032   case ISD::FMAXNUM:
11033   case ISD::FMINNUM:
11034   case ISD::FMAXNUM_IEEE:
11035   case ISD::FMINNUM_IEEE:
11036   case ISD::SMAX:
11037   case ISD::SMIN:
11038   case ISD::UMAX:
11039   case ISD::UMIN:
11040   case AMDGPUISD::FMIN_LEGACY:
11041   case AMDGPUISD::FMAX_LEGACY:
11042     return performMinMaxCombine(N, DCI);
11043   case ISD::FMA:
11044     return performFMACombine(N, DCI);
11045   case ISD::AND:
11046     return performAndCombine(N, DCI);
11047   case ISD::OR:
11048     return performOrCombine(N, DCI);
11049   case ISD::XOR:
11050     return performXorCombine(N, DCI);
11051   case ISD::ZERO_EXTEND:
11052     return performZeroExtendCombine(N, DCI);
11053   case ISD::SIGN_EXTEND_INREG:
11054     return performSignExtendInRegCombine(N , DCI);
11055   case AMDGPUISD::FP_CLASS:
11056     return performClassCombine(N, DCI);
11057   case ISD::FCANONICALIZE:
11058     return performFCanonicalizeCombine(N, DCI);
11059   case AMDGPUISD::RCP:
11060     return performRcpCombine(N, DCI);
11061   case AMDGPUISD::FRACT:
11062   case AMDGPUISD::RSQ:
11063   case AMDGPUISD::RCP_LEGACY:
11064   case AMDGPUISD::RCP_IFLAG:
11065   case AMDGPUISD::RSQ_CLAMP:
11066   case AMDGPUISD::LDEXP: {
11067     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11068     SDValue Src = N->getOperand(0);
11069     if (Src.isUndef())
11070       return Src;
11071     break;
11072   }
11073   case ISD::SINT_TO_FP:
11074   case ISD::UINT_TO_FP:
11075     return performUCharToFloatCombine(N, DCI);
11076   case AMDGPUISD::CVT_F32_UBYTE0:
11077   case AMDGPUISD::CVT_F32_UBYTE1:
11078   case AMDGPUISD::CVT_F32_UBYTE2:
11079   case AMDGPUISD::CVT_F32_UBYTE3:
11080     return performCvtF32UByteNCombine(N, DCI);
11081   case AMDGPUISD::FMED3:
11082     return performFMed3Combine(N, DCI);
11083   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11084     return performCvtPkRTZCombine(N, DCI);
11085   case AMDGPUISD::CLAMP:
11086     return performClampCombine(N, DCI);
11087   case ISD::SCALAR_TO_VECTOR: {
11088     SelectionDAG &DAG = DCI.DAG;
11089     EVT VT = N->getValueType(0);
11090 
11091     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11092     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11093       SDLoc SL(N);
11094       SDValue Src = N->getOperand(0);
11095       EVT EltVT = Src.getValueType();
11096       if (EltVT == MVT::f16)
11097         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11098 
11099       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11100       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11101     }
11102 
11103     break;
11104   }
11105   case ISD::EXTRACT_VECTOR_ELT:
11106     return performExtractVectorEltCombine(N, DCI);
11107   case ISD::INSERT_VECTOR_ELT:
11108     return performInsertVectorEltCombine(N, DCI);
11109   case ISD::LOAD: {
11110     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11111       return Widended;
11112     LLVM_FALLTHROUGH;
11113   }
11114   default: {
11115     if (!DCI.isBeforeLegalize()) {
11116       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11117         return performMemSDNodeCombine(MemNode, DCI);
11118     }
11119 
11120     break;
11121   }
11122   }
11123 
11124   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11125 }
11126 
11127 /// Helper function for adjustWritemask
11128 static unsigned SubIdx2Lane(unsigned Idx) {
11129   switch (Idx) {
11130   default: return ~0u;
11131   case AMDGPU::sub0: return 0;
11132   case AMDGPU::sub1: return 1;
11133   case AMDGPU::sub2: return 2;
11134   case AMDGPU::sub3: return 3;
11135   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11136   }
11137 }
11138 
11139 /// Adjust the writemask of MIMG instructions
11140 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11141                                           SelectionDAG &DAG) const {
11142   unsigned Opcode = Node->getMachineOpcode();
11143 
11144   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11145   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11146   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11147     return Node; // not implemented for D16
11148 
11149   SDNode *Users[5] = { nullptr };
11150   unsigned Lane = 0;
11151   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11152   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11153   unsigned NewDmask = 0;
11154   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11155   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11156   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11157                   Node->getConstantOperandVal(LWEIdx))
11158                      ? true
11159                      : false;
11160   unsigned TFCLane = 0;
11161   bool HasChain = Node->getNumValues() > 1;
11162 
11163   if (OldDmask == 0) {
11164     // These are folded out, but on the chance it happens don't assert.
11165     return Node;
11166   }
11167 
11168   unsigned OldBitsSet = countPopulation(OldDmask);
11169   // Work out which is the TFE/LWE lane if that is enabled.
11170   if (UsesTFC) {
11171     TFCLane = OldBitsSet;
11172   }
11173 
11174   // Try to figure out the used register components
11175   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11176        I != E; ++I) {
11177 
11178     // Don't look at users of the chain.
11179     if (I.getUse().getResNo() != 0)
11180       continue;
11181 
11182     // Abort if we can't understand the usage
11183     if (!I->isMachineOpcode() ||
11184         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11185       return Node;
11186 
11187     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11188     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11189     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11190     // set, etc.
11191     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11192     if (Lane == ~0u)
11193       return Node;
11194 
11195     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11196     if (UsesTFC && Lane == TFCLane) {
11197       Users[Lane] = *I;
11198     } else {
11199       // Set which texture component corresponds to the lane.
11200       unsigned Comp;
11201       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11202         Comp = countTrailingZeros(Dmask);
11203         Dmask &= ~(1 << Comp);
11204       }
11205 
11206       // Abort if we have more than one user per component.
11207       if (Users[Lane])
11208         return Node;
11209 
11210       Users[Lane] = *I;
11211       NewDmask |= 1 << Comp;
11212     }
11213   }
11214 
11215   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11216   bool NoChannels = !NewDmask;
11217   if (NoChannels) {
11218     if (!UsesTFC) {
11219       // No uses of the result and not using TFC. Then do nothing.
11220       return Node;
11221     }
11222     // If the original dmask has one channel - then nothing to do
11223     if (OldBitsSet == 1)
11224       return Node;
11225     // Use an arbitrary dmask - required for the instruction to work
11226     NewDmask = 1;
11227   }
11228   // Abort if there's no change
11229   if (NewDmask == OldDmask)
11230     return Node;
11231 
11232   unsigned BitsSet = countPopulation(NewDmask);
11233 
11234   // Check for TFE or LWE - increase the number of channels by one to account
11235   // for the extra return value
11236   // This will need adjustment for D16 if this is also included in
11237   // adjustWriteMask (this function) but at present D16 are excluded.
11238   unsigned NewChannels = BitsSet + UsesTFC;
11239 
11240   int NewOpcode =
11241       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11242   assert(NewOpcode != -1 &&
11243          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11244          "failed to find equivalent MIMG op");
11245 
11246   // Adjust the writemask in the node
11247   SmallVector<SDValue, 12> Ops;
11248   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11249   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11250   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11251 
11252   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11253 
11254   MVT ResultVT = NewChannels == 1 ?
11255     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11256                            NewChannels == 5 ? 8 : NewChannels);
11257   SDVTList NewVTList = HasChain ?
11258     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11259 
11260 
11261   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11262                                               NewVTList, Ops);
11263 
11264   if (HasChain) {
11265     // Update chain.
11266     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11267     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11268   }
11269 
11270   if (NewChannels == 1) {
11271     assert(Node->hasNUsesOfValue(1, 0));
11272     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11273                                       SDLoc(Node), Users[Lane]->getValueType(0),
11274                                       SDValue(NewNode, 0));
11275     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11276     return nullptr;
11277   }
11278 
11279   // Update the users of the node with the new indices
11280   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11281     SDNode *User = Users[i];
11282     if (!User) {
11283       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11284       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11285       if (i || !NoChannels)
11286         continue;
11287     } else {
11288       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11289       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11290     }
11291 
11292     switch (Idx) {
11293     default: break;
11294     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11295     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11296     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11297     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11298     }
11299   }
11300 
11301   DAG.RemoveDeadNode(Node);
11302   return nullptr;
11303 }
11304 
11305 static bool isFrameIndexOp(SDValue Op) {
11306   if (Op.getOpcode() == ISD::AssertZext)
11307     Op = Op.getOperand(0);
11308 
11309   return isa<FrameIndexSDNode>(Op);
11310 }
11311 
11312 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11313 /// with frame index operands.
11314 /// LLVM assumes that inputs are to these instructions are registers.
11315 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11316                                                         SelectionDAG &DAG) const {
11317   if (Node->getOpcode() == ISD::CopyToReg) {
11318     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11319     SDValue SrcVal = Node->getOperand(2);
11320 
11321     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11322     // to try understanding copies to physical registers.
11323     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11324       SDLoc SL(Node);
11325       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11326       SDValue VReg = DAG.getRegister(
11327         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11328 
11329       SDNode *Glued = Node->getGluedNode();
11330       SDValue ToVReg
11331         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11332                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11333       SDValue ToResultReg
11334         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11335                            VReg, ToVReg.getValue(1));
11336       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11337       DAG.RemoveDeadNode(Node);
11338       return ToResultReg.getNode();
11339     }
11340   }
11341 
11342   SmallVector<SDValue, 8> Ops;
11343   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11344     if (!isFrameIndexOp(Node->getOperand(i))) {
11345       Ops.push_back(Node->getOperand(i));
11346       continue;
11347     }
11348 
11349     SDLoc DL(Node);
11350     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11351                                      Node->getOperand(i).getValueType(),
11352                                      Node->getOperand(i)), 0));
11353   }
11354 
11355   return DAG.UpdateNodeOperands(Node, Ops);
11356 }
11357 
11358 /// Fold the instructions after selecting them.
11359 /// Returns null if users were already updated.
11360 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11361                                           SelectionDAG &DAG) const {
11362   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11363   unsigned Opcode = Node->getMachineOpcode();
11364 
11365   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11366       !TII->isGather4(Opcode) &&
11367       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11368     return adjustWritemask(Node, DAG);
11369   }
11370 
11371   if (Opcode == AMDGPU::INSERT_SUBREG ||
11372       Opcode == AMDGPU::REG_SEQUENCE) {
11373     legalizeTargetIndependentNode(Node, DAG);
11374     return Node;
11375   }
11376 
11377   switch (Opcode) {
11378   case AMDGPU::V_DIV_SCALE_F32_e64:
11379   case AMDGPU::V_DIV_SCALE_F64_e64: {
11380     // Satisfy the operand register constraint when one of the inputs is
11381     // undefined. Ordinarily each undef value will have its own implicit_def of
11382     // a vreg, so force these to use a single register.
11383     SDValue Src0 = Node->getOperand(1);
11384     SDValue Src1 = Node->getOperand(3);
11385     SDValue Src2 = Node->getOperand(5);
11386 
11387     if ((Src0.isMachineOpcode() &&
11388          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11389         (Src0 == Src1 || Src0 == Src2))
11390       break;
11391 
11392     MVT VT = Src0.getValueType().getSimpleVT();
11393     const TargetRegisterClass *RC =
11394         getRegClassFor(VT, Src0.getNode()->isDivergent());
11395 
11396     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11397     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11398 
11399     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11400                                       UndefReg, Src0, SDValue());
11401 
11402     // src0 must be the same register as src1 or src2, even if the value is
11403     // undefined, so make sure we don't violate this constraint.
11404     if (Src0.isMachineOpcode() &&
11405         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11406       if (Src1.isMachineOpcode() &&
11407           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11408         Src0 = Src1;
11409       else if (Src2.isMachineOpcode() &&
11410                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11411         Src0 = Src2;
11412       else {
11413         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11414         Src0 = UndefReg;
11415         Src1 = UndefReg;
11416       }
11417     } else
11418       break;
11419 
11420     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11421     Ops[1] = Src0;
11422     Ops[3] = Src1;
11423     Ops[5] = Src2;
11424     Ops.push_back(ImpDef.getValue(1));
11425     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11426   }
11427   default:
11428     break;
11429   }
11430 
11431   return Node;
11432 }
11433 
11434 // Any MIMG instructions that use tfe or lwe require an initialization of the
11435 // result register that will be written in the case of a memory access failure.
11436 // The required code is also added to tie this init code to the result of the
11437 // img instruction.
11438 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11439   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11440   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11441   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11442   MachineBasicBlock &MBB = *MI.getParent();
11443 
11444   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11445   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11446   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11447 
11448   if (!TFE && !LWE) // intersect_ray
11449     return;
11450 
11451   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11452   unsigned LWEVal = LWE->getImm();
11453   unsigned D16Val = D16 ? D16->getImm() : 0;
11454 
11455   if (!TFEVal && !LWEVal)
11456     return;
11457 
11458   // At least one of TFE or LWE are non-zero
11459   // We have to insert a suitable initialization of the result value and
11460   // tie this to the dest of the image instruction.
11461 
11462   const DebugLoc &DL = MI.getDebugLoc();
11463 
11464   int DstIdx =
11465       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11466 
11467   // Calculate which dword we have to initialize to 0.
11468   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11469 
11470   // check that dmask operand is found.
11471   assert(MO_Dmask && "Expected dmask operand in instruction");
11472 
11473   unsigned dmask = MO_Dmask->getImm();
11474   // Determine the number of active lanes taking into account the
11475   // Gather4 special case
11476   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11477 
11478   bool Packed = !Subtarget->hasUnpackedD16VMem();
11479 
11480   unsigned InitIdx =
11481       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11482 
11483   // Abandon attempt if the dst size isn't large enough
11484   // - this is in fact an error but this is picked up elsewhere and
11485   // reported correctly.
11486   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11487   if (DstSize < InitIdx)
11488     return;
11489 
11490   // Create a register for the intialization value.
11491   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11492   unsigned NewDst = 0; // Final initialized value will be in here
11493 
11494   // If PRTStrictNull feature is enabled (the default) then initialize
11495   // all the result registers to 0, otherwise just the error indication
11496   // register (VGPRn+1)
11497   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11498   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11499 
11500   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11501   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11502     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11503     // Initialize dword
11504     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11505     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11506       .addImm(0);
11507     // Insert into the super-reg
11508     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11509       .addReg(PrevDst)
11510       .addReg(SubReg)
11511       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11512 
11513     PrevDst = NewDst;
11514   }
11515 
11516   // Add as an implicit operand
11517   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11518 
11519   // Tie the just added implicit operand to the dst
11520   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11521 }
11522 
11523 /// Assign the register class depending on the number of
11524 /// bits set in the writemask
11525 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11526                                                      SDNode *Node) const {
11527   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11528 
11529   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11530 
11531   if (TII->isVOP3(MI.getOpcode())) {
11532     // Make sure constant bus requirements are respected.
11533     TII->legalizeOperandsVOP3(MRI, MI);
11534 
11535     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11536     // This saves a chain-copy of registers and better ballance register
11537     // use between vgpr and agpr as agpr tuples tend to be big.
11538     if (MI.getDesc().OpInfo) {
11539       unsigned Opc = MI.getOpcode();
11540       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11541       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11542                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11543         if (I == -1)
11544           break;
11545         MachineOperand &Op = MI.getOperand(I);
11546         if (!Op.isReg() || !Op.getReg().isVirtual())
11547           continue;
11548         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11549         if (!TRI->hasAGPRs(RC))
11550           continue;
11551         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11552         if (!Src || !Src->isCopy() ||
11553             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11554           continue;
11555         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11556         // All uses of agpr64 and agpr32 can also accept vgpr except for
11557         // v_accvgpr_read, but we do not produce agpr reads during selection,
11558         // so no use checks are needed.
11559         MRI.setRegClass(Op.getReg(), NewRC);
11560       }
11561     }
11562 
11563     return;
11564   }
11565 
11566   // Replace unused atomics with the no return version.
11567   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11568   if (NoRetAtomicOp != -1) {
11569     if (!Node->hasAnyUseOfValue(0)) {
11570       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11571                                                AMDGPU::OpName::cpol);
11572       if (CPolIdx != -1) {
11573         MachineOperand &CPol = MI.getOperand(CPolIdx);
11574         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11575       }
11576       MI.RemoveOperand(0);
11577       MI.setDesc(TII->get(NoRetAtomicOp));
11578       return;
11579     }
11580 
11581     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11582     // instruction, because the return type of these instructions is a vec2 of
11583     // the memory type, so it can be tied to the input operand.
11584     // This means these instructions always have a use, so we need to add a
11585     // special case to check if the atomic has only one extract_subreg use,
11586     // which itself has no uses.
11587     if ((Node->hasNUsesOfValue(1, 0) &&
11588          Node->use_begin()->isMachineOpcode() &&
11589          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11590          !Node->use_begin()->hasAnyUseOfValue(0))) {
11591       Register Def = MI.getOperand(0).getReg();
11592 
11593       // Change this into a noret atomic.
11594       MI.setDesc(TII->get(NoRetAtomicOp));
11595       MI.RemoveOperand(0);
11596 
11597       // If we only remove the def operand from the atomic instruction, the
11598       // extract_subreg will be left with a use of a vreg without a def.
11599       // So we need to insert an implicit_def to avoid machine verifier
11600       // errors.
11601       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11602               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11603     }
11604     return;
11605   }
11606 
11607   if (TII->isMIMG(MI) && !MI.mayStore())
11608     AddIMGInit(MI);
11609 }
11610 
11611 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11612                               uint64_t Val) {
11613   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11614   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11615 }
11616 
11617 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11618                                                 const SDLoc &DL,
11619                                                 SDValue Ptr) const {
11620   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11621 
11622   // Build the half of the subregister with the constants before building the
11623   // full 128-bit register. If we are building multiple resource descriptors,
11624   // this will allow CSEing of the 2-component register.
11625   const SDValue Ops0[] = {
11626     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11627     buildSMovImm32(DAG, DL, 0),
11628     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11629     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11630     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11631   };
11632 
11633   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11634                                                 MVT::v2i32, Ops0), 0);
11635 
11636   // Combine the constants and the pointer.
11637   const SDValue Ops1[] = {
11638     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11639     Ptr,
11640     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11641     SubRegHi,
11642     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11643   };
11644 
11645   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11646 }
11647 
11648 /// Return a resource descriptor with the 'Add TID' bit enabled
11649 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11650 ///        of the resource descriptor) to create an offset, which is added to
11651 ///        the resource pointer.
11652 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11653                                            SDValue Ptr, uint32_t RsrcDword1,
11654                                            uint64_t RsrcDword2And3) const {
11655   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11656   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11657   if (RsrcDword1) {
11658     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11659                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11660                     0);
11661   }
11662 
11663   SDValue DataLo = buildSMovImm32(DAG, DL,
11664                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11665   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11666 
11667   const SDValue Ops[] = {
11668     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11669     PtrLo,
11670     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11671     PtrHi,
11672     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11673     DataLo,
11674     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11675     DataHi,
11676     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11677   };
11678 
11679   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11680 }
11681 
11682 //===----------------------------------------------------------------------===//
11683 //                         SI Inline Assembly Support
11684 //===----------------------------------------------------------------------===//
11685 
11686 std::pair<unsigned, const TargetRegisterClass *>
11687 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11688                                                StringRef Constraint,
11689                                                MVT VT) const {
11690   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11691 
11692   const TargetRegisterClass *RC = nullptr;
11693   if (Constraint.size() == 1) {
11694     const unsigned BitWidth = VT.getSizeInBits();
11695     switch (Constraint[0]) {
11696     default:
11697       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11698     case 's':
11699     case 'r':
11700       switch (BitWidth) {
11701       case 16:
11702         RC = &AMDGPU::SReg_32RegClass;
11703         break;
11704       case 64:
11705         RC = &AMDGPU::SGPR_64RegClass;
11706         break;
11707       default:
11708         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11709         if (!RC)
11710           return std::make_pair(0U, nullptr);
11711         break;
11712       }
11713       break;
11714     case 'v':
11715       switch (BitWidth) {
11716       case 16:
11717         RC = &AMDGPU::VGPR_32RegClass;
11718         break;
11719       default:
11720         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11721         if (!RC)
11722           return std::make_pair(0U, nullptr);
11723         break;
11724       }
11725       break;
11726     case 'a':
11727       if (!Subtarget->hasMAIInsts())
11728         break;
11729       switch (BitWidth) {
11730       case 16:
11731         RC = &AMDGPU::AGPR_32RegClass;
11732         break;
11733       default:
11734         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11735         if (!RC)
11736           return std::make_pair(0U, nullptr);
11737         break;
11738       }
11739       break;
11740     }
11741     // We actually support i128, i16 and f16 as inline parameters
11742     // even if they are not reported as legal
11743     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11744                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11745       return std::make_pair(0U, RC);
11746   }
11747 
11748   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11749     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11750     if (RegName.consume_front("v")) {
11751       RC = &AMDGPU::VGPR_32RegClass;
11752     } else if (RegName.consume_front("s")) {
11753       RC = &AMDGPU::SGPR_32RegClass;
11754     } else if (RegName.consume_front("a")) {
11755       RC = &AMDGPU::AGPR_32RegClass;
11756     }
11757 
11758     if (RC) {
11759       uint32_t Idx;
11760       if (RegName.consume_front("[")) {
11761         uint32_t End;
11762         bool Failed = RegName.consumeInteger(10, Idx);
11763         Failed |= !RegName.consume_front(":");
11764         Failed |= RegName.consumeInteger(10, End);
11765         Failed |= !RegName.consume_back("]");
11766         if (!Failed) {
11767           uint32_t Width = (End - Idx + 1) * 32;
11768           MCRegister Reg = RC->getRegister(Idx);
11769           if (SIRegisterInfo::isVGPRClass(RC))
11770             RC = TRI->getVGPRClassForBitWidth(Width);
11771           else if (SIRegisterInfo::isSGPRClass(RC))
11772             RC = TRI->getSGPRClassForBitWidth(Width);
11773           else if (SIRegisterInfo::isAGPRClass(RC))
11774             RC = TRI->getAGPRClassForBitWidth(Width);
11775           if (RC) {
11776             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11777             return std::make_pair(Reg, RC);
11778           }
11779         }
11780       } else {
11781         bool Failed = RegName.getAsInteger(10, Idx);
11782         if (!Failed && Idx < RC->getNumRegs())
11783           return std::make_pair(RC->getRegister(Idx), RC);
11784       }
11785     }
11786   }
11787 
11788   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11789   if (Ret.first)
11790     Ret.second = TRI->getPhysRegClass(Ret.first);
11791 
11792   return Ret;
11793 }
11794 
11795 static bool isImmConstraint(StringRef Constraint) {
11796   if (Constraint.size() == 1) {
11797     switch (Constraint[0]) {
11798     default: break;
11799     case 'I':
11800     case 'J':
11801     case 'A':
11802     case 'B':
11803     case 'C':
11804       return true;
11805     }
11806   } else if (Constraint == "DA" ||
11807              Constraint == "DB") {
11808     return true;
11809   }
11810   return false;
11811 }
11812 
11813 SITargetLowering::ConstraintType
11814 SITargetLowering::getConstraintType(StringRef Constraint) const {
11815   if (Constraint.size() == 1) {
11816     switch (Constraint[0]) {
11817     default: break;
11818     case 's':
11819     case 'v':
11820     case 'a':
11821       return C_RegisterClass;
11822     }
11823   }
11824   if (isImmConstraint(Constraint)) {
11825     return C_Other;
11826   }
11827   return TargetLowering::getConstraintType(Constraint);
11828 }
11829 
11830 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11831   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11832     Val = Val & maskTrailingOnes<uint64_t>(Size);
11833   }
11834   return Val;
11835 }
11836 
11837 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11838                                                     std::string &Constraint,
11839                                                     std::vector<SDValue> &Ops,
11840                                                     SelectionDAG &DAG) const {
11841   if (isImmConstraint(Constraint)) {
11842     uint64_t Val;
11843     if (getAsmOperandConstVal(Op, Val) &&
11844         checkAsmConstraintVal(Op, Constraint, Val)) {
11845       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11846       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11847     }
11848   } else {
11849     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11850   }
11851 }
11852 
11853 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11854   unsigned Size = Op.getScalarValueSizeInBits();
11855   if (Size > 64)
11856     return false;
11857 
11858   if (Size == 16 && !Subtarget->has16BitInsts())
11859     return false;
11860 
11861   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11862     Val = C->getSExtValue();
11863     return true;
11864   }
11865   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11866     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11867     return true;
11868   }
11869   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11870     if (Size != 16 || Op.getNumOperands() != 2)
11871       return false;
11872     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11873       return false;
11874     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11875       Val = C->getSExtValue();
11876       return true;
11877     }
11878     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11879       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11880       return true;
11881     }
11882   }
11883 
11884   return false;
11885 }
11886 
11887 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11888                                              const std::string &Constraint,
11889                                              uint64_t Val) const {
11890   if (Constraint.size() == 1) {
11891     switch (Constraint[0]) {
11892     case 'I':
11893       return AMDGPU::isInlinableIntLiteral(Val);
11894     case 'J':
11895       return isInt<16>(Val);
11896     case 'A':
11897       return checkAsmConstraintValA(Op, Val);
11898     case 'B':
11899       return isInt<32>(Val);
11900     case 'C':
11901       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11902              AMDGPU::isInlinableIntLiteral(Val);
11903     default:
11904       break;
11905     }
11906   } else if (Constraint.size() == 2) {
11907     if (Constraint == "DA") {
11908       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11909       int64_t LoBits = static_cast<int32_t>(Val);
11910       return checkAsmConstraintValA(Op, HiBits, 32) &&
11911              checkAsmConstraintValA(Op, LoBits, 32);
11912     }
11913     if (Constraint == "DB") {
11914       return true;
11915     }
11916   }
11917   llvm_unreachable("Invalid asm constraint");
11918 }
11919 
11920 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11921                                               uint64_t Val,
11922                                               unsigned MaxSize) const {
11923   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11924   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11925   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11926       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11927       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11928     return true;
11929   }
11930   return false;
11931 }
11932 
11933 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11934   switch (UnalignedClassID) {
11935   case AMDGPU::VReg_64RegClassID:
11936     return AMDGPU::VReg_64_Align2RegClassID;
11937   case AMDGPU::VReg_96RegClassID:
11938     return AMDGPU::VReg_96_Align2RegClassID;
11939   case AMDGPU::VReg_128RegClassID:
11940     return AMDGPU::VReg_128_Align2RegClassID;
11941   case AMDGPU::VReg_160RegClassID:
11942     return AMDGPU::VReg_160_Align2RegClassID;
11943   case AMDGPU::VReg_192RegClassID:
11944     return AMDGPU::VReg_192_Align2RegClassID;
11945   case AMDGPU::VReg_224RegClassID:
11946     return AMDGPU::VReg_224_Align2RegClassID;
11947   case AMDGPU::VReg_256RegClassID:
11948     return AMDGPU::VReg_256_Align2RegClassID;
11949   case AMDGPU::VReg_512RegClassID:
11950     return AMDGPU::VReg_512_Align2RegClassID;
11951   case AMDGPU::VReg_1024RegClassID:
11952     return AMDGPU::VReg_1024_Align2RegClassID;
11953   case AMDGPU::AReg_64RegClassID:
11954     return AMDGPU::AReg_64_Align2RegClassID;
11955   case AMDGPU::AReg_96RegClassID:
11956     return AMDGPU::AReg_96_Align2RegClassID;
11957   case AMDGPU::AReg_128RegClassID:
11958     return AMDGPU::AReg_128_Align2RegClassID;
11959   case AMDGPU::AReg_160RegClassID:
11960     return AMDGPU::AReg_160_Align2RegClassID;
11961   case AMDGPU::AReg_192RegClassID:
11962     return AMDGPU::AReg_192_Align2RegClassID;
11963   case AMDGPU::AReg_256RegClassID:
11964     return AMDGPU::AReg_256_Align2RegClassID;
11965   case AMDGPU::AReg_512RegClassID:
11966     return AMDGPU::AReg_512_Align2RegClassID;
11967   case AMDGPU::AReg_1024RegClassID:
11968     return AMDGPU::AReg_1024_Align2RegClassID;
11969   default:
11970     return -1;
11971   }
11972 }
11973 
11974 // Figure out which registers should be reserved for stack access. Only after
11975 // the function is legalized do we know all of the non-spill stack objects or if
11976 // calls are present.
11977 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11978   MachineRegisterInfo &MRI = MF.getRegInfo();
11979   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11980   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11981   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11982   const SIInstrInfo *TII = ST.getInstrInfo();
11983 
11984   if (Info->isEntryFunction()) {
11985     // Callable functions have fixed registers used for stack access.
11986     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11987   }
11988 
11989   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11990                              Info->getStackPtrOffsetReg()));
11991   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11992     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11993 
11994   // We need to worry about replacing the default register with itself in case
11995   // of MIR testcases missing the MFI.
11996   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11997     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11998 
11999   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12000     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12001 
12002   Info->limitOccupancy(MF);
12003 
12004   if (ST.isWave32() && !MF.empty()) {
12005     for (auto &MBB : MF) {
12006       for (auto &MI : MBB) {
12007         TII->fixImplicitOperands(MI);
12008       }
12009     }
12010   }
12011 
12012   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12013   // classes if required. Ideally the register class constraints would differ
12014   // per-subtarget, but there's no easy way to achieve that right now. This is
12015   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12016   // from using them as the register class for legal types.
12017   if (ST.needsAlignedVGPRs()) {
12018     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12019       const Register Reg = Register::index2VirtReg(I);
12020       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12021       if (!RC)
12022         continue;
12023       int NewClassID = getAlignedAGPRClassID(RC->getID());
12024       if (NewClassID != -1)
12025         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12026     }
12027   }
12028 
12029   TargetLoweringBase::finalizeLowering(MF);
12030 }
12031 
12032 void SITargetLowering::computeKnownBitsForFrameIndex(
12033   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12034   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12035 
12036   // Set the high bits to zero based on the maximum allowed scratch size per
12037   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12038   // calculation won't overflow, so assume the sign bit is never set.
12039   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12040 }
12041 
12042 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12043                                    KnownBits &Known, unsigned Dim) {
12044   unsigned MaxValue =
12045       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12046   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12047 }
12048 
12049 void SITargetLowering::computeKnownBitsForTargetInstr(
12050     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12051     const MachineRegisterInfo &MRI, unsigned Depth) const {
12052   const MachineInstr *MI = MRI.getVRegDef(R);
12053   switch (MI->getOpcode()) {
12054   case AMDGPU::G_INTRINSIC: {
12055     switch (MI->getIntrinsicID()) {
12056     case Intrinsic::amdgcn_workitem_id_x:
12057       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12058       break;
12059     case Intrinsic::amdgcn_workitem_id_y:
12060       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12061       break;
12062     case Intrinsic::amdgcn_workitem_id_z:
12063       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12064       break;
12065     case Intrinsic::amdgcn_mbcnt_lo:
12066     case Intrinsic::amdgcn_mbcnt_hi: {
12067       // These return at most the wavefront size - 1.
12068       unsigned Size = MRI.getType(R).getSizeInBits();
12069       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12070       break;
12071     }
12072     case Intrinsic::amdgcn_groupstaticsize: {
12073       // We can report everything over the maximum size as 0. We can't report
12074       // based on the actual size because we don't know if it's accurate or not
12075       // at any given point.
12076       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12077       break;
12078     }
12079     }
12080     break;
12081   }
12082   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12083     Known.Zero.setHighBits(24);
12084     break;
12085   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12086     Known.Zero.setHighBits(16);
12087     break;
12088   }
12089 }
12090 
12091 Align SITargetLowering::computeKnownAlignForTargetInstr(
12092   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12093   unsigned Depth) const {
12094   const MachineInstr *MI = MRI.getVRegDef(R);
12095   switch (MI->getOpcode()) {
12096   case AMDGPU::G_INTRINSIC:
12097   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12098     // FIXME: Can this move to generic code? What about the case where the call
12099     // site specifies a lower alignment?
12100     Intrinsic::ID IID = MI->getIntrinsicID();
12101     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12102     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12103     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12104       return *RetAlign;
12105     return Align(1);
12106   }
12107   default:
12108     return Align(1);
12109   }
12110 }
12111 
12112 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12113   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12114   const Align CacheLineAlign = Align(64);
12115 
12116   // Pre-GFX10 target did not benefit from loop alignment
12117   if (!ML || DisableLoopAlignment ||
12118       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12119       getSubtarget()->hasInstFwdPrefetchBug())
12120     return PrefAlign;
12121 
12122   // On GFX10 I$ is 4 x 64 bytes cache lines.
12123   // By default prefetcher keeps one cache line behind and reads two ahead.
12124   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12125   // behind and one ahead.
12126   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12127   // If loop fits 64 bytes it always spans no more than two cache lines and
12128   // does not need an alignment.
12129   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12130   // Else if loop is less or equal 192 bytes we need two lines behind.
12131 
12132   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12133   const MachineBasicBlock *Header = ML->getHeader();
12134   if (Header->getAlignment() != PrefAlign)
12135     return Header->getAlignment(); // Already processed.
12136 
12137   unsigned LoopSize = 0;
12138   for (const MachineBasicBlock *MBB : ML->blocks()) {
12139     // If inner loop block is aligned assume in average half of the alignment
12140     // size to be added as nops.
12141     if (MBB != Header)
12142       LoopSize += MBB->getAlignment().value() / 2;
12143 
12144     for (const MachineInstr &MI : *MBB) {
12145       LoopSize += TII->getInstSizeInBytes(MI);
12146       if (LoopSize > 192)
12147         return PrefAlign;
12148     }
12149   }
12150 
12151   if (LoopSize <= 64)
12152     return PrefAlign;
12153 
12154   if (LoopSize <= 128)
12155     return CacheLineAlign;
12156 
12157   // If any of parent loops is surrounded by prefetch instructions do not
12158   // insert new for inner loop, which would reset parent's settings.
12159   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12160     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12161       auto I = Exit->getFirstNonDebugInstr();
12162       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12163         return CacheLineAlign;
12164     }
12165   }
12166 
12167   MachineBasicBlock *Pre = ML->getLoopPreheader();
12168   MachineBasicBlock *Exit = ML->getExitBlock();
12169 
12170   if (Pre && Exit) {
12171     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12172             TII->get(AMDGPU::S_INST_PREFETCH))
12173       .addImm(1); // prefetch 2 lines behind PC
12174 
12175     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12176             TII->get(AMDGPU::S_INST_PREFETCH))
12177       .addImm(2); // prefetch 1 line behind PC
12178   }
12179 
12180   return CacheLineAlign;
12181 }
12182 
12183 LLVM_ATTRIBUTE_UNUSED
12184 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12185   assert(N->getOpcode() == ISD::CopyFromReg);
12186   do {
12187     // Follow the chain until we find an INLINEASM node.
12188     N = N->getOperand(0).getNode();
12189     if (N->getOpcode() == ISD::INLINEASM ||
12190         N->getOpcode() == ISD::INLINEASM_BR)
12191       return true;
12192   } while (N->getOpcode() == ISD::CopyFromReg);
12193   return false;
12194 }
12195 
12196 bool SITargetLowering::isSDNodeSourceOfDivergence(
12197     const SDNode *N, FunctionLoweringInfo *FLI,
12198     LegacyDivergenceAnalysis *KDA) const {
12199   switch (N->getOpcode()) {
12200   case ISD::CopyFromReg: {
12201     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12202     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12203     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12204     Register Reg = R->getReg();
12205 
12206     // FIXME: Why does this need to consider isLiveIn?
12207     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12208       return !TRI->isSGPRReg(MRI, Reg);
12209 
12210     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12211       return KDA->isDivergent(V);
12212 
12213     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12214     return !TRI->isSGPRReg(MRI, Reg);
12215   }
12216   case ISD::LOAD: {
12217     const LoadSDNode *L = cast<LoadSDNode>(N);
12218     unsigned AS = L->getAddressSpace();
12219     // A flat load may access private memory.
12220     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12221   }
12222   case ISD::CALLSEQ_END:
12223     return true;
12224   case ISD::INTRINSIC_WO_CHAIN:
12225     return AMDGPU::isIntrinsicSourceOfDivergence(
12226         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12227   case ISD::INTRINSIC_W_CHAIN:
12228     return AMDGPU::isIntrinsicSourceOfDivergence(
12229         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12230   case AMDGPUISD::ATOMIC_CMP_SWAP:
12231   case AMDGPUISD::ATOMIC_INC:
12232   case AMDGPUISD::ATOMIC_DEC:
12233   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12234   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12235   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12236   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12237   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12238   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12239   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12240   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12241   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12242   case AMDGPUISD::BUFFER_ATOMIC_AND:
12243   case AMDGPUISD::BUFFER_ATOMIC_OR:
12244   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12245   case AMDGPUISD::BUFFER_ATOMIC_INC:
12246   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12247   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12248   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12249   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12250   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12251   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12252     // Target-specific read-modify-write atomics are sources of divergence.
12253     return true;
12254   default:
12255     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12256       // Generic read-modify-write atomics are sources of divergence.
12257       return A->readMem() && A->writeMem();
12258     }
12259     return false;
12260   }
12261 }
12262 
12263 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12264                                                EVT VT) const {
12265   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12266   case MVT::f32:
12267     return hasFP32Denormals(DAG.getMachineFunction());
12268   case MVT::f64:
12269   case MVT::f16:
12270     return hasFP64FP16Denormals(DAG.getMachineFunction());
12271   default:
12272     return false;
12273   }
12274 }
12275 
12276 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12277                                                MachineFunction &MF) const {
12278   switch (Ty.getScalarSizeInBits()) {
12279   case 32:
12280     return hasFP32Denormals(MF);
12281   case 64:
12282   case 16:
12283     return hasFP64FP16Denormals(MF);
12284   default:
12285     return false;
12286   }
12287 }
12288 
12289 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12290                                                     const SelectionDAG &DAG,
12291                                                     bool SNaN,
12292                                                     unsigned Depth) const {
12293   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12294     const MachineFunction &MF = DAG.getMachineFunction();
12295     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12296 
12297     if (Info->getMode().DX10Clamp)
12298       return true; // Clamped to 0.
12299     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12300   }
12301 
12302   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12303                                                             SNaN, Depth);
12304 }
12305 
12306 // Global FP atomic instructions have a hardcoded FP mode and do not support
12307 // FP32 denormals, and only support v2f16 denormals.
12308 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12309   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12310   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12311   if (&Flt == &APFloat::IEEEsingle())
12312     return DenormMode == DenormalMode::getPreserveSign();
12313   return DenormMode == DenormalMode::getIEEE();
12314 }
12315 
12316 TargetLowering::AtomicExpansionKind
12317 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12318 
12319   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12320     OptimizationRemarkEmitter ORE(RMW->getFunction());
12321     LLVMContext &Ctx = RMW->getFunction()->getContext();
12322     SmallVector<StringRef> SSNs;
12323     Ctx.getSyncScopeNames(SSNs);
12324     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12325                         ? "system"
12326                         : SSNs[RMW->getSyncScopeID()];
12327     ORE.emit([&]() {
12328       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12329              << "Hardware instruction generated for atomic "
12330              << RMW->getOperationName(RMW->getOperation())
12331              << " operation at memory scope " << MemScope
12332              << " due to an unsafe request.";
12333     });
12334     return Kind;
12335   };
12336 
12337   switch (RMW->getOperation()) {
12338   case AtomicRMWInst::FAdd: {
12339     Type *Ty = RMW->getType();
12340 
12341     // We don't have a way to support 16-bit atomics now, so just leave them
12342     // as-is.
12343     if (Ty->isHalfTy())
12344       return AtomicExpansionKind::None;
12345 
12346     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12347       return AtomicExpansionKind::CmpXChg;
12348 
12349     unsigned AS = RMW->getPointerAddressSpace();
12350 
12351     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12352          Subtarget->hasAtomicFaddInsts()) {
12353       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12354       // floating point atomic instructions. May generate more efficient code,
12355       // but may not respect rounding and denormal modes, and may give incorrect
12356       // results for certain memory destinations.
12357       if (RMW->getFunction()
12358               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12359               .getValueAsString() != "true")
12360         return AtomicExpansionKind::CmpXChg;
12361 
12362       if (Subtarget->hasGFX90AInsts()) {
12363         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12364           return AtomicExpansionKind::CmpXChg;
12365 
12366         auto SSID = RMW->getSyncScopeID();
12367         if (SSID == SyncScope::System ||
12368             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12369           return AtomicExpansionKind::CmpXChg;
12370 
12371         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12372       }
12373 
12374       if (AS == AMDGPUAS::FLAT_ADDRESS)
12375         return AtomicExpansionKind::CmpXChg;
12376 
12377       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12378                               : AtomicExpansionKind::CmpXChg;
12379     }
12380 
12381     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12382     // to round-to-nearest-even.
12383     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12384     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12385       if (!Ty->isDoubleTy())
12386         return AtomicExpansionKind::None;
12387 
12388       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12389         return AtomicExpansionKind::None;
12390 
12391       return RMW->getFunction()
12392                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12393                          .getValueAsString() == "true"
12394                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12395                  : AtomicExpansionKind::CmpXChg;
12396     }
12397 
12398     return AtomicExpansionKind::CmpXChg;
12399   }
12400   default:
12401     break;
12402   }
12403 
12404   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12405 }
12406 
12407 const TargetRegisterClass *
12408 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12409   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12410   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12411   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12412     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12413                                                : &AMDGPU::SReg_32RegClass;
12414   if (!TRI->isSGPRClass(RC) && !isDivergent)
12415     return TRI->getEquivalentSGPRClass(RC);
12416   else if (TRI->isSGPRClass(RC) && isDivergent)
12417     return TRI->getEquivalentVGPRClass(RC);
12418 
12419   return RC;
12420 }
12421 
12422 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12423 // uniform values (as produced by the mask results of control flow intrinsics)
12424 // used outside of divergent blocks. The phi users need to also be treated as
12425 // always uniform.
12426 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12427                       unsigned WaveSize) {
12428   // FIXME: We asssume we never cast the mask results of a control flow
12429   // intrinsic.
12430   // Early exit if the type won't be consistent as a compile time hack.
12431   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12432   if (!IT || IT->getBitWidth() != WaveSize)
12433     return false;
12434 
12435   if (!isa<Instruction>(V))
12436     return false;
12437   if (!Visited.insert(V).second)
12438     return false;
12439   bool Result = false;
12440   for (auto U : V->users()) {
12441     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12442       if (V == U->getOperand(1)) {
12443         switch (Intrinsic->getIntrinsicID()) {
12444         default:
12445           Result = false;
12446           break;
12447         case Intrinsic::amdgcn_if_break:
12448         case Intrinsic::amdgcn_if:
12449         case Intrinsic::amdgcn_else:
12450           Result = true;
12451           break;
12452         }
12453       }
12454       if (V == U->getOperand(0)) {
12455         switch (Intrinsic->getIntrinsicID()) {
12456         default:
12457           Result = false;
12458           break;
12459         case Intrinsic::amdgcn_end_cf:
12460         case Intrinsic::amdgcn_loop:
12461           Result = true;
12462           break;
12463         }
12464       }
12465     } else {
12466       Result = hasCFUser(U, Visited, WaveSize);
12467     }
12468     if (Result)
12469       break;
12470   }
12471   return Result;
12472 }
12473 
12474 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12475                                                const Value *V) const {
12476   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12477     if (CI->isInlineAsm()) {
12478       // FIXME: This cannot give a correct answer. This should only trigger in
12479       // the case where inline asm returns mixed SGPR and VGPR results, used
12480       // outside the defining block. We don't have a specific result to
12481       // consider, so this assumes if any value is SGPR, the overall register
12482       // also needs to be SGPR.
12483       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12484       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12485           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12486       for (auto &TC : TargetConstraints) {
12487         if (TC.Type == InlineAsm::isOutput) {
12488           ComputeConstraintToUse(TC, SDValue());
12489           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12490               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12491           if (RC && SIRI->isSGPRClass(RC))
12492             return true;
12493         }
12494       }
12495     }
12496   }
12497   SmallPtrSet<const Value *, 16> Visited;
12498   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12499 }
12500 
12501 std::pair<InstructionCost, MVT>
12502 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12503                                           Type *Ty) const {
12504   std::pair<InstructionCost, MVT> Cost =
12505       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12506   auto Size = DL.getTypeSizeInBits(Ty);
12507   // Maximum load or store can handle 8 dwords for scalar and 4 for
12508   // vector ALU. Let's assume anything above 8 dwords is expensive
12509   // even if legal.
12510   if (Size <= 256)
12511     return Cost;
12512 
12513   Cost.first += (Size + 255) / 256;
12514   return Cost;
12515 }
12516