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     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
138     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
139   }
140 
141   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
142   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
143 
144   computeRegisterProperties(Subtarget->getRegisterInfo());
145 
146   // The boolean content concept here is too inflexible. Compares only ever
147   // really produce a 1-bit result. Any copy/extend from these will turn into a
148   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
149   // it's what most targets use.
150   setBooleanContents(ZeroOrOneBooleanContent);
151   setBooleanVectorContents(ZeroOrOneBooleanContent);
152 
153   // We need to custom lower vector stores from local memory
154   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::i1, Custom);
163   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
164 
165   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
166   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
173   setOperationAction(ISD::STORE, MVT::i1, Custom);
174   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
175 
176   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
177   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
178   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
179   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
180   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
181   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
182   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
183   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
184   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
185   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
186   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
187   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
188   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
189   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
190   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
191   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
192 
193   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
194   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
195   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
196   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
199   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
200 
201   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
202   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
203 
204   setOperationAction(ISD::SELECT, MVT::i1, Promote);
205   setOperationAction(ISD::SELECT, MVT::i64, Custom);
206   setOperationAction(ISD::SELECT, MVT::f64, Promote);
207   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
208 
209   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
210   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
214 
215   setOperationAction(ISD::SETCC, MVT::i1, Promote);
216   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
217   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
218   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
219 
220   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
221   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
222   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
236 
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
245 
246   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
248   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
250   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
252 
253   setOperationAction(ISD::UADDO, MVT::i32, Legal);
254   setOperationAction(ISD::USUBO, MVT::i32, Legal);
255 
256   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
258 
259   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
260   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
262 
263 #if 0
264   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
265   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
266 #endif
267 
268   // We only support LOAD/STORE and vector manipulation ops for vectors
269   // with > 4 elements.
270   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
271                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
272                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
273                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
274                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
275                   MVT::v32i32, MVT::v32f32 }) {
276     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
277       switch (Op) {
278       case ISD::LOAD:
279       case ISD::STORE:
280       case ISD::BUILD_VECTOR:
281       case ISD::BITCAST:
282       case ISD::EXTRACT_VECTOR_ELT:
283       case ISD::INSERT_VECTOR_ELT:
284       case ISD::EXTRACT_SUBVECTOR:
285       case ISD::SCALAR_TO_VECTOR:
286         break;
287       case ISD::INSERT_SUBVECTOR:
288       case ISD::CONCAT_VECTORS:
289         setOperationAction(Op, VT, Custom);
290         break;
291       default:
292         setOperationAction(Op, VT, Expand);
293         break;
294       }
295     }
296   }
297 
298   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
299 
300   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
301   // is expanded to avoid having two separate loops in case the index is a VGPR.
302 
303   // Most operations are naturally 32-bit vector operations. We only support
304   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
305   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
306     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
314 
315     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
317   }
318 
319   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
320     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
322 
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
325 
326     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
328 
329     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
331   }
332 
333   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
334     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
341     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
344     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
345   }
346 
347   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
348     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
355     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
358     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
359   }
360 
361   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
362     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
369     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
372     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
373   }
374 
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
379 
380   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
382 
383   // Avoid stack access for these.
384   // TODO: Generalize to more vector types.
385   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
387   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
389 
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396 
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401 
402   // Deal with vec3 vector operations when widened to vec4.
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407 
408   // Deal with vec5/6/7 vector operations when widened to vec8.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
417 
418   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
419   // and output demarshalling
420   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
422 
423   // We can't return success/failure, only the old value,
424   // let LLVM add the comparison
425   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
427 
428   if (Subtarget->hasFlatAddressSpace()) {
429     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
431   }
432 
433   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
434   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
435 
436   // FIXME: This should be narrowed to i32, but that only happens if i64 is
437   // illegal.
438   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
439   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
440   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
441 
442   // On SI this is s_memtime and s_memrealtime on VI.
443   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444   setOperationAction(ISD::TRAP, MVT::Other, Custom);
445   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
446 
447   if (Subtarget->has16BitInsts()) {
448     setOperationAction(ISD::FPOW, MVT::f16, Promote);
449     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
450     setOperationAction(ISD::FLOG, MVT::f16, Custom);
451     setOperationAction(ISD::FEXP, MVT::f16, Custom);
452     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453   }
454 
455   if (Subtarget->hasMadMacF32Insts())
456     setOperationAction(ISD::FMAD, MVT::f32, Legal);
457 
458   if (!Subtarget->hasBFI()) {
459     // fcopysign can be done in a single instruction with BFI.
460     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
461     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
462   }
463 
464   if (!Subtarget->hasBCNT(32))
465     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
466 
467   if (!Subtarget->hasBCNT(64))
468     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
469 
470   if (Subtarget->hasFFBH()) {
471     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473   }
474 
475   if (Subtarget->hasFFBL()) {
476     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478   }
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
618                    MVT::v8f16}) {
619       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
620         switch (Op) {
621         case ISD::LOAD:
622         case ISD::STORE:
623         case ISD::BUILD_VECTOR:
624         case ISD::BITCAST:
625         case ISD::EXTRACT_VECTOR_ELT:
626         case ISD::INSERT_VECTOR_ELT:
627         case ISD::INSERT_SUBVECTOR:
628         case ISD::EXTRACT_SUBVECTOR:
629         case ISD::SCALAR_TO_VECTOR:
630           break;
631         case ISD::CONCAT_VECTORS:
632           setOperationAction(Op, VT, Custom);
633           break;
634         default:
635           setOperationAction(Op, VT, Expand);
636           break;
637         }
638       }
639     }
640 
641     // v_perm_b32 can handle either of these.
642     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
644     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
645 
646     // XXX - Do these do anything? Vector constants turn into build_vector.
647     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
648     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
651     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
655     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
657 
658     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
660     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
662 
663     setOperationAction(ISD::AND, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::OR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
669 
670     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
672     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
674 
675     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
677     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
679 
680     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
681     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
682     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
683     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
684 
685     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
686     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
687     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
688     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
689 
690     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
691     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
692     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
693     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
694 
695     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
696     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
697     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
698     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
699 
700     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
701     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
702     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
703 
704     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
705     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
706     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
707 
708     if (!Subtarget->hasVOP3PInsts()) {
709       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
710       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
711     }
712 
713     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
714     // This isn't really legal, but this avoids the legalizer unrolling it (and
715     // allows matching fneg (fabs x) patterns)
716     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
717 
718     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
719     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
720     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
721     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
722 
723     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
724     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
725     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
726     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
727 
728     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
729     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
730     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
731     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
732 
733     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
734       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
735       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
736       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
737       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand);
738     }
739   }
740 
741   if (Subtarget->hasVOP3PInsts()) {
742     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
743     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
744     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
745     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
746     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
747     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
748     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
749     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
750     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
751     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
754     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
755     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
756     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
757 
758     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
759     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
760     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
761 
762     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
763     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
764 
765     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
766 
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
768     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
769 
770     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
771     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
772     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
774 
775     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
776       // Split vector operations.
777       setOperationAction(ISD::SHL, VT, Custom);
778       setOperationAction(ISD::SRA, VT, Custom);
779       setOperationAction(ISD::SRL, VT, Custom);
780       setOperationAction(ISD::ADD, VT, Custom);
781       setOperationAction(ISD::SUB, VT, Custom);
782       setOperationAction(ISD::MUL, VT, Custom);
783 
784       setOperationAction(ISD::SMIN, VT, Custom);
785       setOperationAction(ISD::SMAX, VT, Custom);
786       setOperationAction(ISD::UMIN, VT, Custom);
787       setOperationAction(ISD::UMAX, VT, Custom);
788 
789       setOperationAction(ISD::UADDSAT, VT, Custom);
790       setOperationAction(ISD::SADDSAT, VT, Custom);
791       setOperationAction(ISD::USUBSAT, VT, Custom);
792       setOperationAction(ISD::SSUBSAT, VT, Custom);
793     }
794 
795     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
796       // Split vector operations.
797       setOperationAction(ISD::FADD, VT, Custom);
798       setOperationAction(ISD::FMUL, VT, Custom);
799       setOperationAction(ISD::FMA, VT, Custom);
800       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
801     }
802 
803     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
804     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
805 
806     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
807     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
808 
809     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
810     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
811     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
812 
813     if (Subtarget->hasPackedFP32Ops()) {
814       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
815       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
816       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
817       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
818 
819       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
820         setOperationAction(ISD::FADD, VT, Custom);
821         setOperationAction(ISD::FMUL, VT, Custom);
822         setOperationAction(ISD::FMA, VT, Custom);
823       }
824     }
825   }
826 
827   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
828   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
829 
830   if (Subtarget->has16BitInsts()) {
831     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
832     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
833     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
834     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
835   } else {
836     // Legalization hack.
837     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
838     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
839 
840     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
841     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
842   }
843 
844   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
845                   MVT::v8i16, MVT::v8f16 }) {
846     setOperationAction(ISD::SELECT, VT, Custom);
847   }
848 
849   setOperationAction(ISD::SMULO, MVT::i64, Custom);
850   setOperationAction(ISD::UMULO, MVT::i64, Custom);
851 
852   if (Subtarget->hasMad64_32()) {
853     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
854     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
855   }
856 
857   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
858   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
864 
865   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
866   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
867   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
876 
877   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
878   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
879   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
887 
888   setTargetDAGCombine(ISD::ADD);
889   setTargetDAGCombine(ISD::ADDCARRY);
890   setTargetDAGCombine(ISD::SUB);
891   setTargetDAGCombine(ISD::SUBCARRY);
892   setTargetDAGCombine(ISD::FADD);
893   setTargetDAGCombine(ISD::FSUB);
894   setTargetDAGCombine(ISD::FMINNUM);
895   setTargetDAGCombine(ISD::FMAXNUM);
896   setTargetDAGCombine(ISD::FMINNUM_IEEE);
897   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
898   setTargetDAGCombine(ISD::FMA);
899   setTargetDAGCombine(ISD::SMIN);
900   setTargetDAGCombine(ISD::SMAX);
901   setTargetDAGCombine(ISD::UMIN);
902   setTargetDAGCombine(ISD::UMAX);
903   setTargetDAGCombine(ISD::SETCC);
904   setTargetDAGCombine(ISD::AND);
905   setTargetDAGCombine(ISD::OR);
906   setTargetDAGCombine(ISD::XOR);
907   setTargetDAGCombine(ISD::SINT_TO_FP);
908   setTargetDAGCombine(ISD::UINT_TO_FP);
909   setTargetDAGCombine(ISD::FCANONICALIZE);
910   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
911   setTargetDAGCombine(ISD::ZERO_EXTEND);
912   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
913   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
914   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
915 
916   // All memory operations. Some folding on the pointer operand is done to help
917   // matching the constant offsets in the addressing modes.
918   setTargetDAGCombine(ISD::LOAD);
919   setTargetDAGCombine(ISD::STORE);
920   setTargetDAGCombine(ISD::ATOMIC_LOAD);
921   setTargetDAGCombine(ISD::ATOMIC_STORE);
922   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
923   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
924   setTargetDAGCombine(ISD::ATOMIC_SWAP);
925   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
926   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
927   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
928   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
929   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
930   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
931   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
932   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
933   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
934   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
935   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
936   setTargetDAGCombine(ISD::INTRINSIC_VOID);
937   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
938 
939   // FIXME: In other contexts we pretend this is a per-function property.
940   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
941 
942   setSchedulingPreference(Sched::RegPressure);
943 }
944 
945 const GCNSubtarget *SITargetLowering::getSubtarget() const {
946   return Subtarget;
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // TargetLowering queries
951 //===----------------------------------------------------------------------===//
952 
953 // v_mad_mix* support a conversion from f16 to f32.
954 //
955 // There is only one special case when denormals are enabled we don't currently,
956 // where this is OK to use.
957 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
958                                        EVT DestVT, EVT SrcVT) const {
959   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
960           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
961     DestVT.getScalarType() == MVT::f32 &&
962     SrcVT.getScalarType() == MVT::f16 &&
963     // TODO: This probably only requires no input flushing?
964     !hasFP32Denormals(DAG.getMachineFunction());
965 }
966 
967 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
968                                        LLT DestTy, LLT SrcTy) const {
969   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
970           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
971          DestTy.getScalarSizeInBits() == 32 &&
972          SrcTy.getScalarSizeInBits() == 16 &&
973          // TODO: This probably only requires no input flushing?
974          !hasFP32Denormals(*MI.getMF());
975 }
976 
977 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
978   // SI has some legal vector types, but no legal vector operations. Say no
979   // shuffles are legal in order to prefer scalarizing some vector operations.
980   return false;
981 }
982 
983 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
984                                                     CallingConv::ID CC,
985                                                     EVT VT) const {
986   if (CC == CallingConv::AMDGPU_KERNEL)
987     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
988 
989   if (VT.isVector()) {
990     EVT ScalarVT = VT.getScalarType();
991     unsigned Size = ScalarVT.getSizeInBits();
992     if (Size == 16) {
993       if (Subtarget->has16BitInsts())
994         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
995       return VT.isInteger() ? MVT::i32 : MVT::f32;
996     }
997 
998     if (Size < 16)
999       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1000     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1001   }
1002 
1003   if (VT.getSizeInBits() > 32)
1004     return MVT::i32;
1005 
1006   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1007 }
1008 
1009 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1010                                                          CallingConv::ID CC,
1011                                                          EVT VT) const {
1012   if (CC == CallingConv::AMDGPU_KERNEL)
1013     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1014 
1015   if (VT.isVector()) {
1016     unsigned NumElts = VT.getVectorNumElements();
1017     EVT ScalarVT = VT.getScalarType();
1018     unsigned Size = ScalarVT.getSizeInBits();
1019 
1020     // FIXME: Should probably promote 8-bit vectors to i16.
1021     if (Size == 16 && Subtarget->has16BitInsts())
1022       return (NumElts + 1) / 2;
1023 
1024     if (Size <= 32)
1025       return NumElts;
1026 
1027     if (Size > 32)
1028       return NumElts * ((Size + 31) / 32);
1029   } else if (VT.getSizeInBits() > 32)
1030     return (VT.getSizeInBits() + 31) / 32;
1031 
1032   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1033 }
1034 
1035 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1036   LLVMContext &Context, CallingConv::ID CC,
1037   EVT VT, EVT &IntermediateVT,
1038   unsigned &NumIntermediates, MVT &RegisterVT) const {
1039   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1040     unsigned NumElts = VT.getVectorNumElements();
1041     EVT ScalarVT = VT.getScalarType();
1042     unsigned Size = ScalarVT.getSizeInBits();
1043     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1044     // support, but unless we can properly handle 3-vectors, it will be still be
1045     // inconsistent.
1046     if (Size == 16 && Subtarget->has16BitInsts()) {
1047       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1048       IntermediateVT = RegisterVT;
1049       NumIntermediates = (NumElts + 1) / 2;
1050       return NumIntermediates;
1051     }
1052 
1053     if (Size == 32) {
1054       RegisterVT = ScalarVT.getSimpleVT();
1055       IntermediateVT = RegisterVT;
1056       NumIntermediates = NumElts;
1057       return NumIntermediates;
1058     }
1059 
1060     if (Size < 16 && Subtarget->has16BitInsts()) {
1061       // FIXME: Should probably form v2i16 pieces
1062       RegisterVT = MVT::i16;
1063       IntermediateVT = ScalarVT;
1064       NumIntermediates = NumElts;
1065       return NumIntermediates;
1066     }
1067 
1068 
1069     if (Size != 16 && Size <= 32) {
1070       RegisterVT = MVT::i32;
1071       IntermediateVT = ScalarVT;
1072       NumIntermediates = NumElts;
1073       return NumIntermediates;
1074     }
1075 
1076     if (Size > 32) {
1077       RegisterVT = MVT::i32;
1078       IntermediateVT = RegisterVT;
1079       NumIntermediates = NumElts * ((Size + 31) / 32);
1080       return NumIntermediates;
1081     }
1082   }
1083 
1084   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1085     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1086 }
1087 
1088 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1089   assert(DMaskLanes != 0);
1090 
1091   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1092     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1093     return EVT::getVectorVT(Ty->getContext(),
1094                             EVT::getEVT(VT->getElementType()),
1095                             NumElts);
1096   }
1097 
1098   return EVT::getEVT(Ty);
1099 }
1100 
1101 // Peek through TFE struct returns to only use the data size.
1102 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1103   auto *ST = dyn_cast<StructType>(Ty);
1104   if (!ST)
1105     return memVTFromImageData(Ty, DMaskLanes);
1106 
1107   // Some intrinsics return an aggregate type - special case to work out the
1108   // correct memVT.
1109   //
1110   // Only limited forms of aggregate type currently expected.
1111   if (ST->getNumContainedTypes() != 2 ||
1112       !ST->getContainedType(1)->isIntegerTy(32))
1113     return EVT();
1114   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1115 }
1116 
1117 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1118                                           const CallInst &CI,
1119                                           MachineFunction &MF,
1120                                           unsigned IntrID) const {
1121   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1122           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1123     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1124                                                   (Intrinsic::ID)IntrID);
1125     if (Attr.hasFnAttr(Attribute::ReadNone))
1126       return false;
1127 
1128     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1129 
1130     if (RsrcIntr->IsImage) {
1131       Info.ptrVal =
1132           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1133       Info.align.reset();
1134     } else {
1135       Info.ptrVal =
1136           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1137     }
1138 
1139     Info.flags = MachineMemOperand::MODereferenceable;
1140     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1141       unsigned DMaskLanes = 4;
1142 
1143       if (RsrcIntr->IsImage) {
1144         const AMDGPU::ImageDimIntrinsicInfo *Intr
1145           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1146         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1147           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1148 
1149         if (!BaseOpcode->Gather4) {
1150           // If this isn't a gather, we may have excess loaded elements in the
1151           // IR type. Check the dmask for the real number of elements loaded.
1152           unsigned DMask
1153             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1154           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1155         }
1156 
1157         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1158       } else
1159         Info.memVT = EVT::getEVT(CI.getType());
1160 
1161       // FIXME: What does alignment mean for an image?
1162       Info.opc = ISD::INTRINSIC_W_CHAIN;
1163       Info.flags |= MachineMemOperand::MOLoad;
1164     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1165       Info.opc = ISD::INTRINSIC_VOID;
1166 
1167       Type *DataTy = CI.getArgOperand(0)->getType();
1168       if (RsrcIntr->IsImage) {
1169         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1170         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1171         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1172       } else
1173         Info.memVT = EVT::getEVT(DataTy);
1174 
1175       Info.flags |= MachineMemOperand::MOStore;
1176     } else {
1177       // Atomic
1178       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1179                                             ISD::INTRINSIC_W_CHAIN;
1180       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1181       Info.flags = MachineMemOperand::MOLoad |
1182                    MachineMemOperand::MOStore |
1183                    MachineMemOperand::MODereferenceable;
1184 
1185       // XXX - Should this be volatile without known ordering?
1186       Info.flags |= MachineMemOperand::MOVolatile;
1187     }
1188     return true;
1189   }
1190 
1191   switch (IntrID) {
1192   case Intrinsic::amdgcn_atomic_inc:
1193   case Intrinsic::amdgcn_atomic_dec:
1194   case Intrinsic::amdgcn_ds_ordered_add:
1195   case Intrinsic::amdgcn_ds_ordered_swap:
1196   case Intrinsic::amdgcn_ds_fadd:
1197   case Intrinsic::amdgcn_ds_fmin:
1198   case Intrinsic::amdgcn_ds_fmax: {
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 | MachineMemOperand::MOStore;
1204 
1205     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1206     if (!Vol->isZero())
1207       Info.flags |= MachineMemOperand::MOVolatile;
1208 
1209     return true;
1210   }
1211   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1212     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1213 
1214     Info.opc = ISD::INTRINSIC_W_CHAIN;
1215     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1216     Info.ptrVal =
1217         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1218     Info.align.reset();
1219     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1220 
1221     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1222     if (!Vol || !Vol->isZero())
1223       Info.flags |= MachineMemOperand::MOVolatile;
1224 
1225     return true;
1226   }
1227   case Intrinsic::amdgcn_ds_append:
1228   case Intrinsic::amdgcn_ds_consume: {
1229     Info.opc = ISD::INTRINSIC_W_CHAIN;
1230     Info.memVT = MVT::getVT(CI.getType());
1231     Info.ptrVal = CI.getOperand(0);
1232     Info.align.reset();
1233     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1234 
1235     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1236     if (!Vol->isZero())
1237       Info.flags |= MachineMemOperand::MOVolatile;
1238 
1239     return true;
1240   }
1241   case Intrinsic::amdgcn_global_atomic_csub: {
1242     Info.opc = ISD::INTRINSIC_W_CHAIN;
1243     Info.memVT = MVT::getVT(CI.getType());
1244     Info.ptrVal = CI.getOperand(0);
1245     Info.align.reset();
1246     Info.flags = MachineMemOperand::MOLoad |
1247                  MachineMemOperand::MOStore |
1248                  MachineMemOperand::MOVolatile;
1249     return true;
1250   }
1251   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1252     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1253     Info.opc = ISD::INTRINSIC_W_CHAIN;
1254     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1255     Info.ptrVal =
1256         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1257     Info.align.reset();
1258     Info.flags = MachineMemOperand::MOLoad |
1259                  MachineMemOperand::MODereferenceable;
1260     return true;
1261   }
1262   case Intrinsic::amdgcn_global_atomic_fadd:
1263   case Intrinsic::amdgcn_global_atomic_fmin:
1264   case Intrinsic::amdgcn_global_atomic_fmax:
1265   case Intrinsic::amdgcn_flat_atomic_fadd:
1266   case Intrinsic::amdgcn_flat_atomic_fmin:
1267   case Intrinsic::amdgcn_flat_atomic_fmax: {
1268     Info.opc = ISD::INTRINSIC_W_CHAIN;
1269     Info.memVT = MVT::getVT(CI.getType());
1270     Info.ptrVal = CI.getOperand(0);
1271     Info.align.reset();
1272     Info.flags = MachineMemOperand::MOLoad |
1273                  MachineMemOperand::MOStore |
1274                  MachineMemOperand::MODereferenceable |
1275                  MachineMemOperand::MOVolatile;
1276     return true;
1277   }
1278   case Intrinsic::amdgcn_ds_gws_init:
1279   case Intrinsic::amdgcn_ds_gws_barrier:
1280   case Intrinsic::amdgcn_ds_gws_sema_v:
1281   case Intrinsic::amdgcn_ds_gws_sema_br:
1282   case Intrinsic::amdgcn_ds_gws_sema_p:
1283   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1284     Info.opc = ISD::INTRINSIC_VOID;
1285 
1286     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1287     Info.ptrVal =
1288         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1289 
1290     // This is an abstract access, but we need to specify a type and size.
1291     Info.memVT = MVT::i32;
1292     Info.size = 4;
1293     Info.align = Align(4);
1294 
1295     Info.flags = MachineMemOperand::MOStore;
1296     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1297       Info.flags = MachineMemOperand::MOLoad;
1298     return true;
1299   }
1300   default:
1301     return false;
1302   }
1303 }
1304 
1305 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1306                                             SmallVectorImpl<Value*> &Ops,
1307                                             Type *&AccessTy) const {
1308   switch (II->getIntrinsicID()) {
1309   case Intrinsic::amdgcn_atomic_inc:
1310   case Intrinsic::amdgcn_atomic_dec:
1311   case Intrinsic::amdgcn_ds_ordered_add:
1312   case Intrinsic::amdgcn_ds_ordered_swap:
1313   case Intrinsic::amdgcn_ds_append:
1314   case Intrinsic::amdgcn_ds_consume:
1315   case Intrinsic::amdgcn_ds_fadd:
1316   case Intrinsic::amdgcn_ds_fmin:
1317   case Intrinsic::amdgcn_ds_fmax:
1318   case Intrinsic::amdgcn_global_atomic_fadd:
1319   case Intrinsic::amdgcn_flat_atomic_fadd:
1320   case Intrinsic::amdgcn_flat_atomic_fmin:
1321   case Intrinsic::amdgcn_flat_atomic_fmax:
1322   case Intrinsic::amdgcn_global_atomic_csub: {
1323     Value *Ptr = II->getArgOperand(0);
1324     AccessTy = II->getType();
1325     Ops.push_back(Ptr);
1326     return true;
1327   }
1328   default:
1329     return false;
1330   }
1331 }
1332 
1333 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1334   if (!Subtarget->hasFlatInstOffsets()) {
1335     // Flat instructions do not have offsets, and only have the register
1336     // address.
1337     return AM.BaseOffs == 0 && AM.Scale == 0;
1338   }
1339 
1340   return AM.Scale == 0 &&
1341          (AM.BaseOffs == 0 ||
1342           Subtarget->getInstrInfo()->isLegalFLATOffset(
1343               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1344 }
1345 
1346 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1347   if (Subtarget->hasFlatGlobalInsts())
1348     return AM.Scale == 0 &&
1349            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1350                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1351                                     SIInstrFlags::FlatGlobal));
1352 
1353   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1354       // Assume the we will use FLAT for all global memory accesses
1355       // on VI.
1356       // FIXME: This assumption is currently wrong.  On VI we still use
1357       // MUBUF instructions for the r + i addressing mode.  As currently
1358       // implemented, the MUBUF instructions only work on buffer < 4GB.
1359       // It may be possible to support > 4GB buffers with MUBUF instructions,
1360       // by setting the stride value in the resource descriptor which would
1361       // increase the size limit to (stride * 4GB).  However, this is risky,
1362       // because it has never been validated.
1363     return isLegalFlatAddressingMode(AM);
1364   }
1365 
1366   return isLegalMUBUFAddressingMode(AM);
1367 }
1368 
1369 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1370   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1371   // additionally can do r + r + i with addr64. 32-bit has more addressing
1372   // mode options. Depending on the resource constant, it can also do
1373   // (i64 r0) + (i32 r1) * (i14 i).
1374   //
1375   // Private arrays end up using a scratch buffer most of the time, so also
1376   // assume those use MUBUF instructions. Scratch loads / stores are currently
1377   // implemented as mubuf instructions with offen bit set, so slightly
1378   // different than the normal addr64.
1379   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1380     return false;
1381 
1382   // FIXME: Since we can split immediate into soffset and immediate offset,
1383   // would it make sense to allow any immediate?
1384 
1385   switch (AM.Scale) {
1386   case 0: // r + i or just i, depending on HasBaseReg.
1387     return true;
1388   case 1:
1389     return true; // We have r + r or r + i.
1390   case 2:
1391     if (AM.HasBaseReg) {
1392       // Reject 2 * r + r.
1393       return false;
1394     }
1395 
1396     // Allow 2 * r as r + r
1397     // Or  2 * r + i is allowed as r + r + i.
1398     return true;
1399   default: // Don't allow n * r
1400     return false;
1401   }
1402 }
1403 
1404 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1405                                              const AddrMode &AM, Type *Ty,
1406                                              unsigned AS, Instruction *I) const {
1407   // No global is ever allowed as a base.
1408   if (AM.BaseGV)
1409     return false;
1410 
1411   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1412     return isLegalGlobalAddressingMode(AM);
1413 
1414   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1415       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1416       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1417     // If the offset isn't a multiple of 4, it probably isn't going to be
1418     // correctly aligned.
1419     // FIXME: Can we get the real alignment here?
1420     if (AM.BaseOffs % 4 != 0)
1421       return isLegalMUBUFAddressingMode(AM);
1422 
1423     // There are no SMRD extloads, so if we have to do a small type access we
1424     // will use a MUBUF load.
1425     // FIXME?: We also need to do this if unaligned, but we don't know the
1426     // alignment here.
1427     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1428       return isLegalGlobalAddressingMode(AM);
1429 
1430     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1431       // SMRD instructions have an 8-bit, dword offset on SI.
1432       if (!isUInt<8>(AM.BaseOffs / 4))
1433         return false;
1434     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1435       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1436       // in 8-bits, it can use a smaller encoding.
1437       if (!isUInt<32>(AM.BaseOffs / 4))
1438         return false;
1439     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1440       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1441       if (!isUInt<20>(AM.BaseOffs))
1442         return false;
1443     } else
1444       llvm_unreachable("unhandled generation");
1445 
1446     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1447       return true;
1448 
1449     if (AM.Scale == 1 && AM.HasBaseReg)
1450       return true;
1451 
1452     return false;
1453 
1454   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1455     return isLegalMUBUFAddressingMode(AM);
1456   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1457              AS == AMDGPUAS::REGION_ADDRESS) {
1458     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1459     // field.
1460     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1461     // an 8-bit dword offset but we don't know the alignment here.
1462     if (!isUInt<16>(AM.BaseOffs))
1463       return false;
1464 
1465     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1466       return true;
1467 
1468     if (AM.Scale == 1 && AM.HasBaseReg)
1469       return true;
1470 
1471     return false;
1472   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1473              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1474     // For an unknown address space, this usually means that this is for some
1475     // reason being used for pure arithmetic, and not based on some addressing
1476     // computation. We don't have instructions that compute pointers with any
1477     // addressing modes, so treat them as having no offset like flat
1478     // instructions.
1479     return isLegalFlatAddressingMode(AM);
1480   }
1481 
1482   // Assume a user alias of global for unknown address spaces.
1483   return isLegalGlobalAddressingMode(AM);
1484 }
1485 
1486 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1487                                         const MachineFunction &MF) const {
1488   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1489     return (MemVT.getSizeInBits() <= 4 * 32);
1490   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1491     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1492     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1493   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1494     return (MemVT.getSizeInBits() <= 2 * 32);
1495   }
1496   return true;
1497 }
1498 
1499 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1500     unsigned Size, unsigned AddrSpace, Align Alignment,
1501     MachineMemOperand::Flags Flags, bool *IsFast) const {
1502   if (IsFast)
1503     *IsFast = false;
1504 
1505   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1506       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1507     // Check if alignment requirements for ds_read/write instructions are
1508     // disabled.
1509     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1510         !Subtarget->hasLDSMisalignedBug()) {
1511       if (IsFast)
1512         *IsFast = Alignment != Align(2);
1513       return true;
1514     }
1515 
1516     // Either, the alignment requirements are "enabled", or there is an
1517     // unaligned LDS access related hardware bug though alignment requirements
1518     // are "disabled". In either case, we need to check for proper alignment
1519     // requirements.
1520     //
1521     if (Size == 64) {
1522       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1523       // can do a 4 byte aligned, 8 byte access in a single operation using
1524       // ds_read2/write2_b32 with adjacent offsets.
1525       bool AlignedBy4 = Alignment >= Align(4);
1526       if (IsFast)
1527         *IsFast = AlignedBy4;
1528 
1529       return AlignedBy4;
1530     }
1531     if (Size == 96) {
1532       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1533       // gfx8 and older.
1534       bool AlignedBy16 = Alignment >= Align(16);
1535       if (IsFast)
1536         *IsFast = AlignedBy16;
1537 
1538       return AlignedBy16;
1539     }
1540     if (Size == 128) {
1541       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1542       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1543       // single operation using ds_read2/write2_b64.
1544       bool AlignedBy8 = Alignment >= Align(8);
1545       if (IsFast)
1546         *IsFast = AlignedBy8;
1547 
1548       return AlignedBy8;
1549     }
1550   }
1551 
1552   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1553     bool AlignedBy4 = Alignment >= Align(4);
1554     if (IsFast)
1555       *IsFast = AlignedBy4;
1556 
1557     return AlignedBy4 ||
1558            Subtarget->enableFlatScratch() ||
1559            Subtarget->hasUnalignedScratchAccess();
1560   }
1561 
1562   // FIXME: We have to be conservative here and assume that flat operations
1563   // will access scratch.  If we had access to the IR function, then we
1564   // could determine if any private memory was used in the function.
1565   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1566       !Subtarget->hasUnalignedScratchAccess()) {
1567     bool AlignedBy4 = Alignment >= Align(4);
1568     if (IsFast)
1569       *IsFast = AlignedBy4;
1570 
1571     return AlignedBy4;
1572   }
1573 
1574   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1575       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1576         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1577     // If we have an uniform constant load, it still requires using a slow
1578     // buffer instruction if unaligned.
1579     if (IsFast) {
1580       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1581       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1582       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1583                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1584         Alignment >= Align(4) : Alignment != Align(2);
1585     }
1586 
1587     return true;
1588   }
1589 
1590   // Smaller than dword value must be aligned.
1591   if (Size < 32)
1592     return false;
1593 
1594   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1595   // byte-address are ignored, thus forcing Dword alignment.
1596   // This applies to private, global, and constant memory.
1597   if (IsFast)
1598     *IsFast = true;
1599 
1600   return Size >= 32 && Alignment >= Align(4);
1601 }
1602 
1603 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1604     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1605     bool *IsFast) const {
1606   if (IsFast)
1607     *IsFast = false;
1608 
1609   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1610   // which isn't a simple VT.
1611   // Until MVT is extended to handle this, simply check for the size and
1612   // rely on the condition below: allow accesses if the size is a multiple of 4.
1613   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1614                            VT.getStoreSize() > 16)) {
1615     return false;
1616   }
1617 
1618   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1619                                             Alignment, Flags, IsFast);
1620 }
1621 
1622 EVT SITargetLowering::getOptimalMemOpType(
1623     const MemOp &Op, const AttributeList &FuncAttributes) const {
1624   // FIXME: Should account for address space here.
1625 
1626   // The default fallback uses the private pointer size as a guess for a type to
1627   // use. Make sure we switch these to 64-bit accesses.
1628 
1629   if (Op.size() >= 16 &&
1630       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1631     return MVT::v4i32;
1632 
1633   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1634     return MVT::v2i32;
1635 
1636   // Use the default.
1637   return MVT::Other;
1638 }
1639 
1640 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1641   const MemSDNode *MemNode = cast<MemSDNode>(N);
1642   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1643 }
1644 
1645 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1646   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1647          AS == AMDGPUAS::PRIVATE_ADDRESS;
1648 }
1649 
1650 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1651                                            unsigned DestAS) const {
1652   // Flat -> private/local is a simple truncate.
1653   // Flat -> global is no-op
1654   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1655     return true;
1656 
1657   const GCNTargetMachine &TM =
1658       static_cast<const GCNTargetMachine &>(getTargetMachine());
1659   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1660 }
1661 
1662 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1663   const MemSDNode *MemNode = cast<MemSDNode>(N);
1664 
1665   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1666 }
1667 
1668 TargetLoweringBase::LegalizeTypeAction
1669 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1670   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1671       VT.getScalarType().bitsLE(MVT::i16))
1672     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1673   return TargetLoweringBase::getPreferredVectorAction(VT);
1674 }
1675 
1676 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1677                                                          Type *Ty) const {
1678   // FIXME: Could be smarter if called for vector constants.
1679   return true;
1680 }
1681 
1682 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1683   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1684     switch (Op) {
1685     case ISD::LOAD:
1686     case ISD::STORE:
1687 
1688     // These operations are done with 32-bit instructions anyway.
1689     case ISD::AND:
1690     case ISD::OR:
1691     case ISD::XOR:
1692     case ISD::SELECT:
1693       // TODO: Extensions?
1694       return true;
1695     default:
1696       return false;
1697     }
1698   }
1699 
1700   // SimplifySetCC uses this function to determine whether or not it should
1701   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1702   if (VT == MVT::i1 && Op == ISD::SETCC)
1703     return false;
1704 
1705   return TargetLowering::isTypeDesirableForOp(Op, VT);
1706 }
1707 
1708 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1709                                                    const SDLoc &SL,
1710                                                    SDValue Chain,
1711                                                    uint64_t Offset) const {
1712   const DataLayout &DL = DAG.getDataLayout();
1713   MachineFunction &MF = DAG.getMachineFunction();
1714   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1715 
1716   const ArgDescriptor *InputPtrReg;
1717   const TargetRegisterClass *RC;
1718   LLT ArgTy;
1719   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1720 
1721   std::tie(InputPtrReg, RC, ArgTy) =
1722       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1723 
1724   // We may not have the kernarg segment argument if we have no kernel
1725   // arguments.
1726   if (!InputPtrReg)
1727     return DAG.getConstant(0, SL, PtrVT);
1728 
1729   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1730   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1731     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1732 
1733   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1734 }
1735 
1736 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1737                                             const SDLoc &SL) const {
1738   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1739                                                FIRST_IMPLICIT);
1740   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1741 }
1742 
1743 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1744                                          const SDLoc &SL, SDValue Val,
1745                                          bool Signed,
1746                                          const ISD::InputArg *Arg) const {
1747   // First, if it is a widened vector, narrow it.
1748   if (VT.isVector() &&
1749       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1750     EVT NarrowedVT =
1751         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1752                          VT.getVectorNumElements());
1753     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1754                       DAG.getConstant(0, SL, MVT::i32));
1755   }
1756 
1757   // Then convert the vector elements or scalar value.
1758   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1759       VT.bitsLT(MemVT)) {
1760     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1761     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1762   }
1763 
1764   if (MemVT.isFloatingPoint())
1765     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1766   else if (Signed)
1767     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1768   else
1769     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1770 
1771   return Val;
1772 }
1773 
1774 SDValue SITargetLowering::lowerKernargMemParameter(
1775     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1776     uint64_t Offset, Align Alignment, bool Signed,
1777     const ISD::InputArg *Arg) const {
1778   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1779 
1780   // Try to avoid using an extload by loading earlier than the argument address,
1781   // and extracting the relevant bits. The load should hopefully be merged with
1782   // the previous argument.
1783   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1784     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1785     int64_t AlignDownOffset = alignDown(Offset, 4);
1786     int64_t OffsetDiff = Offset - AlignDownOffset;
1787 
1788     EVT IntVT = MemVT.changeTypeToInteger();
1789 
1790     // TODO: If we passed in the base kernel offset we could have a better
1791     // alignment than 4, but we don't really need it.
1792     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1793     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1794                                MachineMemOperand::MODereferenceable |
1795                                    MachineMemOperand::MOInvariant);
1796 
1797     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1798     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1799 
1800     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1801     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1802     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1803 
1804 
1805     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1806   }
1807 
1808   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1809   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1810                              MachineMemOperand::MODereferenceable |
1811                                  MachineMemOperand::MOInvariant);
1812 
1813   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1814   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1815 }
1816 
1817 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1818                                               const SDLoc &SL, SDValue Chain,
1819                                               const ISD::InputArg &Arg) const {
1820   MachineFunction &MF = DAG.getMachineFunction();
1821   MachineFrameInfo &MFI = MF.getFrameInfo();
1822 
1823   if (Arg.Flags.isByVal()) {
1824     unsigned Size = Arg.Flags.getByValSize();
1825     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1826     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1827   }
1828 
1829   unsigned ArgOffset = VA.getLocMemOffset();
1830   unsigned ArgSize = VA.getValVT().getStoreSize();
1831 
1832   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1833 
1834   // Create load nodes to retrieve arguments from the stack.
1835   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1836   SDValue ArgValue;
1837 
1838   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1839   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1840   MVT MemVT = VA.getValVT();
1841 
1842   switch (VA.getLocInfo()) {
1843   default:
1844     break;
1845   case CCValAssign::BCvt:
1846     MemVT = VA.getLocVT();
1847     break;
1848   case CCValAssign::SExt:
1849     ExtType = ISD::SEXTLOAD;
1850     break;
1851   case CCValAssign::ZExt:
1852     ExtType = ISD::ZEXTLOAD;
1853     break;
1854   case CCValAssign::AExt:
1855     ExtType = ISD::EXTLOAD;
1856     break;
1857   }
1858 
1859   ArgValue = DAG.getExtLoad(
1860     ExtType, SL, VA.getLocVT(), Chain, FIN,
1861     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1862     MemVT);
1863   return ArgValue;
1864 }
1865 
1866 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1867   const SIMachineFunctionInfo &MFI,
1868   EVT VT,
1869   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1870   const ArgDescriptor *Reg;
1871   const TargetRegisterClass *RC;
1872   LLT Ty;
1873 
1874   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1875   if (!Reg) {
1876     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1877       // It's possible for a kernarg intrinsic call to appear in a kernel with
1878       // no allocated segment, in which case we do not add the user sgpr
1879       // argument, so just return null.
1880       return DAG.getConstant(0, SDLoc(), VT);
1881     }
1882 
1883     // It's undefined behavior if a function marked with the amdgpu-no-*
1884     // attributes uses the corresponding intrinsic.
1885     return DAG.getUNDEF(VT);
1886   }
1887 
1888   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1889 }
1890 
1891 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1892                                CallingConv::ID CallConv,
1893                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1894                                FunctionType *FType,
1895                                SIMachineFunctionInfo *Info) {
1896   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1897     const ISD::InputArg *Arg = &Ins[I];
1898 
1899     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1900            "vector type argument should have been split");
1901 
1902     // First check if it's a PS input addr.
1903     if (CallConv == CallingConv::AMDGPU_PS &&
1904         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1905       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1906 
1907       // Inconveniently only the first part of the split is marked as isSplit,
1908       // so skip to the end. We only want to increment PSInputNum once for the
1909       // entire split argument.
1910       if (Arg->Flags.isSplit()) {
1911         while (!Arg->Flags.isSplitEnd()) {
1912           assert((!Arg->VT.isVector() ||
1913                   Arg->VT.getScalarSizeInBits() == 16) &&
1914                  "unexpected vector split in ps argument type");
1915           if (!SkipArg)
1916             Splits.push_back(*Arg);
1917           Arg = &Ins[++I];
1918         }
1919       }
1920 
1921       if (SkipArg) {
1922         // We can safely skip PS inputs.
1923         Skipped.set(Arg->getOrigArgIndex());
1924         ++PSInputNum;
1925         continue;
1926       }
1927 
1928       Info->markPSInputAllocated(PSInputNum);
1929       if (Arg->Used)
1930         Info->markPSInputEnabled(PSInputNum);
1931 
1932       ++PSInputNum;
1933     }
1934 
1935     Splits.push_back(*Arg);
1936   }
1937 }
1938 
1939 // Allocate special inputs passed in VGPRs.
1940 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1941                                                       MachineFunction &MF,
1942                                                       const SIRegisterInfo &TRI,
1943                                                       SIMachineFunctionInfo &Info) const {
1944   const LLT S32 = LLT::scalar(32);
1945   MachineRegisterInfo &MRI = MF.getRegInfo();
1946 
1947   if (Info.hasWorkItemIDX()) {
1948     Register Reg = AMDGPU::VGPR0;
1949     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1950 
1951     CCInfo.AllocateReg(Reg);
1952     unsigned Mask = (Subtarget->hasPackedTID() &&
1953                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1954     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1955   }
1956 
1957   if (Info.hasWorkItemIDY()) {
1958     assert(Info.hasWorkItemIDX());
1959     if (Subtarget->hasPackedTID()) {
1960       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1961                                                         0x3ff << 10));
1962     } else {
1963       unsigned Reg = AMDGPU::VGPR1;
1964       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1965 
1966       CCInfo.AllocateReg(Reg);
1967       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1968     }
1969   }
1970 
1971   if (Info.hasWorkItemIDZ()) {
1972     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1973     if (Subtarget->hasPackedTID()) {
1974       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1975                                                         0x3ff << 20));
1976     } else {
1977       unsigned Reg = AMDGPU::VGPR2;
1978       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1979 
1980       CCInfo.AllocateReg(Reg);
1981       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1982     }
1983   }
1984 }
1985 
1986 // Try to allocate a VGPR at the end of the argument list, or if no argument
1987 // VGPRs are left allocating a stack slot.
1988 // If \p Mask is is given it indicates bitfield position in the register.
1989 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1990 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1991                                          ArgDescriptor Arg = ArgDescriptor()) {
1992   if (Arg.isSet())
1993     return ArgDescriptor::createArg(Arg, Mask);
1994 
1995   ArrayRef<MCPhysReg> ArgVGPRs
1996     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1997   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1998   if (RegIdx == ArgVGPRs.size()) {
1999     // Spill to stack required.
2000     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2001 
2002     return ArgDescriptor::createStack(Offset, Mask);
2003   }
2004 
2005   unsigned Reg = ArgVGPRs[RegIdx];
2006   Reg = CCInfo.AllocateReg(Reg);
2007   assert(Reg != AMDGPU::NoRegister);
2008 
2009   MachineFunction &MF = CCInfo.getMachineFunction();
2010   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2011   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2012   return ArgDescriptor::createRegister(Reg, Mask);
2013 }
2014 
2015 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2016                                              const TargetRegisterClass *RC,
2017                                              unsigned NumArgRegs) {
2018   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2019   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2020   if (RegIdx == ArgSGPRs.size())
2021     report_fatal_error("ran out of SGPRs for arguments");
2022 
2023   unsigned Reg = ArgSGPRs[RegIdx];
2024   Reg = CCInfo.AllocateReg(Reg);
2025   assert(Reg != AMDGPU::NoRegister);
2026 
2027   MachineFunction &MF = CCInfo.getMachineFunction();
2028   MF.addLiveIn(Reg, RC);
2029   return ArgDescriptor::createRegister(Reg);
2030 }
2031 
2032 // If this has a fixed position, we still should allocate the register in the
2033 // CCInfo state. Technically we could get away with this for values passed
2034 // outside of the normal argument range.
2035 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2036                                        const TargetRegisterClass *RC,
2037                                        MCRegister Reg) {
2038   Reg = CCInfo.AllocateReg(Reg);
2039   assert(Reg != AMDGPU::NoRegister);
2040   MachineFunction &MF = CCInfo.getMachineFunction();
2041   MF.addLiveIn(Reg, RC);
2042 }
2043 
2044 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2045   if (Arg) {
2046     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2047                                Arg.getRegister());
2048   } else
2049     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2050 }
2051 
2052 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2053   if (Arg) {
2054     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2055                                Arg.getRegister());
2056   } else
2057     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2058 }
2059 
2060 /// Allocate implicit function VGPR arguments at the end of allocated user
2061 /// arguments.
2062 void SITargetLowering::allocateSpecialInputVGPRs(
2063   CCState &CCInfo, MachineFunction &MF,
2064   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2065   const unsigned Mask = 0x3ff;
2066   ArgDescriptor Arg;
2067 
2068   if (Info.hasWorkItemIDX()) {
2069     Arg = allocateVGPR32Input(CCInfo, Mask);
2070     Info.setWorkItemIDX(Arg);
2071   }
2072 
2073   if (Info.hasWorkItemIDY()) {
2074     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2075     Info.setWorkItemIDY(Arg);
2076   }
2077 
2078   if (Info.hasWorkItemIDZ())
2079     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2080 }
2081 
2082 /// Allocate implicit function VGPR arguments in fixed registers.
2083 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2084   CCState &CCInfo, MachineFunction &MF,
2085   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2086   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2087   if (!Reg)
2088     report_fatal_error("failed to allocated VGPR for implicit arguments");
2089 
2090   const unsigned Mask = 0x3ff;
2091   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2092   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2093   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2094 }
2095 
2096 void SITargetLowering::allocateSpecialInputSGPRs(
2097   CCState &CCInfo,
2098   MachineFunction &MF,
2099   const SIRegisterInfo &TRI,
2100   SIMachineFunctionInfo &Info) const {
2101   auto &ArgInfo = Info.getArgInfo();
2102 
2103   // TODO: Unify handling with private memory pointers.
2104   if (Info.hasDispatchPtr())
2105     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2106 
2107   if (Info.hasQueuePtr())
2108     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2109 
2110   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2111   // constant offset from the kernarg segment.
2112   if (Info.hasImplicitArgPtr())
2113     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2114 
2115   if (Info.hasDispatchID())
2116     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2117 
2118   // flat_scratch_init is not applicable for non-kernel functions.
2119 
2120   if (Info.hasWorkGroupIDX())
2121     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2122 
2123   if (Info.hasWorkGroupIDY())
2124     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2125 
2126   if (Info.hasWorkGroupIDZ())
2127     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2128 }
2129 
2130 // Allocate special inputs passed in user SGPRs.
2131 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2132                                             MachineFunction &MF,
2133                                             const SIRegisterInfo &TRI,
2134                                             SIMachineFunctionInfo &Info) const {
2135   if (Info.hasImplicitBufferPtr()) {
2136     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2137     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2138     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2139   }
2140 
2141   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2142   if (Info.hasPrivateSegmentBuffer()) {
2143     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2144     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2145     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2146   }
2147 
2148   if (Info.hasDispatchPtr()) {
2149     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2150     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2151     CCInfo.AllocateReg(DispatchPtrReg);
2152   }
2153 
2154   if (Info.hasQueuePtr()) {
2155     Register QueuePtrReg = Info.addQueuePtr(TRI);
2156     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2157     CCInfo.AllocateReg(QueuePtrReg);
2158   }
2159 
2160   if (Info.hasKernargSegmentPtr()) {
2161     MachineRegisterInfo &MRI = MF.getRegInfo();
2162     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2163     CCInfo.AllocateReg(InputPtrReg);
2164 
2165     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2166     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2167   }
2168 
2169   if (Info.hasDispatchID()) {
2170     Register DispatchIDReg = Info.addDispatchID(TRI);
2171     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2172     CCInfo.AllocateReg(DispatchIDReg);
2173   }
2174 
2175   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2176     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2177     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2178     CCInfo.AllocateReg(FlatScratchInitReg);
2179   }
2180 
2181   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2182   // these from the dispatch pointer.
2183 }
2184 
2185 // Allocate special input registers that are initialized per-wave.
2186 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2187                                            MachineFunction &MF,
2188                                            SIMachineFunctionInfo &Info,
2189                                            CallingConv::ID CallConv,
2190                                            bool IsShader) const {
2191   if (Info.hasWorkGroupIDX()) {
2192     Register Reg = Info.addWorkGroupIDX();
2193     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2194     CCInfo.AllocateReg(Reg);
2195   }
2196 
2197   if (Info.hasWorkGroupIDY()) {
2198     Register Reg = Info.addWorkGroupIDY();
2199     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2200     CCInfo.AllocateReg(Reg);
2201   }
2202 
2203   if (Info.hasWorkGroupIDZ()) {
2204     Register Reg = Info.addWorkGroupIDZ();
2205     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2206     CCInfo.AllocateReg(Reg);
2207   }
2208 
2209   if (Info.hasWorkGroupInfo()) {
2210     Register Reg = Info.addWorkGroupInfo();
2211     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2212     CCInfo.AllocateReg(Reg);
2213   }
2214 
2215   if (Info.hasPrivateSegmentWaveByteOffset()) {
2216     // Scratch wave offset passed in system SGPR.
2217     unsigned PrivateSegmentWaveByteOffsetReg;
2218 
2219     if (IsShader) {
2220       PrivateSegmentWaveByteOffsetReg =
2221         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2222 
2223       // This is true if the scratch wave byte offset doesn't have a fixed
2224       // location.
2225       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2226         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2227         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2228       }
2229     } else
2230       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2231 
2232     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2233     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2234   }
2235 }
2236 
2237 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2238                                      MachineFunction &MF,
2239                                      const SIRegisterInfo &TRI,
2240                                      SIMachineFunctionInfo &Info) {
2241   // Now that we've figured out where the scratch register inputs are, see if
2242   // should reserve the arguments and use them directly.
2243   MachineFrameInfo &MFI = MF.getFrameInfo();
2244   bool HasStackObjects = MFI.hasStackObjects();
2245   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2246 
2247   // Record that we know we have non-spill stack objects so we don't need to
2248   // check all stack objects later.
2249   if (HasStackObjects)
2250     Info.setHasNonSpillStackObjects(true);
2251 
2252   // Everything live out of a block is spilled with fast regalloc, so it's
2253   // almost certain that spilling will be required.
2254   if (TM.getOptLevel() == CodeGenOpt::None)
2255     HasStackObjects = true;
2256 
2257   // For now assume stack access is needed in any callee functions, so we need
2258   // the scratch registers to pass in.
2259   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2260 
2261   if (!ST.enableFlatScratch()) {
2262     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2263       // If we have stack objects, we unquestionably need the private buffer
2264       // resource. For the Code Object V2 ABI, this will be the first 4 user
2265       // SGPR inputs. We can reserve those and use them directly.
2266 
2267       Register PrivateSegmentBufferReg =
2268           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2269       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2270     } else {
2271       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2272       // We tentatively reserve the last registers (skipping the last registers
2273       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2274       // we'll replace these with the ones immediately after those which were
2275       // really allocated. In the prologue copies will be inserted from the
2276       // argument to these reserved registers.
2277 
2278       // Without HSA, relocations are used for the scratch pointer and the
2279       // buffer resource setup is always inserted in the prologue. Scratch wave
2280       // offset is still in an input SGPR.
2281       Info.setScratchRSrcReg(ReservedBufferReg);
2282     }
2283   }
2284 
2285   MachineRegisterInfo &MRI = MF.getRegInfo();
2286 
2287   // For entry functions we have to set up the stack pointer if we use it,
2288   // whereas non-entry functions get this "for free". This means there is no
2289   // intrinsic advantage to using S32 over S34 in cases where we do not have
2290   // calls but do need a frame pointer (i.e. if we are requested to have one
2291   // because frame pointer elimination is disabled). To keep things simple we
2292   // only ever use S32 as the call ABI stack pointer, and so using it does not
2293   // imply we need a separate frame pointer.
2294   //
2295   // Try to use s32 as the SP, but move it if it would interfere with input
2296   // arguments. This won't work with calls though.
2297   //
2298   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2299   // registers.
2300   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2301     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2302   } else {
2303     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2304 
2305     if (MFI.hasCalls())
2306       report_fatal_error("call in graphics shader with too many input SGPRs");
2307 
2308     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2309       if (!MRI.isLiveIn(Reg)) {
2310         Info.setStackPtrOffsetReg(Reg);
2311         break;
2312       }
2313     }
2314 
2315     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2316       report_fatal_error("failed to find register for SP");
2317   }
2318 
2319   // hasFP should be accurate for entry functions even before the frame is
2320   // finalized, because it does not rely on the known stack size, only
2321   // properties like whether variable sized objects are present.
2322   if (ST.getFrameLowering()->hasFP(MF)) {
2323     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2324   }
2325 }
2326 
2327 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2328   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2329   return !Info->isEntryFunction();
2330 }
2331 
2332 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2333 
2334 }
2335 
2336 void SITargetLowering::insertCopiesSplitCSR(
2337   MachineBasicBlock *Entry,
2338   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2339   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2340 
2341   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2342   if (!IStart)
2343     return;
2344 
2345   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2346   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2347   MachineBasicBlock::iterator MBBI = Entry->begin();
2348   for (const MCPhysReg *I = IStart; *I; ++I) {
2349     const TargetRegisterClass *RC = nullptr;
2350     if (AMDGPU::SReg_64RegClass.contains(*I))
2351       RC = &AMDGPU::SGPR_64RegClass;
2352     else if (AMDGPU::SReg_32RegClass.contains(*I))
2353       RC = &AMDGPU::SGPR_32RegClass;
2354     else
2355       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2356 
2357     Register NewVR = MRI->createVirtualRegister(RC);
2358     // Create copy from CSR to a virtual register.
2359     Entry->addLiveIn(*I);
2360     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2361       .addReg(*I);
2362 
2363     // Insert the copy-back instructions right before the terminator.
2364     for (auto *Exit : Exits)
2365       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2366               TII->get(TargetOpcode::COPY), *I)
2367         .addReg(NewVR);
2368   }
2369 }
2370 
2371 SDValue SITargetLowering::LowerFormalArguments(
2372     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2373     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2374     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2375   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2376 
2377   MachineFunction &MF = DAG.getMachineFunction();
2378   const Function &Fn = MF.getFunction();
2379   FunctionType *FType = MF.getFunction().getFunctionType();
2380   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2381 
2382   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2383     DiagnosticInfoUnsupported NoGraphicsHSA(
2384         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2385     DAG.getContext()->diagnose(NoGraphicsHSA);
2386     return DAG.getEntryNode();
2387   }
2388 
2389   Info->allocateModuleLDSGlobal(Fn.getParent());
2390 
2391   SmallVector<ISD::InputArg, 16> Splits;
2392   SmallVector<CCValAssign, 16> ArgLocs;
2393   BitVector Skipped(Ins.size());
2394   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2395                  *DAG.getContext());
2396 
2397   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2398   bool IsKernel = AMDGPU::isKernel(CallConv);
2399   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2400 
2401   if (IsGraphics) {
2402     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2403            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2404            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2405            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2406            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2407            !Info->hasWorkItemIDZ());
2408   }
2409 
2410   if (CallConv == CallingConv::AMDGPU_PS) {
2411     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2412 
2413     // At least one interpolation mode must be enabled or else the GPU will
2414     // hang.
2415     //
2416     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2417     // set PSInputAddr, the user wants to enable some bits after the compilation
2418     // based on run-time states. Since we can't know what the final PSInputEna
2419     // will look like, so we shouldn't do anything here and the user should take
2420     // responsibility for the correct programming.
2421     //
2422     // Otherwise, the following restrictions apply:
2423     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2424     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2425     //   enabled too.
2426     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2427         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2428       CCInfo.AllocateReg(AMDGPU::VGPR0);
2429       CCInfo.AllocateReg(AMDGPU::VGPR1);
2430       Info->markPSInputAllocated(0);
2431       Info->markPSInputEnabled(0);
2432     }
2433     if (Subtarget->isAmdPalOS()) {
2434       // For isAmdPalOS, the user does not enable some bits after compilation
2435       // based on run-time states; the register values being generated here are
2436       // the final ones set in hardware. Therefore we need to apply the
2437       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2438       // a bit is set in PSInputAddr but not PSInputEnable is where the
2439       // frontend set up an input arg for a particular interpolation mode, but
2440       // nothing uses that input arg. Really we should have an earlier pass
2441       // that removes such an arg.)
2442       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2443       if ((PsInputBits & 0x7F) == 0 ||
2444           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2445         Info->markPSInputEnabled(
2446             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2447     }
2448   } else if (IsKernel) {
2449     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2450   } else {
2451     Splits.append(Ins.begin(), Ins.end());
2452   }
2453 
2454   if (IsEntryFunc) {
2455     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2456     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2457   } else if (!IsGraphics) {
2458     // For the fixed ABI, pass workitem IDs in the last argument register.
2459     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2460   }
2461 
2462   if (IsKernel) {
2463     analyzeFormalArgumentsCompute(CCInfo, Ins);
2464   } else {
2465     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2466     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2467   }
2468 
2469   SmallVector<SDValue, 16> Chains;
2470 
2471   // FIXME: This is the minimum kernel argument alignment. We should improve
2472   // this to the maximum alignment of the arguments.
2473   //
2474   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2475   // kern arg offset.
2476   const Align KernelArgBaseAlign = Align(16);
2477 
2478   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2479     const ISD::InputArg &Arg = Ins[i];
2480     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2481       InVals.push_back(DAG.getUNDEF(Arg.VT));
2482       continue;
2483     }
2484 
2485     CCValAssign &VA = ArgLocs[ArgIdx++];
2486     MVT VT = VA.getLocVT();
2487 
2488     if (IsEntryFunc && VA.isMemLoc()) {
2489       VT = Ins[i].VT;
2490       EVT MemVT = VA.getLocVT();
2491 
2492       const uint64_t Offset = VA.getLocMemOffset();
2493       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2494 
2495       if (Arg.Flags.isByRef()) {
2496         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2497 
2498         const GCNTargetMachine &TM =
2499             static_cast<const GCNTargetMachine &>(getTargetMachine());
2500         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2501                                     Arg.Flags.getPointerAddrSpace())) {
2502           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2503                                      Arg.Flags.getPointerAddrSpace());
2504         }
2505 
2506         InVals.push_back(Ptr);
2507         continue;
2508       }
2509 
2510       SDValue Arg = lowerKernargMemParameter(
2511         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2512       Chains.push_back(Arg.getValue(1));
2513 
2514       auto *ParamTy =
2515         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2516       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2517           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2518                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2519         // On SI local pointers are just offsets into LDS, so they are always
2520         // less than 16-bits.  On CI and newer they could potentially be
2521         // real pointers, so we can't guarantee their size.
2522         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2523                           DAG.getValueType(MVT::i16));
2524       }
2525 
2526       InVals.push_back(Arg);
2527       continue;
2528     } else if (!IsEntryFunc && VA.isMemLoc()) {
2529       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2530       InVals.push_back(Val);
2531       if (!Arg.Flags.isByVal())
2532         Chains.push_back(Val.getValue(1));
2533       continue;
2534     }
2535 
2536     assert(VA.isRegLoc() && "Parameter must be in a register!");
2537 
2538     Register Reg = VA.getLocReg();
2539     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2540     EVT ValVT = VA.getValVT();
2541 
2542     Reg = MF.addLiveIn(Reg, RC);
2543     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2544 
2545     if (Arg.Flags.isSRet()) {
2546       // The return object should be reasonably addressable.
2547 
2548       // FIXME: This helps when the return is a real sret. If it is a
2549       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2550       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2551       unsigned NumBits
2552         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2553       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2554         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2555     }
2556 
2557     // If this is an 8 or 16-bit value, it is really passed promoted
2558     // to 32 bits. Insert an assert[sz]ext to capture this, then
2559     // truncate to the right size.
2560     switch (VA.getLocInfo()) {
2561     case CCValAssign::Full:
2562       break;
2563     case CCValAssign::BCvt:
2564       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2565       break;
2566     case CCValAssign::SExt:
2567       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2568                         DAG.getValueType(ValVT));
2569       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2570       break;
2571     case CCValAssign::ZExt:
2572       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2573                         DAG.getValueType(ValVT));
2574       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2575       break;
2576     case CCValAssign::AExt:
2577       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2578       break;
2579     default:
2580       llvm_unreachable("Unknown loc info!");
2581     }
2582 
2583     InVals.push_back(Val);
2584   }
2585 
2586   // Start adding system SGPRs.
2587   if (IsEntryFunc) {
2588     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2589   } else {
2590     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2591     if (!IsGraphics)
2592       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2593   }
2594 
2595   auto &ArgUsageInfo =
2596     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2597   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2598 
2599   unsigned StackArgSize = CCInfo.getNextStackOffset();
2600   Info->setBytesInStackArgArea(StackArgSize);
2601 
2602   return Chains.empty() ? Chain :
2603     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2604 }
2605 
2606 // TODO: If return values can't fit in registers, we should return as many as
2607 // possible in registers before passing on stack.
2608 bool SITargetLowering::CanLowerReturn(
2609   CallingConv::ID CallConv,
2610   MachineFunction &MF, bool IsVarArg,
2611   const SmallVectorImpl<ISD::OutputArg> &Outs,
2612   LLVMContext &Context) const {
2613   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2614   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2615   // for shaders. Vector types should be explicitly handled by CC.
2616   if (AMDGPU::isEntryFunctionCC(CallConv))
2617     return true;
2618 
2619   SmallVector<CCValAssign, 16> RVLocs;
2620   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2621   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2622 }
2623 
2624 SDValue
2625 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2626                               bool isVarArg,
2627                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2628                               const SmallVectorImpl<SDValue> &OutVals,
2629                               const SDLoc &DL, SelectionDAG &DAG) const {
2630   MachineFunction &MF = DAG.getMachineFunction();
2631   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2632 
2633   if (AMDGPU::isKernel(CallConv)) {
2634     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2635                                              OutVals, DL, DAG);
2636   }
2637 
2638   bool IsShader = AMDGPU::isShader(CallConv);
2639 
2640   Info->setIfReturnsVoid(Outs.empty());
2641   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2642 
2643   // CCValAssign - represent the assignment of the return value to a location.
2644   SmallVector<CCValAssign, 48> RVLocs;
2645   SmallVector<ISD::OutputArg, 48> Splits;
2646 
2647   // CCState - Info about the registers and stack slots.
2648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2649                  *DAG.getContext());
2650 
2651   // Analyze outgoing return values.
2652   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2653 
2654   SDValue Flag;
2655   SmallVector<SDValue, 48> RetOps;
2656   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2657 
2658   // Add return address for callable functions.
2659   if (!Info->isEntryFunction()) {
2660     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2661     SDValue ReturnAddrReg = CreateLiveInRegister(
2662       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2663 
2664     SDValue ReturnAddrVirtualReg =
2665         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2666                             CallConv != CallingConv::AMDGPU_Gfx
2667                                 ? &AMDGPU::CCR_SGPR_64RegClass
2668                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2669                         MVT::i64);
2670     Chain =
2671         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2672     Flag = Chain.getValue(1);
2673     RetOps.push_back(ReturnAddrVirtualReg);
2674   }
2675 
2676   // Copy the result values into the output registers.
2677   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2678        ++I, ++RealRVLocIdx) {
2679     CCValAssign &VA = RVLocs[I];
2680     assert(VA.isRegLoc() && "Can only return in registers!");
2681     // TODO: Partially return in registers if return values don't fit.
2682     SDValue Arg = OutVals[RealRVLocIdx];
2683 
2684     // Copied from other backends.
2685     switch (VA.getLocInfo()) {
2686     case CCValAssign::Full:
2687       break;
2688     case CCValAssign::BCvt:
2689       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2690       break;
2691     case CCValAssign::SExt:
2692       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2693       break;
2694     case CCValAssign::ZExt:
2695       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2696       break;
2697     case CCValAssign::AExt:
2698       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2699       break;
2700     default:
2701       llvm_unreachable("Unknown loc info!");
2702     }
2703 
2704     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2705     Flag = Chain.getValue(1);
2706     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2707   }
2708 
2709   // FIXME: Does sret work properly?
2710   if (!Info->isEntryFunction()) {
2711     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2712     const MCPhysReg *I =
2713       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2714     if (I) {
2715       for (; *I; ++I) {
2716         if (AMDGPU::SReg_64RegClass.contains(*I))
2717           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2718         else if (AMDGPU::SReg_32RegClass.contains(*I))
2719           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2720         else
2721           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2722       }
2723     }
2724   }
2725 
2726   // Update chain and glue.
2727   RetOps[0] = Chain;
2728   if (Flag.getNode())
2729     RetOps.push_back(Flag);
2730 
2731   unsigned Opc = AMDGPUISD::ENDPGM;
2732   if (!IsWaveEnd) {
2733     if (IsShader)
2734       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2735     else if (CallConv == CallingConv::AMDGPU_Gfx)
2736       Opc = AMDGPUISD::RET_GFX_FLAG;
2737     else
2738       Opc = AMDGPUISD::RET_FLAG;
2739   }
2740 
2741   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2742 }
2743 
2744 SDValue SITargetLowering::LowerCallResult(
2745     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2746     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2747     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2748     SDValue ThisVal) const {
2749   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2750 
2751   // Assign locations to each value returned by this call.
2752   SmallVector<CCValAssign, 16> RVLocs;
2753   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2754                  *DAG.getContext());
2755   CCInfo.AnalyzeCallResult(Ins, RetCC);
2756 
2757   // Copy all of the result registers out of their specified physreg.
2758   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2759     CCValAssign VA = RVLocs[i];
2760     SDValue Val;
2761 
2762     if (VA.isRegLoc()) {
2763       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2764       Chain = Val.getValue(1);
2765       InFlag = Val.getValue(2);
2766     } else if (VA.isMemLoc()) {
2767       report_fatal_error("TODO: return values in memory");
2768     } else
2769       llvm_unreachable("unknown argument location type");
2770 
2771     switch (VA.getLocInfo()) {
2772     case CCValAssign::Full:
2773       break;
2774     case CCValAssign::BCvt:
2775       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2776       break;
2777     case CCValAssign::ZExt:
2778       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2779                         DAG.getValueType(VA.getValVT()));
2780       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2781       break;
2782     case CCValAssign::SExt:
2783       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2784                         DAG.getValueType(VA.getValVT()));
2785       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2786       break;
2787     case CCValAssign::AExt:
2788       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2789       break;
2790     default:
2791       llvm_unreachable("Unknown loc info!");
2792     }
2793 
2794     InVals.push_back(Val);
2795   }
2796 
2797   return Chain;
2798 }
2799 
2800 // Add code to pass special inputs required depending on used features separate
2801 // from the explicit user arguments present in the IR.
2802 void SITargetLowering::passSpecialInputs(
2803     CallLoweringInfo &CLI,
2804     CCState &CCInfo,
2805     const SIMachineFunctionInfo &Info,
2806     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2807     SmallVectorImpl<SDValue> &MemOpChains,
2808     SDValue Chain) const {
2809   // If we don't have a call site, this was a call inserted by
2810   // legalization. These can never use special inputs.
2811   if (!CLI.CB)
2812     return;
2813 
2814   SelectionDAG &DAG = CLI.DAG;
2815   const SDLoc &DL = CLI.DL;
2816   const Function &F = DAG.getMachineFunction().getFunction();
2817 
2818   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2819   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2820 
2821   const AMDGPUFunctionArgInfo *CalleeArgInfo
2822     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2823   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2824     auto &ArgUsageInfo =
2825       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2826     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2827   }
2828 
2829   // TODO: Unify with private memory register handling. This is complicated by
2830   // the fact that at least in kernels, the input argument is not necessarily
2831   // in the same location as the input.
2832   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2833                              StringLiteral> ImplicitAttrs[] = {
2834     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2835     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2836     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2837     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2838     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2839     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2840     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2841   };
2842 
2843   for (auto Attr : ImplicitAttrs) {
2844     const ArgDescriptor *OutgoingArg;
2845     const TargetRegisterClass *ArgRC;
2846     LLT ArgTy;
2847 
2848     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2849 
2850     // If the callee does not use the attribute value, skip copying the value.
2851     if (CLI.CB->hasFnAttr(Attr.second))
2852       continue;
2853 
2854     std::tie(OutgoingArg, ArgRC, ArgTy) =
2855         CalleeArgInfo->getPreloadedValue(InputID);
2856     if (!OutgoingArg)
2857       continue;
2858 
2859     const ArgDescriptor *IncomingArg;
2860     const TargetRegisterClass *IncomingArgRC;
2861     LLT Ty;
2862     std::tie(IncomingArg, IncomingArgRC, Ty) =
2863         CallerArgInfo.getPreloadedValue(InputID);
2864     assert(IncomingArgRC == ArgRC);
2865 
2866     // All special arguments are ints for now.
2867     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2868     SDValue InputReg;
2869 
2870     if (IncomingArg) {
2871       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2872     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2873       // The implicit arg ptr is special because it doesn't have a corresponding
2874       // input for kernels, and is computed from the kernarg segment pointer.
2875       InputReg = getImplicitArgPtr(DAG, DL);
2876     } else {
2877       // We may have proven the input wasn't needed, although the ABI is
2878       // requiring it. We just need to allocate the register appropriately.
2879       InputReg = DAG.getUNDEF(ArgVT);
2880     }
2881 
2882     if (OutgoingArg->isRegister()) {
2883       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2884       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2885         report_fatal_error("failed to allocate implicit input argument");
2886     } else {
2887       unsigned SpecialArgOffset =
2888           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2889       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2890                                               SpecialArgOffset);
2891       MemOpChains.push_back(ArgStore);
2892     }
2893   }
2894 
2895   // Pack workitem IDs into a single register or pass it as is if already
2896   // packed.
2897   const ArgDescriptor *OutgoingArg;
2898   const TargetRegisterClass *ArgRC;
2899   LLT Ty;
2900 
2901   std::tie(OutgoingArg, ArgRC, Ty) =
2902       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2903   if (!OutgoingArg)
2904     std::tie(OutgoingArg, ArgRC, Ty) =
2905         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2906   if (!OutgoingArg)
2907     std::tie(OutgoingArg, ArgRC, Ty) =
2908         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2909   if (!OutgoingArg)
2910     return;
2911 
2912   const ArgDescriptor *IncomingArgX = std::get<0>(
2913       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2914   const ArgDescriptor *IncomingArgY = std::get<0>(
2915       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2916   const ArgDescriptor *IncomingArgZ = std::get<0>(
2917       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2918 
2919   SDValue InputReg;
2920   SDLoc SL;
2921 
2922   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2923   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2924   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2925 
2926   // If incoming ids are not packed we need to pack them.
2927   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2928       NeedWorkItemIDX) {
2929     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2930       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2931     } else {
2932       InputReg = DAG.getConstant(0, DL, MVT::i32);
2933     }
2934   }
2935 
2936   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2937       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2938     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2939     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2940                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2941     InputReg = InputReg.getNode() ?
2942                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2943   }
2944 
2945   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2946       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2947     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2948     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2949                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2950     InputReg = InputReg.getNode() ?
2951                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2952   }
2953 
2954   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2955     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2956       // We're in a situation where the outgoing function requires the workitem
2957       // ID, but the calling function does not have it (e.g a graphics function
2958       // calling a C calling convention function). This is illegal, but we need
2959       // to produce something.
2960       InputReg = DAG.getUNDEF(MVT::i32);
2961     } else {
2962       // Workitem ids are already packed, any of present incoming arguments
2963       // will carry all required fields.
2964       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2965         IncomingArgX ? *IncomingArgX :
2966         IncomingArgY ? *IncomingArgY :
2967         *IncomingArgZ, ~0u);
2968       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2969     }
2970   }
2971 
2972   if (OutgoingArg->isRegister()) {
2973     if (InputReg)
2974       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2975 
2976     CCInfo.AllocateReg(OutgoingArg->getRegister());
2977   } else {
2978     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2979     if (InputReg) {
2980       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2981                                               SpecialArgOffset);
2982       MemOpChains.push_back(ArgStore);
2983     }
2984   }
2985 }
2986 
2987 static bool canGuaranteeTCO(CallingConv::ID CC) {
2988   return CC == CallingConv::Fast;
2989 }
2990 
2991 /// Return true if we might ever do TCO for calls with this calling convention.
2992 static bool mayTailCallThisCC(CallingConv::ID CC) {
2993   switch (CC) {
2994   case CallingConv::C:
2995   case CallingConv::AMDGPU_Gfx:
2996     return true;
2997   default:
2998     return canGuaranteeTCO(CC);
2999   }
3000 }
3001 
3002 bool SITargetLowering::isEligibleForTailCallOptimization(
3003     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3004     const SmallVectorImpl<ISD::OutputArg> &Outs,
3005     const SmallVectorImpl<SDValue> &OutVals,
3006     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3007   if (!mayTailCallThisCC(CalleeCC))
3008     return false;
3009 
3010   // For a divergent call target, we need to do a waterfall loop over the
3011   // possible callees which precludes us from using a simple jump.
3012   if (Callee->isDivergent())
3013     return false;
3014 
3015   MachineFunction &MF = DAG.getMachineFunction();
3016   const Function &CallerF = MF.getFunction();
3017   CallingConv::ID CallerCC = CallerF.getCallingConv();
3018   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3019   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3020 
3021   // Kernels aren't callable, and don't have a live in return address so it
3022   // doesn't make sense to do a tail call with entry functions.
3023   if (!CallerPreserved)
3024     return false;
3025 
3026   bool CCMatch = CallerCC == CalleeCC;
3027 
3028   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3029     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3030       return true;
3031     return false;
3032   }
3033 
3034   // TODO: Can we handle var args?
3035   if (IsVarArg)
3036     return false;
3037 
3038   for (const Argument &Arg : CallerF.args()) {
3039     if (Arg.hasByValAttr())
3040       return false;
3041   }
3042 
3043   LLVMContext &Ctx = *DAG.getContext();
3044 
3045   // Check that the call results are passed in the same way.
3046   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3047                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3048                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3049     return false;
3050 
3051   // The callee has to preserve all registers the caller needs to preserve.
3052   if (!CCMatch) {
3053     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3054     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3055       return false;
3056   }
3057 
3058   // Nothing more to check if the callee is taking no arguments.
3059   if (Outs.empty())
3060     return true;
3061 
3062   SmallVector<CCValAssign, 16> ArgLocs;
3063   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3064 
3065   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3066 
3067   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3068   // If the stack arguments for this call do not fit into our own save area then
3069   // the call cannot be made tail.
3070   // TODO: Is this really necessary?
3071   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3072     return false;
3073 
3074   const MachineRegisterInfo &MRI = MF.getRegInfo();
3075   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3076 }
3077 
3078 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3079   if (!CI->isTailCall())
3080     return false;
3081 
3082   const Function *ParentFn = CI->getParent()->getParent();
3083   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3084     return false;
3085   return true;
3086 }
3087 
3088 // The wave scratch offset register is used as the global base pointer.
3089 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3090                                     SmallVectorImpl<SDValue> &InVals) const {
3091   SelectionDAG &DAG = CLI.DAG;
3092   const SDLoc &DL = CLI.DL;
3093   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3094   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3095   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3096   SDValue Chain = CLI.Chain;
3097   SDValue Callee = CLI.Callee;
3098   bool &IsTailCall = CLI.IsTailCall;
3099   CallingConv::ID CallConv = CLI.CallConv;
3100   bool IsVarArg = CLI.IsVarArg;
3101   bool IsSibCall = false;
3102   bool IsThisReturn = false;
3103   MachineFunction &MF = DAG.getMachineFunction();
3104 
3105   if (Callee.isUndef() || isNullConstant(Callee)) {
3106     if (!CLI.IsTailCall) {
3107       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3108         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3109     }
3110 
3111     return Chain;
3112   }
3113 
3114   if (IsVarArg) {
3115     return lowerUnhandledCall(CLI, InVals,
3116                               "unsupported call to variadic function ");
3117   }
3118 
3119   if (!CLI.CB)
3120     report_fatal_error("unsupported libcall legalization");
3121 
3122   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3123     return lowerUnhandledCall(CLI, InVals,
3124                               "unsupported required tail call to function ");
3125   }
3126 
3127   if (AMDGPU::isShader(CallConv)) {
3128     // Note the issue is with the CC of the called function, not of the call
3129     // itself.
3130     return lowerUnhandledCall(CLI, InVals,
3131                               "unsupported call to a shader function ");
3132   }
3133 
3134   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3135       CallConv != CallingConv::AMDGPU_Gfx) {
3136     // Only allow calls with specific calling conventions.
3137     return lowerUnhandledCall(CLI, InVals,
3138                               "unsupported calling convention for call from "
3139                               "graphics shader of function ");
3140   }
3141 
3142   if (IsTailCall) {
3143     IsTailCall = isEligibleForTailCallOptimization(
3144       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3145     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3146       report_fatal_error("failed to perform tail call elimination on a call "
3147                          "site marked musttail");
3148     }
3149 
3150     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3151 
3152     // A sibling call is one where we're under the usual C ABI and not planning
3153     // to change that but can still do a tail call:
3154     if (!TailCallOpt && IsTailCall)
3155       IsSibCall = true;
3156 
3157     if (IsTailCall)
3158       ++NumTailCalls;
3159   }
3160 
3161   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3162   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3163   SmallVector<SDValue, 8> MemOpChains;
3164 
3165   // Analyze operands of the call, assigning locations to each operand.
3166   SmallVector<CCValAssign, 16> ArgLocs;
3167   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3168   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3169 
3170   if (CallConv != CallingConv::AMDGPU_Gfx) {
3171     // With a fixed ABI, allocate fixed registers before user arguments.
3172     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3173   }
3174 
3175   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3176 
3177   // Get a count of how many bytes are to be pushed on the stack.
3178   unsigned NumBytes = CCInfo.getNextStackOffset();
3179 
3180   if (IsSibCall) {
3181     // Since we're not changing the ABI to make this a tail call, the memory
3182     // operands are already available in the caller's incoming argument space.
3183     NumBytes = 0;
3184   }
3185 
3186   // FPDiff is the byte offset of the call's argument area from the callee's.
3187   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3188   // by this amount for a tail call. In a sibling call it must be 0 because the
3189   // caller will deallocate the entire stack and the callee still expects its
3190   // arguments to begin at SP+0. Completely unused for non-tail calls.
3191   int32_t FPDiff = 0;
3192   MachineFrameInfo &MFI = MF.getFrameInfo();
3193 
3194   // Adjust the stack pointer for the new arguments...
3195   // These operations are automatically eliminated by the prolog/epilog pass
3196   if (!IsSibCall) {
3197     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3198 
3199     if (!Subtarget->enableFlatScratch()) {
3200       SmallVector<SDValue, 4> CopyFromChains;
3201 
3202       // In the HSA case, this should be an identity copy.
3203       SDValue ScratchRSrcReg
3204         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3205       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3206       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3207       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3208     }
3209   }
3210 
3211   MVT PtrVT = MVT::i32;
3212 
3213   // Walk the register/memloc assignments, inserting copies/loads.
3214   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3215     CCValAssign &VA = ArgLocs[i];
3216     SDValue Arg = OutVals[i];
3217 
3218     // Promote the value if needed.
3219     switch (VA.getLocInfo()) {
3220     case CCValAssign::Full:
3221       break;
3222     case CCValAssign::BCvt:
3223       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3224       break;
3225     case CCValAssign::ZExt:
3226       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3227       break;
3228     case CCValAssign::SExt:
3229       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3230       break;
3231     case CCValAssign::AExt:
3232       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3233       break;
3234     case CCValAssign::FPExt:
3235       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3236       break;
3237     default:
3238       llvm_unreachable("Unknown loc info!");
3239     }
3240 
3241     if (VA.isRegLoc()) {
3242       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3243     } else {
3244       assert(VA.isMemLoc());
3245 
3246       SDValue DstAddr;
3247       MachinePointerInfo DstInfo;
3248 
3249       unsigned LocMemOffset = VA.getLocMemOffset();
3250       int32_t Offset = LocMemOffset;
3251 
3252       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3253       MaybeAlign Alignment;
3254 
3255       if (IsTailCall) {
3256         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3257         unsigned OpSize = Flags.isByVal() ?
3258           Flags.getByValSize() : VA.getValVT().getStoreSize();
3259 
3260         // FIXME: We can have better than the minimum byval required alignment.
3261         Alignment =
3262             Flags.isByVal()
3263                 ? Flags.getNonZeroByValAlign()
3264                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3265 
3266         Offset = Offset + FPDiff;
3267         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3268 
3269         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3270         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3271 
3272         // Make sure any stack arguments overlapping with where we're storing
3273         // are loaded before this eventual operation. Otherwise they'll be
3274         // clobbered.
3275 
3276         // FIXME: Why is this really necessary? This seems to just result in a
3277         // lot of code to copy the stack and write them back to the same
3278         // locations, which are supposed to be immutable?
3279         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3280       } else {
3281         // Stores to the argument stack area are relative to the stack pointer.
3282         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3283                                         MVT::i32);
3284         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3285         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3286         Alignment =
3287             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3288       }
3289 
3290       if (Outs[i].Flags.isByVal()) {
3291         SDValue SizeNode =
3292             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3293         SDValue Cpy =
3294             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3295                           Outs[i].Flags.getNonZeroByValAlign(),
3296                           /*isVol = */ false, /*AlwaysInline = */ true,
3297                           /*isTailCall = */ false, DstInfo,
3298                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3299 
3300         MemOpChains.push_back(Cpy);
3301       } else {
3302         SDValue Store =
3303             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3304         MemOpChains.push_back(Store);
3305       }
3306     }
3307   }
3308 
3309   if (!MemOpChains.empty())
3310     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3311 
3312   // Build a sequence of copy-to-reg nodes chained together with token chain
3313   // and flag operands which copy the outgoing args into the appropriate regs.
3314   SDValue InFlag;
3315   for (auto &RegToPass : RegsToPass) {
3316     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3317                              RegToPass.second, InFlag);
3318     InFlag = Chain.getValue(1);
3319   }
3320 
3321 
3322   SDValue PhysReturnAddrReg;
3323   if (IsTailCall) {
3324     // Since the return is being combined with the call, we need to pass on the
3325     // return address.
3326 
3327     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3328     SDValue ReturnAddrReg = CreateLiveInRegister(
3329       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3330 
3331     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3332                                         MVT::i64);
3333     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3334     InFlag = Chain.getValue(1);
3335   }
3336 
3337   // We don't usually want to end the call-sequence here because we would tidy
3338   // the frame up *after* the call, however in the ABI-changing tail-call case
3339   // we've carefully laid out the parameters so that when sp is reset they'll be
3340   // in the correct location.
3341   if (IsTailCall && !IsSibCall) {
3342     Chain = DAG.getCALLSEQ_END(Chain,
3343                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3344                                DAG.getTargetConstant(0, DL, MVT::i32),
3345                                InFlag, DL);
3346     InFlag = Chain.getValue(1);
3347   }
3348 
3349   std::vector<SDValue> Ops;
3350   Ops.push_back(Chain);
3351   Ops.push_back(Callee);
3352   // Add a redundant copy of the callee global which will not be legalized, as
3353   // we need direct access to the callee later.
3354   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3355     const GlobalValue *GV = GSD->getGlobal();
3356     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3357   } else {
3358     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3359   }
3360 
3361   if (IsTailCall) {
3362     // Each tail call may have to adjust the stack by a different amount, so
3363     // this information must travel along with the operation for eventual
3364     // consumption by emitEpilogue.
3365     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3366 
3367     Ops.push_back(PhysReturnAddrReg);
3368   }
3369 
3370   // Add argument registers to the end of the list so that they are known live
3371   // into the call.
3372   for (auto &RegToPass : RegsToPass) {
3373     Ops.push_back(DAG.getRegister(RegToPass.first,
3374                                   RegToPass.second.getValueType()));
3375   }
3376 
3377   // Add a register mask operand representing the call-preserved registers.
3378 
3379   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3380   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3381   assert(Mask && "Missing call preserved mask for calling convention");
3382   Ops.push_back(DAG.getRegisterMask(Mask));
3383 
3384   if (InFlag.getNode())
3385     Ops.push_back(InFlag);
3386 
3387   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3388 
3389   // If we're doing a tall call, use a TC_RETURN here rather than an
3390   // actual call instruction.
3391   if (IsTailCall) {
3392     MFI.setHasTailCall();
3393     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3394   }
3395 
3396   // Returns a chain and a flag for retval copy to use.
3397   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3398   Chain = Call.getValue(0);
3399   InFlag = Call.getValue(1);
3400 
3401   uint64_t CalleePopBytes = NumBytes;
3402   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3403                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3404                              InFlag, DL);
3405   if (!Ins.empty())
3406     InFlag = Chain.getValue(1);
3407 
3408   // Handle result values, copying them out of physregs into vregs that we
3409   // return.
3410   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3411                          InVals, IsThisReturn,
3412                          IsThisReturn ? OutVals[0] : SDValue());
3413 }
3414 
3415 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3416 // except for applying the wave size scale to the increment amount.
3417 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3418     SDValue Op, SelectionDAG &DAG) const {
3419   const MachineFunction &MF = DAG.getMachineFunction();
3420   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3421 
3422   SDLoc dl(Op);
3423   EVT VT = Op.getValueType();
3424   SDValue Tmp1 = Op;
3425   SDValue Tmp2 = Op.getValue(1);
3426   SDValue Tmp3 = Op.getOperand(2);
3427   SDValue Chain = Tmp1.getOperand(0);
3428 
3429   Register SPReg = Info->getStackPtrOffsetReg();
3430 
3431   // Chain the dynamic stack allocation so that it doesn't modify the stack
3432   // pointer when other instructions are using the stack.
3433   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3434 
3435   SDValue Size  = Tmp2.getOperand(1);
3436   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3437   Chain = SP.getValue(1);
3438   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3439   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3440   const TargetFrameLowering *TFL = ST.getFrameLowering();
3441   unsigned Opc =
3442     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3443     ISD::ADD : ISD::SUB;
3444 
3445   SDValue ScaledSize = DAG.getNode(
3446       ISD::SHL, dl, VT, Size,
3447       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3448 
3449   Align StackAlign = TFL->getStackAlign();
3450   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3451   if (Alignment && *Alignment > StackAlign) {
3452     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3453                        DAG.getConstant(-(uint64_t)Alignment->value()
3454                                            << ST.getWavefrontSizeLog2(),
3455                                        dl, VT));
3456   }
3457 
3458   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3459   Tmp2 = DAG.getCALLSEQ_END(
3460       Chain, DAG.getIntPtrConstant(0, dl, true),
3461       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3462 
3463   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3464 }
3465 
3466 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3467                                                   SelectionDAG &DAG) const {
3468   // We only handle constant sizes here to allow non-entry block, static sized
3469   // allocas. A truly dynamic value is more difficult to support because we
3470   // don't know if the size value is uniform or not. If the size isn't uniform,
3471   // we would need to do a wave reduction to get the maximum size to know how
3472   // much to increment the uniform stack pointer.
3473   SDValue Size = Op.getOperand(1);
3474   if (isa<ConstantSDNode>(Size))
3475       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3476 
3477   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3478 }
3479 
3480 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3481                                              const MachineFunction &MF) const {
3482   Register Reg = StringSwitch<Register>(RegName)
3483     .Case("m0", AMDGPU::M0)
3484     .Case("exec", AMDGPU::EXEC)
3485     .Case("exec_lo", AMDGPU::EXEC_LO)
3486     .Case("exec_hi", AMDGPU::EXEC_HI)
3487     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3488     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3489     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3490     .Default(Register());
3491 
3492   if (Reg == AMDGPU::NoRegister) {
3493     report_fatal_error(Twine("invalid register name \""
3494                              + StringRef(RegName)  + "\"."));
3495 
3496   }
3497 
3498   if (!Subtarget->hasFlatScrRegister() &&
3499        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3500     report_fatal_error(Twine("invalid register \""
3501                              + StringRef(RegName)  + "\" for subtarget."));
3502   }
3503 
3504   switch (Reg) {
3505   case AMDGPU::M0:
3506   case AMDGPU::EXEC_LO:
3507   case AMDGPU::EXEC_HI:
3508   case AMDGPU::FLAT_SCR_LO:
3509   case AMDGPU::FLAT_SCR_HI:
3510     if (VT.getSizeInBits() == 32)
3511       return Reg;
3512     break;
3513   case AMDGPU::EXEC:
3514   case AMDGPU::FLAT_SCR:
3515     if (VT.getSizeInBits() == 64)
3516       return Reg;
3517     break;
3518   default:
3519     llvm_unreachable("missing register type checking");
3520   }
3521 
3522   report_fatal_error(Twine("invalid type for register \""
3523                            + StringRef(RegName) + "\"."));
3524 }
3525 
3526 // If kill is not the last instruction, split the block so kill is always a
3527 // proper terminator.
3528 MachineBasicBlock *
3529 SITargetLowering::splitKillBlock(MachineInstr &MI,
3530                                  MachineBasicBlock *BB) const {
3531   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3532   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3533   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3534   return SplitBB;
3535 }
3536 
3537 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3538 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3539 // be the first instruction in the remainder block.
3540 //
3541 /// \returns { LoopBody, Remainder }
3542 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3543 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3544   MachineFunction *MF = MBB.getParent();
3545   MachineBasicBlock::iterator I(&MI);
3546 
3547   // To insert the loop we need to split the block. Move everything after this
3548   // point to a new block, and insert a new empty block between the two.
3549   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3550   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3551   MachineFunction::iterator MBBI(MBB);
3552   ++MBBI;
3553 
3554   MF->insert(MBBI, LoopBB);
3555   MF->insert(MBBI, RemainderBB);
3556 
3557   LoopBB->addSuccessor(LoopBB);
3558   LoopBB->addSuccessor(RemainderBB);
3559 
3560   // Move the rest of the block into a new block.
3561   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3562 
3563   if (InstInLoop) {
3564     auto Next = std::next(I);
3565 
3566     // Move instruction to loop body.
3567     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3568 
3569     // Move the rest of the block.
3570     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3571   } else {
3572     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3573   }
3574 
3575   MBB.addSuccessor(LoopBB);
3576 
3577   return std::make_pair(LoopBB, RemainderBB);
3578 }
3579 
3580 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3581 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3582   MachineBasicBlock *MBB = MI.getParent();
3583   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3584   auto I = MI.getIterator();
3585   auto E = std::next(I);
3586 
3587   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3588     .addImm(0);
3589 
3590   MIBundleBuilder Bundler(*MBB, I, E);
3591   finalizeBundle(*MBB, Bundler.begin());
3592 }
3593 
3594 MachineBasicBlock *
3595 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3596                                          MachineBasicBlock *BB) const {
3597   const DebugLoc &DL = MI.getDebugLoc();
3598 
3599   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3600 
3601   MachineBasicBlock *LoopBB;
3602   MachineBasicBlock *RemainderBB;
3603   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3604 
3605   // Apparently kill flags are only valid if the def is in the same block?
3606   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3607     Src->setIsKill(false);
3608 
3609   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3610 
3611   MachineBasicBlock::iterator I = LoopBB->end();
3612 
3613   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3614     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3615 
3616   // Clear TRAP_STS.MEM_VIOL
3617   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3618     .addImm(0)
3619     .addImm(EncodedReg);
3620 
3621   bundleInstWithWaitcnt(MI);
3622 
3623   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3624 
3625   // Load and check TRAP_STS.MEM_VIOL
3626   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3627     .addImm(EncodedReg);
3628 
3629   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3630   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3631     .addReg(Reg, RegState::Kill)
3632     .addImm(0);
3633   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3634     .addMBB(LoopBB);
3635 
3636   return RemainderBB;
3637 }
3638 
3639 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3640 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3641 // will only do one iteration. In the worst case, this will loop 64 times.
3642 //
3643 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3644 static MachineBasicBlock::iterator
3645 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3646                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3647                        const DebugLoc &DL, const MachineOperand &Idx,
3648                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3649                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3650                        Register &SGPRIdxReg) {
3651 
3652   MachineFunction *MF = OrigBB.getParent();
3653   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3654   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3655   MachineBasicBlock::iterator I = LoopBB.begin();
3656 
3657   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3658   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3659   Register NewExec = MRI.createVirtualRegister(BoolRC);
3660   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3661   Register CondReg = MRI.createVirtualRegister(BoolRC);
3662 
3663   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3664     .addReg(InitReg)
3665     .addMBB(&OrigBB)
3666     .addReg(ResultReg)
3667     .addMBB(&LoopBB);
3668 
3669   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3670     .addReg(InitSaveExecReg)
3671     .addMBB(&OrigBB)
3672     .addReg(NewExec)
3673     .addMBB(&LoopBB);
3674 
3675   // Read the next variant <- also loop target.
3676   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3677       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3678 
3679   // Compare the just read M0 value to all possible Idx values.
3680   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3681       .addReg(CurrentIdxReg)
3682       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3683 
3684   // Update EXEC, save the original EXEC value to VCC.
3685   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3686                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3687           NewExec)
3688     .addReg(CondReg, RegState::Kill);
3689 
3690   MRI.setSimpleHint(NewExec, CondReg);
3691 
3692   if (UseGPRIdxMode) {
3693     if (Offset == 0) {
3694       SGPRIdxReg = CurrentIdxReg;
3695     } else {
3696       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3697       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3698           .addReg(CurrentIdxReg, RegState::Kill)
3699           .addImm(Offset);
3700     }
3701   } else {
3702     // Move index from VCC into M0
3703     if (Offset == 0) {
3704       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3705         .addReg(CurrentIdxReg, RegState::Kill);
3706     } else {
3707       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3708         .addReg(CurrentIdxReg, RegState::Kill)
3709         .addImm(Offset);
3710     }
3711   }
3712 
3713   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3714   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3715   MachineInstr *InsertPt =
3716     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3717                                                   : AMDGPU::S_XOR_B64_term), Exec)
3718       .addReg(Exec)
3719       .addReg(NewExec);
3720 
3721   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3722   // s_cbranch_scc0?
3723 
3724   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3725   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3726     .addMBB(&LoopBB);
3727 
3728   return InsertPt->getIterator();
3729 }
3730 
3731 // This has slightly sub-optimal regalloc when the source vector is killed by
3732 // the read. The register allocator does not understand that the kill is
3733 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3734 // subregister from it, using 1 more VGPR than necessary. This was saved when
3735 // this was expanded after register allocation.
3736 static MachineBasicBlock::iterator
3737 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3738                unsigned InitResultReg, unsigned PhiReg, int Offset,
3739                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3740   MachineFunction *MF = MBB.getParent();
3741   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3742   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3743   MachineRegisterInfo &MRI = MF->getRegInfo();
3744   const DebugLoc &DL = MI.getDebugLoc();
3745   MachineBasicBlock::iterator I(&MI);
3746 
3747   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3748   Register DstReg = MI.getOperand(0).getReg();
3749   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3750   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3751   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3752   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3753 
3754   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3755 
3756   // Save the EXEC mask
3757   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3758     .addReg(Exec);
3759 
3760   MachineBasicBlock *LoopBB;
3761   MachineBasicBlock *RemainderBB;
3762   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3763 
3764   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3765 
3766   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3767                                       InitResultReg, DstReg, PhiReg, TmpExec,
3768                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3769 
3770   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3771   MachineFunction::iterator MBBI(LoopBB);
3772   ++MBBI;
3773   MF->insert(MBBI, LandingPad);
3774   LoopBB->removeSuccessor(RemainderBB);
3775   LandingPad->addSuccessor(RemainderBB);
3776   LoopBB->addSuccessor(LandingPad);
3777   MachineBasicBlock::iterator First = LandingPad->begin();
3778   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3779     .addReg(SaveExec);
3780 
3781   return InsPt;
3782 }
3783 
3784 // Returns subreg index, offset
3785 static std::pair<unsigned, int>
3786 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3787                             const TargetRegisterClass *SuperRC,
3788                             unsigned VecReg,
3789                             int Offset) {
3790   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3791 
3792   // Skip out of bounds offsets, or else we would end up using an undefined
3793   // register.
3794   if (Offset >= NumElts || Offset < 0)
3795     return std::make_pair(AMDGPU::sub0, Offset);
3796 
3797   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3798 }
3799 
3800 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3801                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3802                                  int Offset) {
3803   MachineBasicBlock *MBB = MI.getParent();
3804   const DebugLoc &DL = MI.getDebugLoc();
3805   MachineBasicBlock::iterator I(&MI);
3806 
3807   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3808 
3809   assert(Idx->getReg() != AMDGPU::NoRegister);
3810 
3811   if (Offset == 0) {
3812     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3813   } else {
3814     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3815         .add(*Idx)
3816         .addImm(Offset);
3817   }
3818 }
3819 
3820 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3821                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3822                                    int Offset) {
3823   MachineBasicBlock *MBB = MI.getParent();
3824   const DebugLoc &DL = MI.getDebugLoc();
3825   MachineBasicBlock::iterator I(&MI);
3826 
3827   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3828 
3829   if (Offset == 0)
3830     return Idx->getReg();
3831 
3832   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3833   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3834       .add(*Idx)
3835       .addImm(Offset);
3836   return Tmp;
3837 }
3838 
3839 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3840                                           MachineBasicBlock &MBB,
3841                                           const GCNSubtarget &ST) {
3842   const SIInstrInfo *TII = ST.getInstrInfo();
3843   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3844   MachineFunction *MF = MBB.getParent();
3845   MachineRegisterInfo &MRI = MF->getRegInfo();
3846 
3847   Register Dst = MI.getOperand(0).getReg();
3848   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3849   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3850   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3851 
3852   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3853   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3854 
3855   unsigned SubReg;
3856   std::tie(SubReg, Offset)
3857     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3858 
3859   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3860 
3861   // Check for a SGPR index.
3862   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3863     MachineBasicBlock::iterator I(&MI);
3864     const DebugLoc &DL = MI.getDebugLoc();
3865 
3866     if (UseGPRIdxMode) {
3867       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3868       // to avoid interfering with other uses, so probably requires a new
3869       // optimization pass.
3870       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3871 
3872       const MCInstrDesc &GPRIDXDesc =
3873           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3874       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3875           .addReg(SrcReg)
3876           .addReg(Idx)
3877           .addImm(SubReg);
3878     } else {
3879       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3880 
3881       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3882         .addReg(SrcReg, 0, SubReg)
3883         .addReg(SrcReg, RegState::Implicit);
3884     }
3885 
3886     MI.eraseFromParent();
3887 
3888     return &MBB;
3889   }
3890 
3891   // Control flow needs to be inserted if indexing with a VGPR.
3892   const DebugLoc &DL = MI.getDebugLoc();
3893   MachineBasicBlock::iterator I(&MI);
3894 
3895   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3896   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3897 
3898   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3899 
3900   Register SGPRIdxReg;
3901   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3902                               UseGPRIdxMode, SGPRIdxReg);
3903 
3904   MachineBasicBlock *LoopBB = InsPt->getParent();
3905 
3906   if (UseGPRIdxMode) {
3907     const MCInstrDesc &GPRIDXDesc =
3908         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3909 
3910     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3911         .addReg(SrcReg)
3912         .addReg(SGPRIdxReg)
3913         .addImm(SubReg);
3914   } else {
3915     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3916       .addReg(SrcReg, 0, SubReg)
3917       .addReg(SrcReg, RegState::Implicit);
3918   }
3919 
3920   MI.eraseFromParent();
3921 
3922   return LoopBB;
3923 }
3924 
3925 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3926                                           MachineBasicBlock &MBB,
3927                                           const GCNSubtarget &ST) {
3928   const SIInstrInfo *TII = ST.getInstrInfo();
3929   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3930   MachineFunction *MF = MBB.getParent();
3931   MachineRegisterInfo &MRI = MF->getRegInfo();
3932 
3933   Register Dst = MI.getOperand(0).getReg();
3934   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3935   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3936   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3937   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3938   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3939   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3940 
3941   // This can be an immediate, but will be folded later.
3942   assert(Val->getReg());
3943 
3944   unsigned SubReg;
3945   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3946                                                          SrcVec->getReg(),
3947                                                          Offset);
3948   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3949 
3950   if (Idx->getReg() == AMDGPU::NoRegister) {
3951     MachineBasicBlock::iterator I(&MI);
3952     const DebugLoc &DL = MI.getDebugLoc();
3953 
3954     assert(Offset == 0);
3955 
3956     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3957         .add(*SrcVec)
3958         .add(*Val)
3959         .addImm(SubReg);
3960 
3961     MI.eraseFromParent();
3962     return &MBB;
3963   }
3964 
3965   // Check for a SGPR index.
3966   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3967     MachineBasicBlock::iterator I(&MI);
3968     const DebugLoc &DL = MI.getDebugLoc();
3969 
3970     if (UseGPRIdxMode) {
3971       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3972 
3973       const MCInstrDesc &GPRIDXDesc =
3974           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3975       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3976           .addReg(SrcVec->getReg())
3977           .add(*Val)
3978           .addReg(Idx)
3979           .addImm(SubReg);
3980     } else {
3981       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3982 
3983       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3984           TRI.getRegSizeInBits(*VecRC), 32, false);
3985       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3986           .addReg(SrcVec->getReg())
3987           .add(*Val)
3988           .addImm(SubReg);
3989     }
3990     MI.eraseFromParent();
3991     return &MBB;
3992   }
3993 
3994   // Control flow needs to be inserted if indexing with a VGPR.
3995   if (Val->isReg())
3996     MRI.clearKillFlags(Val->getReg());
3997 
3998   const DebugLoc &DL = MI.getDebugLoc();
3999 
4000   Register PhiReg = MRI.createVirtualRegister(VecRC);
4001 
4002   Register SGPRIdxReg;
4003   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4004                               UseGPRIdxMode, SGPRIdxReg);
4005   MachineBasicBlock *LoopBB = InsPt->getParent();
4006 
4007   if (UseGPRIdxMode) {
4008     const MCInstrDesc &GPRIDXDesc =
4009         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4010 
4011     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4012         .addReg(PhiReg)
4013         .add(*Val)
4014         .addReg(SGPRIdxReg)
4015         .addImm(AMDGPU::sub0);
4016   } else {
4017     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4018         TRI.getRegSizeInBits(*VecRC), 32, false);
4019     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4020         .addReg(PhiReg)
4021         .add(*Val)
4022         .addImm(AMDGPU::sub0);
4023   }
4024 
4025   MI.eraseFromParent();
4026   return LoopBB;
4027 }
4028 
4029 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4030   MachineInstr &MI, MachineBasicBlock *BB) const {
4031 
4032   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4033   MachineFunction *MF = BB->getParent();
4034   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4035 
4036   switch (MI.getOpcode()) {
4037   case AMDGPU::S_UADDO_PSEUDO:
4038   case AMDGPU::S_USUBO_PSEUDO: {
4039     const DebugLoc &DL = MI.getDebugLoc();
4040     MachineOperand &Dest0 = MI.getOperand(0);
4041     MachineOperand &Dest1 = MI.getOperand(1);
4042     MachineOperand &Src0 = MI.getOperand(2);
4043     MachineOperand &Src1 = MI.getOperand(3);
4044 
4045     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4046                        ? AMDGPU::S_ADD_I32
4047                        : AMDGPU::S_SUB_I32;
4048     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4049 
4050     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4051         .addImm(1)
4052         .addImm(0);
4053 
4054     MI.eraseFromParent();
4055     return BB;
4056   }
4057   case AMDGPU::S_ADD_U64_PSEUDO:
4058   case AMDGPU::S_SUB_U64_PSEUDO: {
4059     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4060     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4061     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4062     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4063     const DebugLoc &DL = MI.getDebugLoc();
4064 
4065     MachineOperand &Dest = MI.getOperand(0);
4066     MachineOperand &Src0 = MI.getOperand(1);
4067     MachineOperand &Src1 = MI.getOperand(2);
4068 
4069     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4070     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4071 
4072     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4073         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4074     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4075         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4076 
4077     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4078         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4079     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4080         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4081 
4082     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4083 
4084     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4085     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4086     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4087     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4088     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4089         .addReg(DestSub0)
4090         .addImm(AMDGPU::sub0)
4091         .addReg(DestSub1)
4092         .addImm(AMDGPU::sub1);
4093     MI.eraseFromParent();
4094     return BB;
4095   }
4096   case AMDGPU::V_ADD_U64_PSEUDO:
4097   case AMDGPU::V_SUB_U64_PSEUDO: {
4098     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4099     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4100     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4101     const DebugLoc &DL = MI.getDebugLoc();
4102 
4103     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4104 
4105     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4106 
4107     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4108     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4109 
4110     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4111     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4112 
4113     MachineOperand &Dest = MI.getOperand(0);
4114     MachineOperand &Src0 = MI.getOperand(1);
4115     MachineOperand &Src1 = MI.getOperand(2);
4116 
4117     const TargetRegisterClass *Src0RC = Src0.isReg()
4118                                             ? MRI.getRegClass(Src0.getReg())
4119                                             : &AMDGPU::VReg_64RegClass;
4120     const TargetRegisterClass *Src1RC = Src1.isReg()
4121                                             ? MRI.getRegClass(Src1.getReg())
4122                                             : &AMDGPU::VReg_64RegClass;
4123 
4124     const TargetRegisterClass *Src0SubRC =
4125         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4126     const TargetRegisterClass *Src1SubRC =
4127         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4128 
4129     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4130         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4131     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4132         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4133 
4134     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4135         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4136     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4137         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4138 
4139     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4140     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4141                                .addReg(CarryReg, RegState::Define)
4142                                .add(SrcReg0Sub0)
4143                                .add(SrcReg1Sub0)
4144                                .addImm(0); // clamp bit
4145 
4146     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4147     MachineInstr *HiHalf =
4148         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4149             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4150             .add(SrcReg0Sub1)
4151             .add(SrcReg1Sub1)
4152             .addReg(CarryReg, RegState::Kill)
4153             .addImm(0); // clamp bit
4154 
4155     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4156         .addReg(DestSub0)
4157         .addImm(AMDGPU::sub0)
4158         .addReg(DestSub1)
4159         .addImm(AMDGPU::sub1);
4160     TII->legalizeOperands(*LoHalf);
4161     TII->legalizeOperands(*HiHalf);
4162     MI.eraseFromParent();
4163     return BB;
4164   }
4165   case AMDGPU::S_ADD_CO_PSEUDO:
4166   case AMDGPU::S_SUB_CO_PSEUDO: {
4167     // This pseudo has a chance to be selected
4168     // only from uniform add/subcarry node. All the VGPR operands
4169     // therefore assumed to be splat vectors.
4170     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4171     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4172     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4173     MachineBasicBlock::iterator MII = MI;
4174     const DebugLoc &DL = MI.getDebugLoc();
4175     MachineOperand &Dest = MI.getOperand(0);
4176     MachineOperand &CarryDest = MI.getOperand(1);
4177     MachineOperand &Src0 = MI.getOperand(2);
4178     MachineOperand &Src1 = MI.getOperand(3);
4179     MachineOperand &Src2 = MI.getOperand(4);
4180     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4181                        ? AMDGPU::S_ADDC_U32
4182                        : AMDGPU::S_SUBB_U32;
4183     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4184       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4185       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4186           .addReg(Src0.getReg());
4187       Src0.setReg(RegOp0);
4188     }
4189     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4190       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4191       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4192           .addReg(Src1.getReg());
4193       Src1.setReg(RegOp1);
4194     }
4195     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4196     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4197       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4198           .addReg(Src2.getReg());
4199       Src2.setReg(RegOp2);
4200     }
4201 
4202     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4203     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4204     assert(WaveSize == 64 || WaveSize == 32);
4205 
4206     if (WaveSize == 64) {
4207       if (ST.hasScalarCompareEq64()) {
4208         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4209             .addReg(Src2.getReg())
4210             .addImm(0);
4211       } else {
4212         const TargetRegisterClass *SubRC =
4213             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4214         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4215             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4216         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4217             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4218         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4219 
4220         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4221             .add(Src2Sub0)
4222             .add(Src2Sub1);
4223 
4224         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4225             .addReg(Src2_32, RegState::Kill)
4226             .addImm(0);
4227       }
4228     } else {
4229       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4230           .addReg(Src2.getReg())
4231           .addImm(0);
4232     }
4233 
4234     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4235 
4236     unsigned SelOpc =
4237         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4238 
4239     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4240         .addImm(-1)
4241         .addImm(0);
4242 
4243     MI.eraseFromParent();
4244     return BB;
4245   }
4246   case AMDGPU::SI_INIT_M0: {
4247     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4248             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4249         .add(MI.getOperand(0));
4250     MI.eraseFromParent();
4251     return BB;
4252   }
4253   case AMDGPU::GET_GROUPSTATICSIZE: {
4254     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4255            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4256     DebugLoc DL = MI.getDebugLoc();
4257     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4258         .add(MI.getOperand(0))
4259         .addImm(MFI->getLDSSize());
4260     MI.eraseFromParent();
4261     return BB;
4262   }
4263   case AMDGPU::SI_INDIRECT_SRC_V1:
4264   case AMDGPU::SI_INDIRECT_SRC_V2:
4265   case AMDGPU::SI_INDIRECT_SRC_V4:
4266   case AMDGPU::SI_INDIRECT_SRC_V8:
4267   case AMDGPU::SI_INDIRECT_SRC_V16:
4268   case AMDGPU::SI_INDIRECT_SRC_V32:
4269     return emitIndirectSrc(MI, *BB, *getSubtarget());
4270   case AMDGPU::SI_INDIRECT_DST_V1:
4271   case AMDGPU::SI_INDIRECT_DST_V2:
4272   case AMDGPU::SI_INDIRECT_DST_V4:
4273   case AMDGPU::SI_INDIRECT_DST_V8:
4274   case AMDGPU::SI_INDIRECT_DST_V16:
4275   case AMDGPU::SI_INDIRECT_DST_V32:
4276     return emitIndirectDst(MI, *BB, *getSubtarget());
4277   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4278   case AMDGPU::SI_KILL_I1_PSEUDO:
4279     return splitKillBlock(MI, BB);
4280   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4281     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4282     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4283     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4284 
4285     Register Dst = MI.getOperand(0).getReg();
4286     Register Src0 = MI.getOperand(1).getReg();
4287     Register Src1 = MI.getOperand(2).getReg();
4288     const DebugLoc &DL = MI.getDebugLoc();
4289     Register SrcCond = MI.getOperand(3).getReg();
4290 
4291     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4292     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4293     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4294     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4295 
4296     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4297       .addReg(SrcCond);
4298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4299       .addImm(0)
4300       .addReg(Src0, 0, AMDGPU::sub0)
4301       .addImm(0)
4302       .addReg(Src1, 0, AMDGPU::sub0)
4303       .addReg(SrcCondCopy);
4304     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4305       .addImm(0)
4306       .addReg(Src0, 0, AMDGPU::sub1)
4307       .addImm(0)
4308       .addReg(Src1, 0, AMDGPU::sub1)
4309       .addReg(SrcCondCopy);
4310 
4311     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4312       .addReg(DstLo)
4313       .addImm(AMDGPU::sub0)
4314       .addReg(DstHi)
4315       .addImm(AMDGPU::sub1);
4316     MI.eraseFromParent();
4317     return BB;
4318   }
4319   case AMDGPU::SI_BR_UNDEF: {
4320     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4321     const DebugLoc &DL = MI.getDebugLoc();
4322     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4323                            .add(MI.getOperand(0));
4324     Br->getOperand(1).setIsUndef(true); // read undef SCC
4325     MI.eraseFromParent();
4326     return BB;
4327   }
4328   case AMDGPU::ADJCALLSTACKUP:
4329   case AMDGPU::ADJCALLSTACKDOWN: {
4330     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4331     MachineInstrBuilder MIB(*MF, &MI);
4332     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4333        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4334     return BB;
4335   }
4336   case AMDGPU::SI_CALL_ISEL: {
4337     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4338     const DebugLoc &DL = MI.getDebugLoc();
4339 
4340     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4341 
4342     MachineInstrBuilder MIB;
4343     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4344 
4345     for (const MachineOperand &MO : MI.operands())
4346       MIB.add(MO);
4347 
4348     MIB.cloneMemRefs(MI);
4349     MI.eraseFromParent();
4350     return BB;
4351   }
4352   case AMDGPU::V_ADD_CO_U32_e32:
4353   case AMDGPU::V_SUB_CO_U32_e32:
4354   case AMDGPU::V_SUBREV_CO_U32_e32: {
4355     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4356     const DebugLoc &DL = MI.getDebugLoc();
4357     unsigned Opc = MI.getOpcode();
4358 
4359     bool NeedClampOperand = false;
4360     if (TII->pseudoToMCOpcode(Opc) == -1) {
4361       Opc = AMDGPU::getVOPe64(Opc);
4362       NeedClampOperand = true;
4363     }
4364 
4365     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4366     if (TII->isVOP3(*I)) {
4367       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4368       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4369       I.addReg(TRI->getVCC(), RegState::Define);
4370     }
4371     I.add(MI.getOperand(1))
4372      .add(MI.getOperand(2));
4373     if (NeedClampOperand)
4374       I.addImm(0); // clamp bit for e64 encoding
4375 
4376     TII->legalizeOperands(*I);
4377 
4378     MI.eraseFromParent();
4379     return BB;
4380   }
4381   case AMDGPU::V_ADDC_U32_e32:
4382   case AMDGPU::V_SUBB_U32_e32:
4383   case AMDGPU::V_SUBBREV_U32_e32:
4384     // These instructions have an implicit use of vcc which counts towards the
4385     // constant bus limit.
4386     TII->legalizeOperands(MI);
4387     return BB;
4388   case AMDGPU::DS_GWS_INIT:
4389   case AMDGPU::DS_GWS_SEMA_BR:
4390   case AMDGPU::DS_GWS_BARRIER:
4391     if (Subtarget->needsAlignedVGPRs()) {
4392       // Add implicit aligned super-reg to force alignment on the data operand.
4393       const DebugLoc &DL = MI.getDebugLoc();
4394       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4395       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4396       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4397       Register DataReg = Op->getReg();
4398       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4399       Register Undef = MRI.createVirtualRegister(
4400           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4401       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4402       Register NewVR =
4403           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4404                                            : &AMDGPU::VReg_64_Align2RegClass);
4405       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4406           .addReg(DataReg, 0, Op->getSubReg())
4407           .addImm(AMDGPU::sub0)
4408           .addReg(Undef)
4409           .addImm(AMDGPU::sub1);
4410       Op->setReg(NewVR);
4411       Op->setSubReg(AMDGPU::sub0);
4412       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4413     }
4414     LLVM_FALLTHROUGH;
4415   case AMDGPU::DS_GWS_SEMA_V:
4416   case AMDGPU::DS_GWS_SEMA_P:
4417   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4418     // A s_waitcnt 0 is required to be the instruction immediately following.
4419     if (getSubtarget()->hasGWSAutoReplay()) {
4420       bundleInstWithWaitcnt(MI);
4421       return BB;
4422     }
4423 
4424     return emitGWSMemViolTestLoop(MI, BB);
4425   case AMDGPU::S_SETREG_B32: {
4426     // Try to optimize cases that only set the denormal mode or rounding mode.
4427     //
4428     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4429     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4430     // instead.
4431     //
4432     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4433     // allow you to have a no side effect instruction in the output of a
4434     // sideeffecting pattern.
4435     unsigned ID, Offset, Width;
4436     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4437     if (ID != AMDGPU::Hwreg::ID_MODE)
4438       return BB;
4439 
4440     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4441     const unsigned SetMask = WidthMask << Offset;
4442 
4443     if (getSubtarget()->hasDenormModeInst()) {
4444       unsigned SetDenormOp = 0;
4445       unsigned SetRoundOp = 0;
4446 
4447       // The dedicated instructions can only set the whole denorm or round mode
4448       // at once, not a subset of bits in either.
4449       if (SetMask ==
4450           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4451         // If this fully sets both the round and denorm mode, emit the two
4452         // dedicated instructions for these.
4453         SetRoundOp = AMDGPU::S_ROUND_MODE;
4454         SetDenormOp = AMDGPU::S_DENORM_MODE;
4455       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4456         SetRoundOp = AMDGPU::S_ROUND_MODE;
4457       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4458         SetDenormOp = AMDGPU::S_DENORM_MODE;
4459       }
4460 
4461       if (SetRoundOp || SetDenormOp) {
4462         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4463         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4464         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4465           unsigned ImmVal = Def->getOperand(1).getImm();
4466           if (SetRoundOp) {
4467             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4468                 .addImm(ImmVal & 0xf);
4469 
4470             // If we also have the denorm mode, get just the denorm mode bits.
4471             ImmVal >>= 4;
4472           }
4473 
4474           if (SetDenormOp) {
4475             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4476                 .addImm(ImmVal & 0xf);
4477           }
4478 
4479           MI.eraseFromParent();
4480           return BB;
4481         }
4482       }
4483     }
4484 
4485     // If only FP bits are touched, used the no side effects pseudo.
4486     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4487                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4488       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4489 
4490     return BB;
4491   }
4492   default:
4493     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4494   }
4495 }
4496 
4497 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4498   return isTypeLegal(VT.getScalarType());
4499 }
4500 
4501 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4502   // This currently forces unfolding various combinations of fsub into fma with
4503   // free fneg'd operands. As long as we have fast FMA (controlled by
4504   // isFMAFasterThanFMulAndFAdd), we should perform these.
4505 
4506   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4507   // most of these combines appear to be cycle neutral but save on instruction
4508   // count / code size.
4509   return true;
4510 }
4511 
4512 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4513 
4514 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4515                                          EVT VT) const {
4516   if (!VT.isVector()) {
4517     return MVT::i1;
4518   }
4519   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4520 }
4521 
4522 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4523   // TODO: Should i16 be used always if legal? For now it would force VALU
4524   // shifts.
4525   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4526 }
4527 
4528 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4529   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4530              ? Ty.changeElementSize(16)
4531              : Ty.changeElementSize(32);
4532 }
4533 
4534 // Answering this is somewhat tricky and depends on the specific device which
4535 // have different rates for fma or all f64 operations.
4536 //
4537 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4538 // regardless of which device (although the number of cycles differs between
4539 // devices), so it is always profitable for f64.
4540 //
4541 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4542 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4543 // which we can always do even without fused FP ops since it returns the same
4544 // result as the separate operations and since it is always full
4545 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4546 // however does not support denormals, so we do report fma as faster if we have
4547 // a fast fma device and require denormals.
4548 //
4549 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4550                                                   EVT VT) const {
4551   VT = VT.getScalarType();
4552 
4553   switch (VT.getSimpleVT().SimpleTy) {
4554   case MVT::f32: {
4555     // If mad is not available this depends only on if f32 fma is full rate.
4556     if (!Subtarget->hasMadMacF32Insts())
4557       return Subtarget->hasFastFMAF32();
4558 
4559     // Otherwise f32 mad is always full rate and returns the same result as
4560     // the separate operations so should be preferred over fma.
4561     // However does not support denomals.
4562     if (hasFP32Denormals(MF))
4563       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4564 
4565     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4566     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4567   }
4568   case MVT::f64:
4569     return true;
4570   case MVT::f16:
4571     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4572   default:
4573     break;
4574   }
4575 
4576   return false;
4577 }
4578 
4579 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4580                                                   LLT Ty) const {
4581   switch (Ty.getScalarSizeInBits()) {
4582   case 16:
4583     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4584   case 32:
4585     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4586   case 64:
4587     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4588   default:
4589     break;
4590   }
4591 
4592   return false;
4593 }
4594 
4595 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4596   if (!Ty.isScalar())
4597     return false;
4598 
4599   if (Ty.getScalarSizeInBits() == 16)
4600     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4601   if (Ty.getScalarSizeInBits() == 32)
4602     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4603 
4604   return false;
4605 }
4606 
4607 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4608                                    const SDNode *N) const {
4609   // TODO: Check future ftz flag
4610   // v_mad_f32/v_mac_f32 do not support denormals.
4611   EVT VT = N->getValueType(0);
4612   if (VT == MVT::f32)
4613     return Subtarget->hasMadMacF32Insts() &&
4614            !hasFP32Denormals(DAG.getMachineFunction());
4615   if (VT == MVT::f16) {
4616     return Subtarget->hasMadF16() &&
4617            !hasFP64FP16Denormals(DAG.getMachineFunction());
4618   }
4619 
4620   return false;
4621 }
4622 
4623 //===----------------------------------------------------------------------===//
4624 // Custom DAG Lowering Operations
4625 //===----------------------------------------------------------------------===//
4626 
4627 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4628 // wider vector type is legal.
4629 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4630                                              SelectionDAG &DAG) const {
4631   unsigned Opc = Op.getOpcode();
4632   EVT VT = Op.getValueType();
4633   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4634 
4635   SDValue Lo, Hi;
4636   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4637 
4638   SDLoc SL(Op);
4639   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4640                              Op->getFlags());
4641   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4642                              Op->getFlags());
4643 
4644   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4645 }
4646 
4647 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4648 // wider vector type is legal.
4649 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4650                                               SelectionDAG &DAG) const {
4651   unsigned Opc = Op.getOpcode();
4652   EVT VT = Op.getValueType();
4653   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4654          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4655          VT == MVT::v16f32 || VT == MVT::v32f32);
4656 
4657   SDValue Lo0, Hi0;
4658   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4659   SDValue Lo1, Hi1;
4660   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4661 
4662   SDLoc SL(Op);
4663 
4664   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4665                              Op->getFlags());
4666   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4667                              Op->getFlags());
4668 
4669   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4670 }
4671 
4672 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4673                                               SelectionDAG &DAG) const {
4674   unsigned Opc = Op.getOpcode();
4675   EVT VT = Op.getValueType();
4676   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4677          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4678          VT == MVT::v16f32 || VT == MVT::v32f32);
4679 
4680   SDValue Lo0, Hi0;
4681   SDValue Op0 = Op.getOperand(0);
4682   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4683                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4684                          : std::make_pair(Op0, Op0);
4685   SDValue Lo1, Hi1;
4686   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4687   SDValue Lo2, Hi2;
4688   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4689 
4690   SDLoc SL(Op);
4691   auto ResVT = DAG.GetSplitDestVTs(VT);
4692 
4693   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4694                              Op->getFlags());
4695   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4696                              Op->getFlags());
4697 
4698   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4699 }
4700 
4701 
4702 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4703   switch (Op.getOpcode()) {
4704   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4705   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4706   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4707   case ISD::LOAD: {
4708     SDValue Result = LowerLOAD(Op, DAG);
4709     assert((!Result.getNode() ||
4710             Result.getNode()->getNumValues() == 2) &&
4711            "Load should return a value and a chain");
4712     return Result;
4713   }
4714 
4715   case ISD::FSIN:
4716   case ISD::FCOS:
4717     return LowerTrig(Op, DAG);
4718   case ISD::SELECT: return LowerSELECT(Op, DAG);
4719   case ISD::FDIV: return LowerFDIV(Op, DAG);
4720   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4721   case ISD::STORE: return LowerSTORE(Op, DAG);
4722   case ISD::GlobalAddress: {
4723     MachineFunction &MF = DAG.getMachineFunction();
4724     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4725     return LowerGlobalAddress(MFI, Op, DAG);
4726   }
4727   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4728   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4729   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4730   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4731   case ISD::INSERT_SUBVECTOR:
4732     return lowerINSERT_SUBVECTOR(Op, DAG);
4733   case ISD::INSERT_VECTOR_ELT:
4734     return lowerINSERT_VECTOR_ELT(Op, DAG);
4735   case ISD::EXTRACT_VECTOR_ELT:
4736     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4737   case ISD::VECTOR_SHUFFLE:
4738     return lowerVECTOR_SHUFFLE(Op, DAG);
4739   case ISD::BUILD_VECTOR:
4740     return lowerBUILD_VECTOR(Op, DAG);
4741   case ISD::FP_ROUND:
4742     return lowerFP_ROUND(Op, DAG);
4743   case ISD::TRAP:
4744     return lowerTRAP(Op, DAG);
4745   case ISD::DEBUGTRAP:
4746     return lowerDEBUGTRAP(Op, DAG);
4747   case ISD::FABS:
4748   case ISD::FNEG:
4749   case ISD::FCANONICALIZE:
4750   case ISD::BSWAP:
4751     return splitUnaryVectorOp(Op, DAG);
4752   case ISD::FMINNUM:
4753   case ISD::FMAXNUM:
4754     return lowerFMINNUM_FMAXNUM(Op, DAG);
4755   case ISD::FMA:
4756     return splitTernaryVectorOp(Op, DAG);
4757   case ISD::FP_TO_SINT:
4758   case ISD::FP_TO_UINT:
4759     return LowerFP_TO_INT(Op, DAG);
4760   case ISD::SHL:
4761   case ISD::SRA:
4762   case ISD::SRL:
4763   case ISD::ADD:
4764   case ISD::SUB:
4765   case ISD::MUL:
4766   case ISD::SMIN:
4767   case ISD::SMAX:
4768   case ISD::UMIN:
4769   case ISD::UMAX:
4770   case ISD::FADD:
4771   case ISD::FMUL:
4772   case ISD::FMINNUM_IEEE:
4773   case ISD::FMAXNUM_IEEE:
4774   case ISD::UADDSAT:
4775   case ISD::USUBSAT:
4776   case ISD::SADDSAT:
4777   case ISD::SSUBSAT:
4778     return splitBinaryVectorOp(Op, DAG);
4779   case ISD::SMULO:
4780   case ISD::UMULO:
4781     return lowerXMULO(Op, DAG);
4782   case ISD::SMUL_LOHI:
4783   case ISD::UMUL_LOHI:
4784     return lowerXMUL_LOHI(Op, DAG);
4785   case ISD::DYNAMIC_STACKALLOC:
4786     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4787   }
4788   return SDValue();
4789 }
4790 
4791 // Used for D16: Casts the result of an instruction into the right vector,
4792 // packs values if loads return unpacked values.
4793 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4794                                        const SDLoc &DL,
4795                                        SelectionDAG &DAG, bool Unpacked) {
4796   if (!LoadVT.isVector())
4797     return Result;
4798 
4799   // Cast back to the original packed type or to a larger type that is a
4800   // multiple of 32 bit for D16. Widening the return type is a required for
4801   // legalization.
4802   EVT FittingLoadVT = LoadVT;
4803   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4804     FittingLoadVT =
4805         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4806                          LoadVT.getVectorNumElements() + 1);
4807   }
4808 
4809   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4810     // Truncate to v2i16/v4i16.
4811     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4812 
4813     // Workaround legalizer not scalarizing truncate after vector op
4814     // legalization but not creating intermediate vector trunc.
4815     SmallVector<SDValue, 4> Elts;
4816     DAG.ExtractVectorElements(Result, Elts);
4817     for (SDValue &Elt : Elts)
4818       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4819 
4820     // Pad illegal v1i16/v3fi6 to v4i16
4821     if ((LoadVT.getVectorNumElements() % 2) == 1)
4822       Elts.push_back(DAG.getUNDEF(MVT::i16));
4823 
4824     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4825 
4826     // Bitcast to original type (v2f16/v4f16).
4827     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4828   }
4829 
4830   // Cast back to the original packed type.
4831   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4832 }
4833 
4834 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4835                                               MemSDNode *M,
4836                                               SelectionDAG &DAG,
4837                                               ArrayRef<SDValue> Ops,
4838                                               bool IsIntrinsic) const {
4839   SDLoc DL(M);
4840 
4841   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4842   EVT LoadVT = M->getValueType(0);
4843 
4844   EVT EquivLoadVT = LoadVT;
4845   if (LoadVT.isVector()) {
4846     if (Unpacked) {
4847       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4848                                      LoadVT.getVectorNumElements());
4849     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4850       // Widen v3f16 to legal type
4851       EquivLoadVT =
4852           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4853                            LoadVT.getVectorNumElements() + 1);
4854     }
4855   }
4856 
4857   // Change from v4f16/v2f16 to EquivLoadVT.
4858   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4859 
4860   SDValue Load
4861     = DAG.getMemIntrinsicNode(
4862       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4863       VTList, Ops, M->getMemoryVT(),
4864       M->getMemOperand());
4865 
4866   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4867 
4868   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4869 }
4870 
4871 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4872                                              SelectionDAG &DAG,
4873                                              ArrayRef<SDValue> Ops) const {
4874   SDLoc DL(M);
4875   EVT LoadVT = M->getValueType(0);
4876   EVT EltType = LoadVT.getScalarType();
4877   EVT IntVT = LoadVT.changeTypeToInteger();
4878 
4879   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4880 
4881   unsigned Opc =
4882       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4883 
4884   if (IsD16) {
4885     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4886   }
4887 
4888   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4889   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4890     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4891 
4892   if (isTypeLegal(LoadVT)) {
4893     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4894                                M->getMemOperand(), DAG);
4895   }
4896 
4897   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4898   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4899   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4900                                         M->getMemOperand(), DAG);
4901   return DAG.getMergeValues(
4902       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4903       DL);
4904 }
4905 
4906 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4907                                   SDNode *N, SelectionDAG &DAG) {
4908   EVT VT = N->getValueType(0);
4909   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4910   unsigned CondCode = CD->getZExtValue();
4911   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4912     return DAG.getUNDEF(VT);
4913 
4914   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4915 
4916   SDValue LHS = N->getOperand(1);
4917   SDValue RHS = N->getOperand(2);
4918 
4919   SDLoc DL(N);
4920 
4921   EVT CmpVT = LHS.getValueType();
4922   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4923     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4924       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4925     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4926     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4927   }
4928 
4929   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4930 
4931   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4932   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4933 
4934   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4935                               DAG.getCondCode(CCOpcode));
4936   if (VT.bitsEq(CCVT))
4937     return SetCC;
4938   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4939 }
4940 
4941 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4942                                   SDNode *N, SelectionDAG &DAG) {
4943   EVT VT = N->getValueType(0);
4944   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4945 
4946   unsigned CondCode = CD->getZExtValue();
4947   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4948     return DAG.getUNDEF(VT);
4949 
4950   SDValue Src0 = N->getOperand(1);
4951   SDValue Src1 = N->getOperand(2);
4952   EVT CmpVT = Src0.getValueType();
4953   SDLoc SL(N);
4954 
4955   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4956     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4957     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4958   }
4959 
4960   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4961   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4962   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4963   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4964   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4965                               Src1, DAG.getCondCode(CCOpcode));
4966   if (VT.bitsEq(CCVT))
4967     return SetCC;
4968   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4969 }
4970 
4971 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4972                                     SelectionDAG &DAG) {
4973   EVT VT = N->getValueType(0);
4974   SDValue Src = N->getOperand(1);
4975   SDLoc SL(N);
4976 
4977   if (Src.getOpcode() == ISD::SETCC) {
4978     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4979     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4980                        Src.getOperand(1), Src.getOperand(2));
4981   }
4982   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4983     // (ballot 0) -> 0
4984     if (Arg->isZero())
4985       return DAG.getConstant(0, SL, VT);
4986 
4987     // (ballot 1) -> EXEC/EXEC_LO
4988     if (Arg->isOne()) {
4989       Register Exec;
4990       if (VT.getScalarSizeInBits() == 32)
4991         Exec = AMDGPU::EXEC_LO;
4992       else if (VT.getScalarSizeInBits() == 64)
4993         Exec = AMDGPU::EXEC;
4994       else
4995         return SDValue();
4996 
4997       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4998     }
4999   }
5000 
5001   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5002   // ISD::SETNE)
5003   return DAG.getNode(
5004       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5005       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5006 }
5007 
5008 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5009                                           SmallVectorImpl<SDValue> &Results,
5010                                           SelectionDAG &DAG) const {
5011   switch (N->getOpcode()) {
5012   case ISD::INSERT_VECTOR_ELT: {
5013     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5014       Results.push_back(Res);
5015     return;
5016   }
5017   case ISD::EXTRACT_VECTOR_ELT: {
5018     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5019       Results.push_back(Res);
5020     return;
5021   }
5022   case ISD::INTRINSIC_WO_CHAIN: {
5023     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5024     switch (IID) {
5025     case Intrinsic::amdgcn_cvt_pkrtz: {
5026       SDValue Src0 = N->getOperand(1);
5027       SDValue Src1 = N->getOperand(2);
5028       SDLoc SL(N);
5029       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5030                                 Src0, Src1);
5031       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5032       return;
5033     }
5034     case Intrinsic::amdgcn_cvt_pknorm_i16:
5035     case Intrinsic::amdgcn_cvt_pknorm_u16:
5036     case Intrinsic::amdgcn_cvt_pk_i16:
5037     case Intrinsic::amdgcn_cvt_pk_u16: {
5038       SDValue Src0 = N->getOperand(1);
5039       SDValue Src1 = N->getOperand(2);
5040       SDLoc SL(N);
5041       unsigned Opcode;
5042 
5043       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5044         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5045       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5046         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5047       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5048         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5049       else
5050         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5051 
5052       EVT VT = N->getValueType(0);
5053       if (isTypeLegal(VT))
5054         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5055       else {
5056         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5057         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5058       }
5059       return;
5060     }
5061     }
5062     break;
5063   }
5064   case ISD::INTRINSIC_W_CHAIN: {
5065     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5066       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5067         // FIXME: Hacky
5068         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5069           Results.push_back(Res.getOperand(I));
5070         }
5071       } else {
5072         Results.push_back(Res);
5073         Results.push_back(Res.getValue(1));
5074       }
5075       return;
5076     }
5077 
5078     break;
5079   }
5080   case ISD::SELECT: {
5081     SDLoc SL(N);
5082     EVT VT = N->getValueType(0);
5083     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5084     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5085     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5086 
5087     EVT SelectVT = NewVT;
5088     if (NewVT.bitsLT(MVT::i32)) {
5089       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5090       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5091       SelectVT = MVT::i32;
5092     }
5093 
5094     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5095                                     N->getOperand(0), LHS, RHS);
5096 
5097     if (NewVT != SelectVT)
5098       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5099     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5100     return;
5101   }
5102   case ISD::FNEG: {
5103     if (N->getValueType(0) != MVT::v2f16)
5104       break;
5105 
5106     SDLoc SL(N);
5107     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5108 
5109     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5110                              BC,
5111                              DAG.getConstant(0x80008000, SL, MVT::i32));
5112     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5113     return;
5114   }
5115   case ISD::FABS: {
5116     if (N->getValueType(0) != MVT::v2f16)
5117       break;
5118 
5119     SDLoc SL(N);
5120     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5121 
5122     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5123                              BC,
5124                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5125     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5126     return;
5127   }
5128   default:
5129     break;
5130   }
5131 }
5132 
5133 /// Helper function for LowerBRCOND
5134 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5135 
5136   SDNode *Parent = Value.getNode();
5137   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5138        I != E; ++I) {
5139 
5140     if (I.getUse().get() != Value)
5141       continue;
5142 
5143     if (I->getOpcode() == Opcode)
5144       return *I;
5145   }
5146   return nullptr;
5147 }
5148 
5149 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5150   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5151     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5152     case Intrinsic::amdgcn_if:
5153       return AMDGPUISD::IF;
5154     case Intrinsic::amdgcn_else:
5155       return AMDGPUISD::ELSE;
5156     case Intrinsic::amdgcn_loop:
5157       return AMDGPUISD::LOOP;
5158     case Intrinsic::amdgcn_end_cf:
5159       llvm_unreachable("should not occur");
5160     default:
5161       return 0;
5162     }
5163   }
5164 
5165   // break, if_break, else_break are all only used as inputs to loop, not
5166   // directly as branch conditions.
5167   return 0;
5168 }
5169 
5170 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5171   const Triple &TT = getTargetMachine().getTargetTriple();
5172   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5173           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5174          AMDGPU::shouldEmitConstantsToTextSection(TT);
5175 }
5176 
5177 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5178   // FIXME: Either avoid relying on address space here or change the default
5179   // address space for functions to avoid the explicit check.
5180   return (GV->getValueType()->isFunctionTy() ||
5181           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5182          !shouldEmitFixup(GV) &&
5183          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5184 }
5185 
5186 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5187   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5188 }
5189 
5190 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5191   if (!GV->hasExternalLinkage())
5192     return true;
5193 
5194   const auto OS = getTargetMachine().getTargetTriple().getOS();
5195   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5196 }
5197 
5198 /// This transforms the control flow intrinsics to get the branch destination as
5199 /// last parameter, also switches branch target with BR if the need arise
5200 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5201                                       SelectionDAG &DAG) const {
5202   SDLoc DL(BRCOND);
5203 
5204   SDNode *Intr = BRCOND.getOperand(1).getNode();
5205   SDValue Target = BRCOND.getOperand(2);
5206   SDNode *BR = nullptr;
5207   SDNode *SetCC = nullptr;
5208 
5209   if (Intr->getOpcode() == ISD::SETCC) {
5210     // As long as we negate the condition everything is fine
5211     SetCC = Intr;
5212     Intr = SetCC->getOperand(0).getNode();
5213 
5214   } else {
5215     // Get the target from BR if we don't negate the condition
5216     BR = findUser(BRCOND, ISD::BR);
5217     assert(BR && "brcond missing unconditional branch user");
5218     Target = BR->getOperand(1);
5219   }
5220 
5221   unsigned CFNode = isCFIntrinsic(Intr);
5222   if (CFNode == 0) {
5223     // This is a uniform branch so we don't need to legalize.
5224     return BRCOND;
5225   }
5226 
5227   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5228                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5229 
5230   assert(!SetCC ||
5231         (SetCC->getConstantOperandVal(1) == 1 &&
5232          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5233                                                              ISD::SETNE));
5234 
5235   // operands of the new intrinsic call
5236   SmallVector<SDValue, 4> Ops;
5237   if (HaveChain)
5238     Ops.push_back(BRCOND.getOperand(0));
5239 
5240   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5241   Ops.push_back(Target);
5242 
5243   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5244 
5245   // build the new intrinsic call
5246   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5247 
5248   if (!HaveChain) {
5249     SDValue Ops[] =  {
5250       SDValue(Result, 0),
5251       BRCOND.getOperand(0)
5252     };
5253 
5254     Result = DAG.getMergeValues(Ops, DL).getNode();
5255   }
5256 
5257   if (BR) {
5258     // Give the branch instruction our target
5259     SDValue Ops[] = {
5260       BR->getOperand(0),
5261       BRCOND.getOperand(2)
5262     };
5263     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5264     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5265   }
5266 
5267   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5268 
5269   // Copy the intrinsic results to registers
5270   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5271     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5272     if (!CopyToReg)
5273       continue;
5274 
5275     Chain = DAG.getCopyToReg(
5276       Chain, DL,
5277       CopyToReg->getOperand(1),
5278       SDValue(Result, i - 1),
5279       SDValue());
5280 
5281     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5282   }
5283 
5284   // Remove the old intrinsic from the chain
5285   DAG.ReplaceAllUsesOfValueWith(
5286     SDValue(Intr, Intr->getNumValues() - 1),
5287     Intr->getOperand(0));
5288 
5289   return Chain;
5290 }
5291 
5292 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5293                                           SelectionDAG &DAG) const {
5294   MVT VT = Op.getSimpleValueType();
5295   SDLoc DL(Op);
5296   // Checking the depth
5297   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5298     return DAG.getConstant(0, DL, VT);
5299 
5300   MachineFunction &MF = DAG.getMachineFunction();
5301   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5302   // Check for kernel and shader functions
5303   if (Info->isEntryFunction())
5304     return DAG.getConstant(0, DL, VT);
5305 
5306   MachineFrameInfo &MFI = MF.getFrameInfo();
5307   // There is a call to @llvm.returnaddress in this function
5308   MFI.setReturnAddressIsTaken(true);
5309 
5310   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5311   // Get the return address reg and mark it as an implicit live-in
5312   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5313 
5314   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5315 }
5316 
5317 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5318                                             SDValue Op,
5319                                             const SDLoc &DL,
5320                                             EVT VT) const {
5321   return Op.getValueType().bitsLE(VT) ?
5322       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5323     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5324                 DAG.getTargetConstant(0, DL, MVT::i32));
5325 }
5326 
5327 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5328   assert(Op.getValueType() == MVT::f16 &&
5329          "Do not know how to custom lower FP_ROUND for non-f16 type");
5330 
5331   SDValue Src = Op.getOperand(0);
5332   EVT SrcVT = Src.getValueType();
5333   if (SrcVT != MVT::f64)
5334     return Op;
5335 
5336   SDLoc DL(Op);
5337 
5338   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5339   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5340   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5341 }
5342 
5343 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5344                                                SelectionDAG &DAG) const {
5345   EVT VT = Op.getValueType();
5346   const MachineFunction &MF = DAG.getMachineFunction();
5347   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5348   bool IsIEEEMode = Info->getMode().IEEE;
5349 
5350   // FIXME: Assert during selection that this is only selected for
5351   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5352   // mode functions, but this happens to be OK since it's only done in cases
5353   // where there is known no sNaN.
5354   if (IsIEEEMode)
5355     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5356 
5357   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5358     return splitBinaryVectorOp(Op, DAG);
5359   return Op;
5360 }
5361 
5362 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5363   EVT VT = Op.getValueType();
5364   SDLoc SL(Op);
5365   SDValue LHS = Op.getOperand(0);
5366   SDValue RHS = Op.getOperand(1);
5367   bool isSigned = Op.getOpcode() == ISD::SMULO;
5368 
5369   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5370     const APInt &C = RHSC->getAPIntValue();
5371     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5372     if (C.isPowerOf2()) {
5373       // smulo(x, signed_min) is same as umulo(x, signed_min).
5374       bool UseArithShift = isSigned && !C.isMinSignedValue();
5375       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5376       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5377       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5378           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5379                       SL, VT, Result, ShiftAmt),
5380           LHS, ISD::SETNE);
5381       return DAG.getMergeValues({ Result, Overflow }, SL);
5382     }
5383   }
5384 
5385   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5386   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5387                             SL, VT, LHS, RHS);
5388 
5389   SDValue Sign = isSigned
5390     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5391                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5392     : DAG.getConstant(0, SL, VT);
5393   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5394 
5395   return DAG.getMergeValues({ Result, Overflow }, SL);
5396 }
5397 
5398 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5399   if (Op->isDivergent()) {
5400     // Select to V_MAD_[IU]64_[IU]32.
5401     return Op;
5402   }
5403   if (Subtarget->hasSMulHi()) {
5404     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5405     return SDValue();
5406   }
5407   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5408   // calculate the high part, so we might as well do the whole thing with
5409   // V_MAD_[IU]64_[IU]32.
5410   return Op;
5411 }
5412 
5413 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5414   if (!Subtarget->isTrapHandlerEnabled() ||
5415       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5416     return lowerTrapEndpgm(Op, DAG);
5417 
5418   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5419     switch (*HsaAbiVer) {
5420     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5421     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5422       return lowerTrapHsaQueuePtr(Op, DAG);
5423     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5424     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5425       return Subtarget->supportsGetDoorbellID() ?
5426           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5427     }
5428   }
5429 
5430   llvm_unreachable("Unknown trap handler");
5431 }
5432 
5433 SDValue SITargetLowering::lowerTrapEndpgm(
5434     SDValue Op, SelectionDAG &DAG) const {
5435   SDLoc SL(Op);
5436   SDValue Chain = Op.getOperand(0);
5437   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5438 }
5439 
5440 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5441     SDValue Op, SelectionDAG &DAG) const {
5442   SDLoc SL(Op);
5443   SDValue Chain = Op.getOperand(0);
5444 
5445   MachineFunction &MF = DAG.getMachineFunction();
5446   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5447   Register UserSGPR = Info->getQueuePtrUserSGPR();
5448 
5449   SDValue QueuePtr;
5450   if (UserSGPR == AMDGPU::NoRegister) {
5451     // We probably are in a function incorrectly marked with
5452     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5453     // so just use a null pointer.
5454     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5455   } else {
5456     QueuePtr = CreateLiveInRegister(
5457       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5458   }
5459 
5460   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5461   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5462                                    QueuePtr, SDValue());
5463 
5464   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5465   SDValue Ops[] = {
5466     ToReg,
5467     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5468     SGPR01,
5469     ToReg.getValue(1)
5470   };
5471   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5472 }
5473 
5474 SDValue SITargetLowering::lowerTrapHsa(
5475     SDValue Op, SelectionDAG &DAG) const {
5476   SDLoc SL(Op);
5477   SDValue Chain = Op.getOperand(0);
5478 
5479   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5480   SDValue Ops[] = {
5481     Chain,
5482     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5483   };
5484   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5485 }
5486 
5487 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5488   SDLoc SL(Op);
5489   SDValue Chain = Op.getOperand(0);
5490   MachineFunction &MF = DAG.getMachineFunction();
5491 
5492   if (!Subtarget->isTrapHandlerEnabled() ||
5493       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5494     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5495                                      "debugtrap handler not supported",
5496                                      Op.getDebugLoc(),
5497                                      DS_Warning);
5498     LLVMContext &Ctx = MF.getFunction().getContext();
5499     Ctx.diagnose(NoTrap);
5500     return Chain;
5501   }
5502 
5503   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5504   SDValue Ops[] = {
5505     Chain,
5506     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5507   };
5508   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5509 }
5510 
5511 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5512                                              SelectionDAG &DAG) const {
5513   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5514   if (Subtarget->hasApertureRegs()) {
5515     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5516         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5517         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5518     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5519         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5520         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5521     unsigned Encoding =
5522         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5523         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5524         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5525 
5526     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5527     SDValue ApertureReg = SDValue(
5528         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5529     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5530     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5531   }
5532 
5533   MachineFunction &MF = DAG.getMachineFunction();
5534   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5535   Register UserSGPR = Info->getQueuePtrUserSGPR();
5536   if (UserSGPR == AMDGPU::NoRegister) {
5537     // We probably are in a function incorrectly marked with
5538     // amdgpu-no-queue-ptr. This is undefined.
5539     return DAG.getUNDEF(MVT::i32);
5540   }
5541 
5542   SDValue QueuePtr = CreateLiveInRegister(
5543     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5544 
5545   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5546   // private_segment_aperture_base_hi.
5547   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5548 
5549   SDValue Ptr =
5550       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5551 
5552   // TODO: Use custom target PseudoSourceValue.
5553   // TODO: We should use the value from the IR intrinsic call, but it might not
5554   // be available and how do we get it?
5555   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5556   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5557                      commonAlignment(Align(64), StructOffset),
5558                      MachineMemOperand::MODereferenceable |
5559                          MachineMemOperand::MOInvariant);
5560 }
5561 
5562 /// Return true if the value is a known valid address, such that a null check is
5563 /// not necessary.
5564 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5565                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5566   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5567       isa<BasicBlockSDNode>(Val))
5568     return true;
5569 
5570   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5571     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5572 
5573   // TODO: Search through arithmetic, handle arguments and loads
5574   // marked nonnull.
5575   return false;
5576 }
5577 
5578 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5579                                              SelectionDAG &DAG) const {
5580   SDLoc SL(Op);
5581   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5582 
5583   SDValue Src = ASC->getOperand(0);
5584   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5585   unsigned SrcAS = ASC->getSrcAddressSpace();
5586 
5587   const AMDGPUTargetMachine &TM =
5588     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5589 
5590   // flat -> local/private
5591   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5592     unsigned DestAS = ASC->getDestAddressSpace();
5593 
5594     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5595         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5596       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5597 
5598       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5599         return Ptr;
5600 
5601       unsigned NullVal = TM.getNullPointerValue(DestAS);
5602       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5603       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5604 
5605       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5606                          SegmentNullPtr);
5607     }
5608   }
5609 
5610   // local/private -> flat
5611   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5612     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5613         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5614 
5615       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5616       SDValue CvtPtr =
5617           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5618       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5619 
5620       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5621         return CvtPtr;
5622 
5623       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5624       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5625 
5626       SDValue NonNull
5627         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5628 
5629       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5630                          FlatNullPtr);
5631     }
5632   }
5633 
5634   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5635       Op.getValueType() == MVT::i64) {
5636     const SIMachineFunctionInfo *Info =
5637         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5638     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5639     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5640     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5641   }
5642 
5643   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5644       Src.getValueType() == MVT::i64)
5645     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5646 
5647   // global <-> flat are no-ops and never emitted.
5648 
5649   const MachineFunction &MF = DAG.getMachineFunction();
5650   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5651     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5652   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5653 
5654   return DAG.getUNDEF(ASC->getValueType(0));
5655 }
5656 
5657 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5658 // the small vector and inserting them into the big vector. That is better than
5659 // the default expansion of doing it via a stack slot. Even though the use of
5660 // the stack slot would be optimized away afterwards, the stack slot itself
5661 // remains.
5662 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5663                                                 SelectionDAG &DAG) const {
5664   SDValue Vec = Op.getOperand(0);
5665   SDValue Ins = Op.getOperand(1);
5666   SDValue Idx = Op.getOperand(2);
5667   EVT VecVT = Vec.getValueType();
5668   EVT InsVT = Ins.getValueType();
5669   EVT EltVT = VecVT.getVectorElementType();
5670   unsigned InsNumElts = InsVT.getVectorNumElements();
5671   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5672   SDLoc SL(Op);
5673 
5674   for (unsigned I = 0; I != InsNumElts; ++I) {
5675     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5676                               DAG.getConstant(I, SL, MVT::i32));
5677     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5678                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5679   }
5680   return Vec;
5681 }
5682 
5683 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5684                                                  SelectionDAG &DAG) const {
5685   SDValue Vec = Op.getOperand(0);
5686   SDValue InsVal = Op.getOperand(1);
5687   SDValue Idx = Op.getOperand(2);
5688   EVT VecVT = Vec.getValueType();
5689   EVT EltVT = VecVT.getVectorElementType();
5690   unsigned VecSize = VecVT.getSizeInBits();
5691   unsigned EltSize = EltVT.getSizeInBits();
5692 
5693 
5694   assert(VecSize <= 64);
5695 
5696   unsigned NumElts = VecVT.getVectorNumElements();
5697   SDLoc SL(Op);
5698   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5699 
5700   if (NumElts == 4 && EltSize == 16 && KIdx) {
5701     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5702 
5703     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5704                                  DAG.getConstant(0, SL, MVT::i32));
5705     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5706                                  DAG.getConstant(1, SL, MVT::i32));
5707 
5708     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5709     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5710 
5711     unsigned Idx = KIdx->getZExtValue();
5712     bool InsertLo = Idx < 2;
5713     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5714       InsertLo ? LoVec : HiVec,
5715       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5716       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5717 
5718     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5719 
5720     SDValue Concat = InsertLo ?
5721       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5722       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5723 
5724     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5725   }
5726 
5727   if (isa<ConstantSDNode>(Idx))
5728     return SDValue();
5729 
5730   MVT IntVT = MVT::getIntegerVT(VecSize);
5731 
5732   // Avoid stack access for dynamic indexing.
5733   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5734 
5735   // Create a congruent vector with the target value in each element so that
5736   // the required element can be masked and ORed into the target vector.
5737   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5738                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5739 
5740   assert(isPowerOf2_32(EltSize));
5741   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5742 
5743   // Convert vector index to bit-index.
5744   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5745 
5746   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5747   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5748                             DAG.getConstant(0xffff, SL, IntVT),
5749                             ScaledIdx);
5750 
5751   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5752   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5753                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5754 
5755   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5756   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5757 }
5758 
5759 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5760                                                   SelectionDAG &DAG) const {
5761   SDLoc SL(Op);
5762 
5763   EVT ResultVT = Op.getValueType();
5764   SDValue Vec = Op.getOperand(0);
5765   SDValue Idx = Op.getOperand(1);
5766   EVT VecVT = Vec.getValueType();
5767   unsigned VecSize = VecVT.getSizeInBits();
5768   EVT EltVT = VecVT.getVectorElementType();
5769 
5770   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5771 
5772   // Make sure we do any optimizations that will make it easier to fold
5773   // source modifiers before obscuring it with bit operations.
5774 
5775   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5776   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5777     return Combined;
5778 
5779   if (VecSize == 128) {
5780     SDValue Lo, Hi;
5781     EVT LoVT, HiVT;
5782     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5783     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5784     Lo =
5785         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5786                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5787     Hi =
5788         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5789                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5790     EVT IdxVT = Idx.getValueType();
5791     unsigned NElem = VecVT.getVectorNumElements();
5792     assert(isPowerOf2_32(NElem));
5793     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5794     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5795     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5796     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5797   }
5798 
5799   assert(VecSize <= 64);
5800 
5801   unsigned EltSize = EltVT.getSizeInBits();
5802   assert(isPowerOf2_32(EltSize));
5803 
5804   MVT IntVT = MVT::getIntegerVT(VecSize);
5805   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5806 
5807   // Convert vector index to bit-index (* EltSize)
5808   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5809 
5810   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5811   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5812 
5813   if (ResultVT == MVT::f16) {
5814     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5815     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5816   }
5817 
5818   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5819 }
5820 
5821 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5822   assert(Elt % 2 == 0);
5823   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5824 }
5825 
5826 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5827                                               SelectionDAG &DAG) const {
5828   SDLoc SL(Op);
5829   EVT ResultVT = Op.getValueType();
5830   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5831 
5832   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5833   EVT EltVT = PackVT.getVectorElementType();
5834   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5835 
5836   // vector_shuffle <0,1,6,7> lhs, rhs
5837   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5838   //
5839   // vector_shuffle <6,7,2,3> lhs, rhs
5840   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5841   //
5842   // vector_shuffle <6,7,0,1> lhs, rhs
5843   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5844 
5845   // Avoid scalarizing when both halves are reading from consecutive elements.
5846   SmallVector<SDValue, 4> Pieces;
5847   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5848     if (elementPairIsContiguous(SVN->getMask(), I)) {
5849       const int Idx = SVN->getMaskElt(I);
5850       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5851       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5852       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5853                                     PackVT, SVN->getOperand(VecIdx),
5854                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5855       Pieces.push_back(SubVec);
5856     } else {
5857       const int Idx0 = SVN->getMaskElt(I);
5858       const int Idx1 = SVN->getMaskElt(I + 1);
5859       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5860       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5861       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5862       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5863 
5864       SDValue Vec0 = SVN->getOperand(VecIdx0);
5865       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5866                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5867 
5868       SDValue Vec1 = SVN->getOperand(VecIdx1);
5869       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5870                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5871       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5872     }
5873   }
5874 
5875   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5876 }
5877 
5878 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5879                                             SelectionDAG &DAG) const {
5880   SDLoc SL(Op);
5881   EVT VT = Op.getValueType();
5882 
5883   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5884       VT == MVT::v8i16 || VT == MVT::v8f16) {
5885     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5886                                   VT.getVectorNumElements() / 2);
5887     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5888 
5889     // Turn into pair of packed build_vectors.
5890     // TODO: Special case for constants that can be materialized with s_mov_b64.
5891     SmallVector<SDValue, 4> LoOps, HiOps;
5892     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5893       LoOps.push_back(Op.getOperand(I));
5894       HiOps.push_back(Op.getOperand(I + E));
5895     }
5896     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5897     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5898 
5899     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5900     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5901 
5902     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5903                                        { CastLo, CastHi });
5904     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5905   }
5906 
5907   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5908   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5909 
5910   SDValue Lo = Op.getOperand(0);
5911   SDValue Hi = Op.getOperand(1);
5912 
5913   // Avoid adding defined bits with the zero_extend.
5914   if (Hi.isUndef()) {
5915     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5916     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5917     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5918   }
5919 
5920   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5921   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5922 
5923   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5924                               DAG.getConstant(16, SL, MVT::i32));
5925   if (Lo.isUndef())
5926     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5927 
5928   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5929   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5930 
5931   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5932   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5933 }
5934 
5935 bool
5936 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5937   // We can fold offsets for anything that doesn't require a GOT relocation.
5938   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5939           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5940           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5941          !shouldEmitGOTReloc(GA->getGlobal());
5942 }
5943 
5944 static SDValue
5945 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5946                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5947                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5948   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5949   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5950   // lowered to the following code sequence:
5951   //
5952   // For constant address space:
5953   //   s_getpc_b64 s[0:1]
5954   //   s_add_u32 s0, s0, $symbol
5955   //   s_addc_u32 s1, s1, 0
5956   //
5957   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5958   //   a fixup or relocation is emitted to replace $symbol with a literal
5959   //   constant, which is a pc-relative offset from the encoding of the $symbol
5960   //   operand to the global variable.
5961   //
5962   // For global address space:
5963   //   s_getpc_b64 s[0:1]
5964   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5965   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5966   //
5967   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5968   //   fixups or relocations are emitted to replace $symbol@*@lo and
5969   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5970   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5971   //   operand to the global variable.
5972   //
5973   // What we want here is an offset from the value returned by s_getpc
5974   // (which is the address of the s_add_u32 instruction) to the global
5975   // variable, but since the encoding of $symbol starts 4 bytes after the start
5976   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5977   // small. This requires us to add 4 to the global variable offset in order to
5978   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5979   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5980   // instruction.
5981   SDValue PtrLo =
5982       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5983   SDValue PtrHi;
5984   if (GAFlags == SIInstrInfo::MO_NONE) {
5985     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5986   } else {
5987     PtrHi =
5988         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5989   }
5990   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5991 }
5992 
5993 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5994                                              SDValue Op,
5995                                              SelectionDAG &DAG) const {
5996   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5997   SDLoc DL(GSD);
5998   EVT PtrVT = Op.getValueType();
5999 
6000   const GlobalValue *GV = GSD->getGlobal();
6001   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6002        shouldUseLDSConstAddress(GV)) ||
6003       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6004       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6005     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6006         GV->hasExternalLinkage()) {
6007       Type *Ty = GV->getValueType();
6008       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6009       // zero-sized type in other languages to declare the dynamic shared
6010       // memory which size is not known at the compile time. They will be
6011       // allocated by the runtime and placed directly after the static
6012       // allocated ones. They all share the same offset.
6013       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6014         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6015         // Adjust alignment for that dynamic shared memory array.
6016         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6017         return SDValue(
6018             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6019       }
6020     }
6021     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6022   }
6023 
6024   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6025     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6026                                             SIInstrInfo::MO_ABS32_LO);
6027     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6028   }
6029 
6030   if (shouldEmitFixup(GV))
6031     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6032   else if (shouldEmitPCReloc(GV))
6033     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6034                                    SIInstrInfo::MO_REL32);
6035 
6036   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6037                                             SIInstrInfo::MO_GOTPCREL32);
6038 
6039   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6040   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6041   const DataLayout &DataLayout = DAG.getDataLayout();
6042   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6043   MachinePointerInfo PtrInfo
6044     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6045 
6046   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6047                      MachineMemOperand::MODereferenceable |
6048                          MachineMemOperand::MOInvariant);
6049 }
6050 
6051 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6052                                    const SDLoc &DL, SDValue V) const {
6053   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6054   // the destination register.
6055   //
6056   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6057   // so we will end up with redundant moves to m0.
6058   //
6059   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6060 
6061   // A Null SDValue creates a glue result.
6062   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6063                                   V, Chain);
6064   return SDValue(M0, 0);
6065 }
6066 
6067 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6068                                                  SDValue Op,
6069                                                  MVT VT,
6070                                                  unsigned Offset) const {
6071   SDLoc SL(Op);
6072   SDValue Param = lowerKernargMemParameter(
6073       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6074   // The local size values will have the hi 16-bits as zero.
6075   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6076                      DAG.getValueType(VT));
6077 }
6078 
6079 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6080                                         EVT VT) {
6081   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6082                                       "non-hsa intrinsic with hsa target",
6083                                       DL.getDebugLoc());
6084   DAG.getContext()->diagnose(BadIntrin);
6085   return DAG.getUNDEF(VT);
6086 }
6087 
6088 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6089                                          EVT VT) {
6090   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6091                                       "intrinsic not supported on subtarget",
6092                                       DL.getDebugLoc());
6093   DAG.getContext()->diagnose(BadIntrin);
6094   return DAG.getUNDEF(VT);
6095 }
6096 
6097 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6098                                     ArrayRef<SDValue> Elts) {
6099   assert(!Elts.empty());
6100   MVT Type;
6101   unsigned NumElts = Elts.size();
6102 
6103   if (NumElts <= 8) {
6104     Type = MVT::getVectorVT(MVT::f32, NumElts);
6105   } else {
6106     assert(Elts.size() <= 16);
6107     Type = MVT::v16f32;
6108     NumElts = 16;
6109   }
6110 
6111   SmallVector<SDValue, 16> VecElts(NumElts);
6112   for (unsigned i = 0; i < Elts.size(); ++i) {
6113     SDValue Elt = Elts[i];
6114     if (Elt.getValueType() != MVT::f32)
6115       Elt = DAG.getBitcast(MVT::f32, Elt);
6116     VecElts[i] = Elt;
6117   }
6118   for (unsigned i = Elts.size(); i < NumElts; ++i)
6119     VecElts[i] = DAG.getUNDEF(MVT::f32);
6120 
6121   if (NumElts == 1)
6122     return VecElts[0];
6123   return DAG.getBuildVector(Type, DL, VecElts);
6124 }
6125 
6126 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6127                               SDValue Src, int ExtraElts) {
6128   EVT SrcVT = Src.getValueType();
6129 
6130   SmallVector<SDValue, 8> Elts;
6131 
6132   if (SrcVT.isVector())
6133     DAG.ExtractVectorElements(Src, Elts);
6134   else
6135     Elts.push_back(Src);
6136 
6137   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6138   while (ExtraElts--)
6139     Elts.push_back(Undef);
6140 
6141   return DAG.getBuildVector(CastVT, DL, Elts);
6142 }
6143 
6144 // Re-construct the required return value for a image load intrinsic.
6145 // This is more complicated due to the optional use TexFailCtrl which means the required
6146 // return type is an aggregate
6147 static SDValue constructRetValue(SelectionDAG &DAG,
6148                                  MachineSDNode *Result,
6149                                  ArrayRef<EVT> ResultTypes,
6150                                  bool IsTexFail, bool Unpacked, bool IsD16,
6151                                  int DMaskPop, int NumVDataDwords,
6152                                  const SDLoc &DL) {
6153   // Determine the required return type. This is the same regardless of IsTexFail flag
6154   EVT ReqRetVT = ResultTypes[0];
6155   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6156   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6157     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6158 
6159   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6160     DMaskPop : (DMaskPop + 1) / 2;
6161 
6162   MVT DataDwordVT = NumDataDwords == 1 ?
6163     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6164 
6165   MVT MaskPopVT = MaskPopDwords == 1 ?
6166     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6167 
6168   SDValue Data(Result, 0);
6169   SDValue TexFail;
6170 
6171   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6172     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6173     if (MaskPopVT.isVector()) {
6174       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6175                          SDValue(Result, 0), ZeroIdx);
6176     } else {
6177       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6178                          SDValue(Result, 0), ZeroIdx);
6179     }
6180   }
6181 
6182   if (DataDwordVT.isVector())
6183     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6184                           NumDataDwords - MaskPopDwords);
6185 
6186   if (IsD16)
6187     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6188 
6189   EVT LegalReqRetVT = ReqRetVT;
6190   if (!ReqRetVT.isVector()) {
6191     if (!Data.getValueType().isInteger())
6192       Data = DAG.getNode(ISD::BITCAST, DL,
6193                          Data.getValueType().changeTypeToInteger(), Data);
6194     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6195   } else {
6196     // We need to widen the return vector to a legal type
6197     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6198         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6199       LegalReqRetVT =
6200           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6201                            ReqRetVT.getVectorNumElements() + 1);
6202     }
6203   }
6204   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6205 
6206   if (IsTexFail) {
6207     TexFail =
6208         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6209                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6210 
6211     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6212   }
6213 
6214   if (Result->getNumValues() == 1)
6215     return Data;
6216 
6217   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6218 }
6219 
6220 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6221                          SDValue *LWE, bool &IsTexFail) {
6222   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6223 
6224   uint64_t Value = TexFailCtrlConst->getZExtValue();
6225   if (Value) {
6226     IsTexFail = true;
6227   }
6228 
6229   SDLoc DL(TexFailCtrlConst);
6230   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6231   Value &= ~(uint64_t)0x1;
6232   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6233   Value &= ~(uint64_t)0x2;
6234 
6235   return Value == 0;
6236 }
6237 
6238 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6239                                       MVT PackVectorVT,
6240                                       SmallVectorImpl<SDValue> &PackedAddrs,
6241                                       unsigned DimIdx, unsigned EndIdx,
6242                                       unsigned NumGradients) {
6243   SDLoc DL(Op);
6244   for (unsigned I = DimIdx; I < EndIdx; I++) {
6245     SDValue Addr = Op.getOperand(I);
6246 
6247     // Gradients are packed with undef for each coordinate.
6248     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6249     // 1D: undef,dx/dh; undef,dx/dv
6250     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6251     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6252     if (((I + 1) >= EndIdx) ||
6253         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6254                                          I == DimIdx + NumGradients - 1))) {
6255       if (Addr.getValueType() != MVT::i16)
6256         Addr = DAG.getBitcast(MVT::i16, Addr);
6257       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6258     } else {
6259       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6260       I++;
6261     }
6262     Addr = DAG.getBitcast(MVT::f32, Addr);
6263     PackedAddrs.push_back(Addr);
6264   }
6265 }
6266 
6267 SDValue SITargetLowering::lowerImage(SDValue Op,
6268                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6269                                      SelectionDAG &DAG, bool WithChain) const {
6270   SDLoc DL(Op);
6271   MachineFunction &MF = DAG.getMachineFunction();
6272   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6273   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6274       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6275   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6276   unsigned IntrOpcode = Intr->BaseOpcode;
6277   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6278 
6279   SmallVector<EVT, 3> ResultTypes(Op->values());
6280   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6281   bool IsD16 = false;
6282   bool IsG16 = false;
6283   bool IsA16 = false;
6284   SDValue VData;
6285   int NumVDataDwords;
6286   bool AdjustRetType = false;
6287 
6288   // Offset of intrinsic arguments
6289   const unsigned ArgOffset = WithChain ? 2 : 1;
6290 
6291   unsigned DMask;
6292   unsigned DMaskLanes = 0;
6293 
6294   if (BaseOpcode->Atomic) {
6295     VData = Op.getOperand(2);
6296 
6297     bool Is64Bit = VData.getValueType() == MVT::i64;
6298     if (BaseOpcode->AtomicX2) {
6299       SDValue VData2 = Op.getOperand(3);
6300       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6301                                  {VData, VData2});
6302       if (Is64Bit)
6303         VData = DAG.getBitcast(MVT::v4i32, VData);
6304 
6305       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6306       DMask = Is64Bit ? 0xf : 0x3;
6307       NumVDataDwords = Is64Bit ? 4 : 2;
6308     } else {
6309       DMask = Is64Bit ? 0x3 : 0x1;
6310       NumVDataDwords = Is64Bit ? 2 : 1;
6311     }
6312   } else {
6313     auto *DMaskConst =
6314         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6315     DMask = DMaskConst->getZExtValue();
6316     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6317 
6318     if (BaseOpcode->Store) {
6319       VData = Op.getOperand(2);
6320 
6321       MVT StoreVT = VData.getSimpleValueType();
6322       if (StoreVT.getScalarType() == MVT::f16) {
6323         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6324           return Op; // D16 is unsupported for this instruction
6325 
6326         IsD16 = true;
6327         VData = handleD16VData(VData, DAG, true);
6328       }
6329 
6330       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6331     } else {
6332       // Work out the num dwords based on the dmask popcount and underlying type
6333       // and whether packing is supported.
6334       MVT LoadVT = ResultTypes[0].getSimpleVT();
6335       if (LoadVT.getScalarType() == MVT::f16) {
6336         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6337           return Op; // D16 is unsupported for this instruction
6338 
6339         IsD16 = true;
6340       }
6341 
6342       // Confirm that the return type is large enough for the dmask specified
6343       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6344           (!LoadVT.isVector() && DMaskLanes > 1))
6345           return Op;
6346 
6347       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6348       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6349       // instructions.
6350       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6351           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6352         NumVDataDwords = (DMaskLanes + 1) / 2;
6353       else
6354         NumVDataDwords = DMaskLanes;
6355 
6356       AdjustRetType = true;
6357     }
6358   }
6359 
6360   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6361   SmallVector<SDValue, 4> VAddrs;
6362 
6363   // Check for 16 bit addresses or derivatives and pack if true.
6364   MVT VAddrVT =
6365       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6366   MVT VAddrScalarVT = VAddrVT.getScalarType();
6367   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6368   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6369 
6370   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6371   VAddrScalarVT = VAddrVT.getScalarType();
6372   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6373   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6374 
6375   // Push back extra arguments.
6376   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6377     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6378       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6379       // Special handling of bias when A16 is on. Bias is of type half but
6380       // occupies full 32-bit.
6381       SDValue Bias = DAG.getBuildVector(
6382           MVT::v2f16, DL,
6383           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6384       VAddrs.push_back(Bias);
6385     } else {
6386       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6387              "Bias needs to be converted to 16 bit in A16 mode");
6388       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6389     }
6390   }
6391 
6392   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6393     // 16 bit gradients are supported, but are tied to the A16 control
6394     // so both gradients and addresses must be 16 bit
6395     LLVM_DEBUG(
6396         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6397                   "require 16 bit args for both gradients and addresses");
6398     return Op;
6399   }
6400 
6401   if (IsA16) {
6402     if (!ST->hasA16()) {
6403       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6404                            "support 16 bit addresses\n");
6405       return Op;
6406     }
6407   }
6408 
6409   // We've dealt with incorrect input so we know that if IsA16, IsG16
6410   // are set then we have to compress/pack operands (either address,
6411   // gradient or both)
6412   // In the case where a16 and gradients are tied (no G16 support) then we
6413   // have already verified that both IsA16 and IsG16 are true
6414   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6415     // Activate g16
6416     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6417         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6418     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6419   }
6420 
6421   // Add gradients (packed or unpacked)
6422   if (IsG16) {
6423     // Pack the gradients
6424     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6425     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6426                               ArgOffset + Intr->GradientStart,
6427                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6428   } else {
6429     for (unsigned I = ArgOffset + Intr->GradientStart;
6430          I < ArgOffset + Intr->CoordStart; I++)
6431       VAddrs.push_back(Op.getOperand(I));
6432   }
6433 
6434   // Add addresses (packed or unpacked)
6435   if (IsA16) {
6436     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6437                               ArgOffset + Intr->CoordStart, VAddrEnd,
6438                               0 /* No gradients */);
6439   } else {
6440     // Add uncompressed address
6441     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6442       VAddrs.push_back(Op.getOperand(I));
6443   }
6444 
6445   // If the register allocator cannot place the address registers contiguously
6446   // without introducing moves, then using the non-sequential address encoding
6447   // is always preferable, since it saves VALU instructions and is usually a
6448   // wash in terms of code size or even better.
6449   //
6450   // However, we currently have no way of hinting to the register allocator that
6451   // MIMG addresses should be placed contiguously when it is possible to do so,
6452   // so force non-NSA for the common 2-address case as a heuristic.
6453   //
6454   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6455   // allocation when possible.
6456   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6457                 VAddrs.size() >= 3 &&
6458                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6459   SDValue VAddr;
6460   if (!UseNSA)
6461     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6462 
6463   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6464   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6465   SDValue Unorm;
6466   if (!BaseOpcode->Sampler) {
6467     Unorm = True;
6468   } else {
6469     auto UnormConst =
6470         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6471 
6472     Unorm = UnormConst->getZExtValue() ? True : False;
6473   }
6474 
6475   SDValue TFE;
6476   SDValue LWE;
6477   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6478   bool IsTexFail = false;
6479   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6480     return Op;
6481 
6482   if (IsTexFail) {
6483     if (!DMaskLanes) {
6484       // Expecting to get an error flag since TFC is on - and dmask is 0
6485       // Force dmask to be at least 1 otherwise the instruction will fail
6486       DMask = 0x1;
6487       DMaskLanes = 1;
6488       NumVDataDwords = 1;
6489     }
6490     NumVDataDwords += 1;
6491     AdjustRetType = true;
6492   }
6493 
6494   // Has something earlier tagged that the return type needs adjusting
6495   // This happens if the instruction is a load or has set TexFailCtrl flags
6496   if (AdjustRetType) {
6497     // NumVDataDwords reflects the true number of dwords required in the return type
6498     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6499       // This is a no-op load. This can be eliminated
6500       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6501       if (isa<MemSDNode>(Op))
6502         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6503       return Undef;
6504     }
6505 
6506     EVT NewVT = NumVDataDwords > 1 ?
6507                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6508                 : MVT::i32;
6509 
6510     ResultTypes[0] = NewVT;
6511     if (ResultTypes.size() == 3) {
6512       // Original result was aggregate type used for TexFailCtrl results
6513       // The actual instruction returns as a vector type which has now been
6514       // created. Remove the aggregate result.
6515       ResultTypes.erase(&ResultTypes[1]);
6516     }
6517   }
6518 
6519   unsigned CPol = cast<ConstantSDNode>(
6520       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6521   if (BaseOpcode->Atomic)
6522     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6523   if (CPol & ~AMDGPU::CPol::ALL)
6524     return Op;
6525 
6526   SmallVector<SDValue, 26> Ops;
6527   if (BaseOpcode->Store || BaseOpcode->Atomic)
6528     Ops.push_back(VData); // vdata
6529   if (UseNSA)
6530     append_range(Ops, VAddrs);
6531   else
6532     Ops.push_back(VAddr);
6533   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6534   if (BaseOpcode->Sampler)
6535     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6536   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6537   if (IsGFX10Plus)
6538     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6539   Ops.push_back(Unorm);
6540   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6541   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6542                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6543   if (IsGFX10Plus)
6544     Ops.push_back(IsA16 ? True : False);
6545   if (!Subtarget->hasGFX90AInsts()) {
6546     Ops.push_back(TFE); //tfe
6547   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6548     report_fatal_error("TFE is not supported on this GPU");
6549   }
6550   Ops.push_back(LWE); // lwe
6551   if (!IsGFX10Plus)
6552     Ops.push_back(DimInfo->DA ? True : False);
6553   if (BaseOpcode->HasD16)
6554     Ops.push_back(IsD16 ? True : False);
6555   if (isa<MemSDNode>(Op))
6556     Ops.push_back(Op.getOperand(0)); // chain
6557 
6558   int NumVAddrDwords =
6559       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6560   int Opcode = -1;
6561 
6562   if (IsGFX10Plus) {
6563     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6564                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6565                                           : AMDGPU::MIMGEncGfx10Default,
6566                                    NumVDataDwords, NumVAddrDwords);
6567   } else {
6568     if (Subtarget->hasGFX90AInsts()) {
6569       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6570                                      NumVDataDwords, NumVAddrDwords);
6571       if (Opcode == -1)
6572         report_fatal_error(
6573             "requested image instruction is not supported on this GPU");
6574     }
6575     if (Opcode == -1 &&
6576         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6577       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6578                                      NumVDataDwords, NumVAddrDwords);
6579     if (Opcode == -1)
6580       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6581                                      NumVDataDwords, NumVAddrDwords);
6582   }
6583   assert(Opcode != -1);
6584 
6585   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6586   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6587     MachineMemOperand *MemRef = MemOp->getMemOperand();
6588     DAG.setNodeMemRefs(NewNode, {MemRef});
6589   }
6590 
6591   if (BaseOpcode->AtomicX2) {
6592     SmallVector<SDValue, 1> Elt;
6593     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6594     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6595   }
6596   if (BaseOpcode->Store)
6597     return SDValue(NewNode, 0);
6598   return constructRetValue(DAG, NewNode,
6599                            OrigResultTypes, IsTexFail,
6600                            Subtarget->hasUnpackedD16VMem(), IsD16,
6601                            DMaskLanes, NumVDataDwords, DL);
6602 }
6603 
6604 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6605                                        SDValue Offset, SDValue CachePolicy,
6606                                        SelectionDAG &DAG) const {
6607   MachineFunction &MF = DAG.getMachineFunction();
6608 
6609   const DataLayout &DataLayout = DAG.getDataLayout();
6610   Align Alignment =
6611       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6612 
6613   MachineMemOperand *MMO = MF.getMachineMemOperand(
6614       MachinePointerInfo(),
6615       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6616           MachineMemOperand::MOInvariant,
6617       VT.getStoreSize(), Alignment);
6618 
6619   if (!Offset->isDivergent()) {
6620     SDValue Ops[] = {
6621         Rsrc,
6622         Offset, // Offset
6623         CachePolicy
6624     };
6625 
6626     // Widen vec3 load to vec4.
6627     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6628       EVT WidenedVT =
6629           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6630       auto WidenedOp = DAG.getMemIntrinsicNode(
6631           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6632           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6633       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6634                                    DAG.getVectorIdxConstant(0, DL));
6635       return Subvector;
6636     }
6637 
6638     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6639                                    DAG.getVTList(VT), Ops, VT, MMO);
6640   }
6641 
6642   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6643   // assume that the buffer is unswizzled.
6644   SmallVector<SDValue, 4> Loads;
6645   unsigned NumLoads = 1;
6646   MVT LoadVT = VT.getSimpleVT();
6647   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6648   assert((LoadVT.getScalarType() == MVT::i32 ||
6649           LoadVT.getScalarType() == MVT::f32));
6650 
6651   if (NumElts == 8 || NumElts == 16) {
6652     NumLoads = NumElts / 4;
6653     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6654   }
6655 
6656   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6657   SDValue Ops[] = {
6658       DAG.getEntryNode(),                               // Chain
6659       Rsrc,                                             // rsrc
6660       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6661       {},                                               // voffset
6662       {},                                               // soffset
6663       {},                                               // offset
6664       CachePolicy,                                      // cachepolicy
6665       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6666   };
6667 
6668   // Use the alignment to ensure that the required offsets will fit into the
6669   // immediate offsets.
6670   setBufferOffsets(Offset, DAG, &Ops[3],
6671                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6672 
6673   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6674   for (unsigned i = 0; i < NumLoads; ++i) {
6675     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6676     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6677                                         LoadVT, MMO, DAG));
6678   }
6679 
6680   if (NumElts == 8 || NumElts == 16)
6681     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6682 
6683   return Loads[0];
6684 }
6685 
6686 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6687                                                   SelectionDAG &DAG) const {
6688   MachineFunction &MF = DAG.getMachineFunction();
6689   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6690 
6691   EVT VT = Op.getValueType();
6692   SDLoc DL(Op);
6693   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6694 
6695   // TODO: Should this propagate fast-math-flags?
6696 
6697   switch (IntrinsicID) {
6698   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6699     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6700       return emitNonHSAIntrinsicError(DAG, DL, VT);
6701     return getPreloadedValue(DAG, *MFI, VT,
6702                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6703   }
6704   case Intrinsic::amdgcn_dispatch_ptr:
6705   case Intrinsic::amdgcn_queue_ptr: {
6706     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6707       DiagnosticInfoUnsupported BadIntrin(
6708           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6709           DL.getDebugLoc());
6710       DAG.getContext()->diagnose(BadIntrin);
6711       return DAG.getUNDEF(VT);
6712     }
6713 
6714     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6715       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6716     return getPreloadedValue(DAG, *MFI, VT, RegID);
6717   }
6718   case Intrinsic::amdgcn_implicitarg_ptr: {
6719     if (MFI->isEntryFunction())
6720       return getImplicitArgPtr(DAG, DL);
6721     return getPreloadedValue(DAG, *MFI, VT,
6722                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6723   }
6724   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6725     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6726       // This only makes sense to call in a kernel, so just lower to null.
6727       return DAG.getConstant(0, DL, VT);
6728     }
6729 
6730     return getPreloadedValue(DAG, *MFI, VT,
6731                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6732   }
6733   case Intrinsic::amdgcn_dispatch_id: {
6734     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6735   }
6736   case Intrinsic::amdgcn_rcp:
6737     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6738   case Intrinsic::amdgcn_rsq:
6739     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6740   case Intrinsic::amdgcn_rsq_legacy:
6741     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6742       return emitRemovedIntrinsicError(DAG, DL, VT);
6743     return SDValue();
6744   case Intrinsic::amdgcn_rcp_legacy:
6745     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6746       return emitRemovedIntrinsicError(DAG, DL, VT);
6747     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6748   case Intrinsic::amdgcn_rsq_clamp: {
6749     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6750       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6751 
6752     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6753     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6754     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6755 
6756     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6757     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6758                               DAG.getConstantFP(Max, DL, VT));
6759     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6760                        DAG.getConstantFP(Min, DL, VT));
6761   }
6762   case Intrinsic::r600_read_ngroups_x:
6763     if (Subtarget->isAmdHsaOS())
6764       return emitNonHSAIntrinsicError(DAG, DL, VT);
6765 
6766     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6767                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6768                                     false);
6769   case Intrinsic::r600_read_ngroups_y:
6770     if (Subtarget->isAmdHsaOS())
6771       return emitNonHSAIntrinsicError(DAG, DL, VT);
6772 
6773     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6774                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6775                                     false);
6776   case Intrinsic::r600_read_ngroups_z:
6777     if (Subtarget->isAmdHsaOS())
6778       return emitNonHSAIntrinsicError(DAG, DL, VT);
6779 
6780     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6781                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6782                                     false);
6783   case Intrinsic::r600_read_global_size_x:
6784     if (Subtarget->isAmdHsaOS())
6785       return emitNonHSAIntrinsicError(DAG, DL, VT);
6786 
6787     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6788                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6789                                     Align(4), false);
6790   case Intrinsic::r600_read_global_size_y:
6791     if (Subtarget->isAmdHsaOS())
6792       return emitNonHSAIntrinsicError(DAG, DL, VT);
6793 
6794     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6795                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6796                                     Align(4), false);
6797   case Intrinsic::r600_read_global_size_z:
6798     if (Subtarget->isAmdHsaOS())
6799       return emitNonHSAIntrinsicError(DAG, DL, VT);
6800 
6801     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6802                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6803                                     Align(4), false);
6804   case Intrinsic::r600_read_local_size_x:
6805     if (Subtarget->isAmdHsaOS())
6806       return emitNonHSAIntrinsicError(DAG, DL, VT);
6807 
6808     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6809                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6810   case Intrinsic::r600_read_local_size_y:
6811     if (Subtarget->isAmdHsaOS())
6812       return emitNonHSAIntrinsicError(DAG, DL, VT);
6813 
6814     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6815                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6816   case Intrinsic::r600_read_local_size_z:
6817     if (Subtarget->isAmdHsaOS())
6818       return emitNonHSAIntrinsicError(DAG, DL, VT);
6819 
6820     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6821                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6822   case Intrinsic::amdgcn_workgroup_id_x:
6823     return getPreloadedValue(DAG, *MFI, VT,
6824                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6825   case Intrinsic::amdgcn_workgroup_id_y:
6826     return getPreloadedValue(DAG, *MFI, VT,
6827                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6828   case Intrinsic::amdgcn_workgroup_id_z:
6829     return getPreloadedValue(DAG, *MFI, VT,
6830                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6831   case Intrinsic::amdgcn_workitem_id_x:
6832     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6833       return DAG.getConstant(0, DL, MVT::i32);
6834 
6835     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6836                           SDLoc(DAG.getEntryNode()),
6837                           MFI->getArgInfo().WorkItemIDX);
6838   case Intrinsic::amdgcn_workitem_id_y:
6839     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6840       return DAG.getConstant(0, DL, MVT::i32);
6841 
6842     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6843                           SDLoc(DAG.getEntryNode()),
6844                           MFI->getArgInfo().WorkItemIDY);
6845   case Intrinsic::amdgcn_workitem_id_z:
6846     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6847       return DAG.getConstant(0, DL, MVT::i32);
6848 
6849     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6850                           SDLoc(DAG.getEntryNode()),
6851                           MFI->getArgInfo().WorkItemIDZ);
6852   case Intrinsic::amdgcn_wavefrontsize:
6853     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6854                            SDLoc(Op), MVT::i32);
6855   case Intrinsic::amdgcn_s_buffer_load: {
6856     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6857     if (CPol & ~AMDGPU::CPol::ALL)
6858       return Op;
6859     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6860                         DAG);
6861   }
6862   case Intrinsic::amdgcn_fdiv_fast:
6863     return lowerFDIV_FAST(Op, DAG);
6864   case Intrinsic::amdgcn_sin:
6865     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6866 
6867   case Intrinsic::amdgcn_cos:
6868     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6869 
6870   case Intrinsic::amdgcn_mul_u24:
6871     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6872   case Intrinsic::amdgcn_mul_i24:
6873     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6874 
6875   case Intrinsic::amdgcn_log_clamp: {
6876     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6877       return SDValue();
6878 
6879     return emitRemovedIntrinsicError(DAG, DL, VT);
6880   }
6881   case Intrinsic::amdgcn_ldexp:
6882     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6883                        Op.getOperand(1), Op.getOperand(2));
6884 
6885   case Intrinsic::amdgcn_fract:
6886     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6887 
6888   case Intrinsic::amdgcn_class:
6889     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6890                        Op.getOperand(1), Op.getOperand(2));
6891   case Intrinsic::amdgcn_div_fmas:
6892     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6893                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6894                        Op.getOperand(4));
6895 
6896   case Intrinsic::amdgcn_div_fixup:
6897     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6898                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6899 
6900   case Intrinsic::amdgcn_div_scale: {
6901     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6902 
6903     // Translate to the operands expected by the machine instruction. The
6904     // first parameter must be the same as the first instruction.
6905     SDValue Numerator = Op.getOperand(1);
6906     SDValue Denominator = Op.getOperand(2);
6907 
6908     // Note this order is opposite of the machine instruction's operations,
6909     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6910     // intrinsic has the numerator as the first operand to match a normal
6911     // division operation.
6912 
6913     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6914 
6915     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6916                        Denominator, Numerator);
6917   }
6918   case Intrinsic::amdgcn_icmp: {
6919     // There is a Pat that handles this variant, so return it as-is.
6920     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6921         Op.getConstantOperandVal(2) == 0 &&
6922         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6923       return Op;
6924     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6925   }
6926   case Intrinsic::amdgcn_fcmp: {
6927     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6928   }
6929   case Intrinsic::amdgcn_ballot:
6930     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6931   case Intrinsic::amdgcn_fmed3:
6932     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6933                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6934   case Intrinsic::amdgcn_fdot2:
6935     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6936                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6937                        Op.getOperand(4));
6938   case Intrinsic::amdgcn_fmul_legacy:
6939     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6940                        Op.getOperand(1), Op.getOperand(2));
6941   case Intrinsic::amdgcn_sffbh:
6942     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6943   case Intrinsic::amdgcn_sbfe:
6944     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6945                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6946   case Intrinsic::amdgcn_ubfe:
6947     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6948                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6949   case Intrinsic::amdgcn_cvt_pkrtz:
6950   case Intrinsic::amdgcn_cvt_pknorm_i16:
6951   case Intrinsic::amdgcn_cvt_pknorm_u16:
6952   case Intrinsic::amdgcn_cvt_pk_i16:
6953   case Intrinsic::amdgcn_cvt_pk_u16: {
6954     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6955     EVT VT = Op.getValueType();
6956     unsigned Opcode;
6957 
6958     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6959       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6960     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6961       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6962     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6963       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6964     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6965       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6966     else
6967       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6968 
6969     if (isTypeLegal(VT))
6970       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6971 
6972     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6973                                Op.getOperand(1), Op.getOperand(2));
6974     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6975   }
6976   case Intrinsic::amdgcn_fmad_ftz:
6977     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6978                        Op.getOperand(2), Op.getOperand(3));
6979 
6980   case Intrinsic::amdgcn_if_break:
6981     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6982                                       Op->getOperand(1), Op->getOperand(2)), 0);
6983 
6984   case Intrinsic::amdgcn_groupstaticsize: {
6985     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6986     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6987       return Op;
6988 
6989     const Module *M = MF.getFunction().getParent();
6990     const GlobalValue *GV =
6991         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6992     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6993                                             SIInstrInfo::MO_ABS32_LO);
6994     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6995   }
6996   case Intrinsic::amdgcn_is_shared:
6997   case Intrinsic::amdgcn_is_private: {
6998     SDLoc SL(Op);
6999     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7000       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7001     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7002     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7003                                  Op.getOperand(1));
7004 
7005     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7006                                 DAG.getConstant(1, SL, MVT::i32));
7007     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7008   }
7009   case Intrinsic::amdgcn_perm:
7010     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7011                        Op.getOperand(2), Op.getOperand(3));
7012   case Intrinsic::amdgcn_reloc_constant: {
7013     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7014     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7015     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7016     auto RelocSymbol = cast<GlobalVariable>(
7017         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7018     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7019                                             SIInstrInfo::MO_ABS32_LO);
7020     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7021   }
7022   default:
7023     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7024             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7025       return lowerImage(Op, ImageDimIntr, DAG, false);
7026 
7027     return Op;
7028   }
7029 }
7030 
7031 /// Update \p MMO based on the offset inputs to an intrinsic.
7032 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7033                             SDValue SOffset, SDValue Offset,
7034                             SDValue VIndex = SDValue()) {
7035   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7036       !isa<ConstantSDNode>(Offset)) {
7037     // The combined offset is not known to be constant, so we cannot represent
7038     // it in the MMO. Give up.
7039     MMO->setValue((Value *)nullptr);
7040     return;
7041   }
7042 
7043   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7044                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7045     // The strided index component of the address is not known to be zero, so we
7046     // cannot represent it in the MMO. Give up.
7047     MMO->setValue((Value *)nullptr);
7048     return;
7049   }
7050 
7051   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7052                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7053                  cast<ConstantSDNode>(Offset)->getSExtValue());
7054 }
7055 
7056 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7057                                                      SelectionDAG &DAG,
7058                                                      unsigned NewOpcode) const {
7059   SDLoc DL(Op);
7060 
7061   SDValue VData = Op.getOperand(2);
7062   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7063   SDValue Ops[] = {
7064     Op.getOperand(0), // Chain
7065     VData,            // vdata
7066     Op.getOperand(3), // rsrc
7067     DAG.getConstant(0, DL, MVT::i32), // vindex
7068     Offsets.first,    // voffset
7069     Op.getOperand(5), // soffset
7070     Offsets.second,   // offset
7071     Op.getOperand(6), // cachepolicy
7072     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7073   };
7074 
7075   auto *M = cast<MemSDNode>(Op);
7076   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7077 
7078   EVT MemVT = VData.getValueType();
7079   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7080                                  M->getMemOperand());
7081 }
7082 
7083 // Return a value to use for the idxen operand by examining the vindex operand.
7084 static unsigned getIdxEn(SDValue VIndex) {
7085   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7086     // No need to set idxen if vindex is known to be zero.
7087     return VIndexC->getZExtValue() != 0;
7088   return 1;
7089 }
7090 
7091 SDValue
7092 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7093                                                 unsigned NewOpcode) const {
7094   SDLoc DL(Op);
7095 
7096   SDValue VData = Op.getOperand(2);
7097   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7098   SDValue Ops[] = {
7099     Op.getOperand(0), // Chain
7100     VData,            // vdata
7101     Op.getOperand(3), // rsrc
7102     Op.getOperand(4), // vindex
7103     Offsets.first,    // voffset
7104     Op.getOperand(6), // soffset
7105     Offsets.second,   // offset
7106     Op.getOperand(7), // cachepolicy
7107     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7108   };
7109 
7110   auto *M = cast<MemSDNode>(Op);
7111   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7112 
7113   EVT MemVT = VData.getValueType();
7114   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7115                                  M->getMemOperand());
7116 }
7117 
7118 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7119                                                  SelectionDAG &DAG) const {
7120   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7121   SDLoc DL(Op);
7122 
7123   switch (IntrID) {
7124   case Intrinsic::amdgcn_ds_ordered_add:
7125   case Intrinsic::amdgcn_ds_ordered_swap: {
7126     MemSDNode *M = cast<MemSDNode>(Op);
7127     SDValue Chain = M->getOperand(0);
7128     SDValue M0 = M->getOperand(2);
7129     SDValue Value = M->getOperand(3);
7130     unsigned IndexOperand = M->getConstantOperandVal(7);
7131     unsigned WaveRelease = M->getConstantOperandVal(8);
7132     unsigned WaveDone = M->getConstantOperandVal(9);
7133 
7134     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7135     IndexOperand &= ~0x3f;
7136     unsigned CountDw = 0;
7137 
7138     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7139       CountDw = (IndexOperand >> 24) & 0xf;
7140       IndexOperand &= ~(0xf << 24);
7141 
7142       if (CountDw < 1 || CountDw > 4) {
7143         report_fatal_error(
7144             "ds_ordered_count: dword count must be between 1 and 4");
7145       }
7146     }
7147 
7148     if (IndexOperand)
7149       report_fatal_error("ds_ordered_count: bad index operand");
7150 
7151     if (WaveDone && !WaveRelease)
7152       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7153 
7154     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7155     unsigned ShaderType =
7156         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7157     unsigned Offset0 = OrderedCountIndex << 2;
7158     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7159                        (Instruction << 4);
7160 
7161     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7162       Offset1 |= (CountDw - 1) << 6;
7163 
7164     unsigned Offset = Offset0 | (Offset1 << 8);
7165 
7166     SDValue Ops[] = {
7167       Chain,
7168       Value,
7169       DAG.getTargetConstant(Offset, DL, MVT::i16),
7170       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7171     };
7172     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7173                                    M->getVTList(), Ops, M->getMemoryVT(),
7174                                    M->getMemOperand());
7175   }
7176   case Intrinsic::amdgcn_ds_fadd: {
7177     MemSDNode *M = cast<MemSDNode>(Op);
7178     unsigned Opc;
7179     switch (IntrID) {
7180     case Intrinsic::amdgcn_ds_fadd:
7181       Opc = ISD::ATOMIC_LOAD_FADD;
7182       break;
7183     }
7184 
7185     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7186                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7187                          M->getMemOperand());
7188   }
7189   case Intrinsic::amdgcn_atomic_inc:
7190   case Intrinsic::amdgcn_atomic_dec:
7191   case Intrinsic::amdgcn_ds_fmin:
7192   case Intrinsic::amdgcn_ds_fmax: {
7193     MemSDNode *M = cast<MemSDNode>(Op);
7194     unsigned Opc;
7195     switch (IntrID) {
7196     case Intrinsic::amdgcn_atomic_inc:
7197       Opc = AMDGPUISD::ATOMIC_INC;
7198       break;
7199     case Intrinsic::amdgcn_atomic_dec:
7200       Opc = AMDGPUISD::ATOMIC_DEC;
7201       break;
7202     case Intrinsic::amdgcn_ds_fmin:
7203       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7204       break;
7205     case Intrinsic::amdgcn_ds_fmax:
7206       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7207       break;
7208     default:
7209       llvm_unreachable("Unknown intrinsic!");
7210     }
7211     SDValue Ops[] = {
7212       M->getOperand(0), // Chain
7213       M->getOperand(2), // Ptr
7214       M->getOperand(3)  // Value
7215     };
7216 
7217     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7218                                    M->getMemoryVT(), M->getMemOperand());
7219   }
7220   case Intrinsic::amdgcn_buffer_load:
7221   case Intrinsic::amdgcn_buffer_load_format: {
7222     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7223     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7224     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7225     SDValue Ops[] = {
7226       Op.getOperand(0), // Chain
7227       Op.getOperand(2), // rsrc
7228       Op.getOperand(3), // vindex
7229       SDValue(),        // voffset -- will be set by setBufferOffsets
7230       SDValue(),        // soffset -- will be set by setBufferOffsets
7231       SDValue(),        // offset -- will be set by setBufferOffsets
7232       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7233       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7234     };
7235     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7236 
7237     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7238         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7239 
7240     EVT VT = Op.getValueType();
7241     EVT IntVT = VT.changeTypeToInteger();
7242     auto *M = cast<MemSDNode>(Op);
7243     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7244     EVT LoadVT = Op.getValueType();
7245 
7246     if (LoadVT.getScalarType() == MVT::f16)
7247       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7248                                  M, DAG, Ops);
7249 
7250     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7251     if (LoadVT.getScalarType() == MVT::i8 ||
7252         LoadVT.getScalarType() == MVT::i16)
7253       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7254 
7255     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7256                                M->getMemOperand(), DAG);
7257   }
7258   case Intrinsic::amdgcn_raw_buffer_load:
7259   case Intrinsic::amdgcn_raw_buffer_load_format: {
7260     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7261 
7262     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7263     SDValue Ops[] = {
7264       Op.getOperand(0), // Chain
7265       Op.getOperand(2), // rsrc
7266       DAG.getConstant(0, DL, MVT::i32), // vindex
7267       Offsets.first,    // voffset
7268       Op.getOperand(4), // soffset
7269       Offsets.second,   // offset
7270       Op.getOperand(5), // cachepolicy, swizzled buffer
7271       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7272     };
7273 
7274     auto *M = cast<MemSDNode>(Op);
7275     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7276     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7277   }
7278   case Intrinsic::amdgcn_struct_buffer_load:
7279   case Intrinsic::amdgcn_struct_buffer_load_format: {
7280     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7281 
7282     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7283     SDValue Ops[] = {
7284       Op.getOperand(0), // Chain
7285       Op.getOperand(2), // rsrc
7286       Op.getOperand(3), // vindex
7287       Offsets.first,    // voffset
7288       Op.getOperand(5), // soffset
7289       Offsets.second,   // offset
7290       Op.getOperand(6), // cachepolicy, swizzled buffer
7291       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7292     };
7293 
7294     auto *M = cast<MemSDNode>(Op);
7295     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7296     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7297   }
7298   case Intrinsic::amdgcn_tbuffer_load: {
7299     MemSDNode *M = cast<MemSDNode>(Op);
7300     EVT LoadVT = Op.getValueType();
7301 
7302     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7303     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7304     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7305     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7306     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7307     SDValue Ops[] = {
7308       Op.getOperand(0),  // Chain
7309       Op.getOperand(2),  // rsrc
7310       Op.getOperand(3),  // vindex
7311       Op.getOperand(4),  // voffset
7312       Op.getOperand(5),  // soffset
7313       Op.getOperand(6),  // offset
7314       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7315       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7316       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7317     };
7318 
7319     if (LoadVT.getScalarType() == MVT::f16)
7320       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7321                                  M, DAG, Ops);
7322     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7323                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7324                                DAG);
7325   }
7326   case Intrinsic::amdgcn_raw_tbuffer_load: {
7327     MemSDNode *M = cast<MemSDNode>(Op);
7328     EVT LoadVT = Op.getValueType();
7329     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7330 
7331     SDValue Ops[] = {
7332       Op.getOperand(0),  // Chain
7333       Op.getOperand(2),  // rsrc
7334       DAG.getConstant(0, DL, MVT::i32), // vindex
7335       Offsets.first,     // voffset
7336       Op.getOperand(4),  // soffset
7337       Offsets.second,    // offset
7338       Op.getOperand(5),  // format
7339       Op.getOperand(6),  // cachepolicy, swizzled buffer
7340       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7341     };
7342 
7343     if (LoadVT.getScalarType() == MVT::f16)
7344       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7345                                  M, DAG, Ops);
7346     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7347                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7348                                DAG);
7349   }
7350   case Intrinsic::amdgcn_struct_tbuffer_load: {
7351     MemSDNode *M = cast<MemSDNode>(Op);
7352     EVT LoadVT = Op.getValueType();
7353     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7354 
7355     SDValue Ops[] = {
7356       Op.getOperand(0),  // Chain
7357       Op.getOperand(2),  // rsrc
7358       Op.getOperand(3),  // vindex
7359       Offsets.first,     // voffset
7360       Op.getOperand(5),  // soffset
7361       Offsets.second,    // offset
7362       Op.getOperand(6),  // format
7363       Op.getOperand(7),  // cachepolicy, swizzled buffer
7364       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7365     };
7366 
7367     if (LoadVT.getScalarType() == MVT::f16)
7368       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7369                                  M, DAG, Ops);
7370     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7371                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7372                                DAG);
7373   }
7374   case Intrinsic::amdgcn_buffer_atomic_swap:
7375   case Intrinsic::amdgcn_buffer_atomic_add:
7376   case Intrinsic::amdgcn_buffer_atomic_sub:
7377   case Intrinsic::amdgcn_buffer_atomic_csub:
7378   case Intrinsic::amdgcn_buffer_atomic_smin:
7379   case Intrinsic::amdgcn_buffer_atomic_umin:
7380   case Intrinsic::amdgcn_buffer_atomic_smax:
7381   case Intrinsic::amdgcn_buffer_atomic_umax:
7382   case Intrinsic::amdgcn_buffer_atomic_and:
7383   case Intrinsic::amdgcn_buffer_atomic_or:
7384   case Intrinsic::amdgcn_buffer_atomic_xor:
7385   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7386     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7387     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7388     SDValue Ops[] = {
7389       Op.getOperand(0), // Chain
7390       Op.getOperand(2), // vdata
7391       Op.getOperand(3), // rsrc
7392       Op.getOperand(4), // vindex
7393       SDValue(),        // voffset -- will be set by setBufferOffsets
7394       SDValue(),        // soffset -- will be set by setBufferOffsets
7395       SDValue(),        // offset -- will be set by setBufferOffsets
7396       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7397       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7398     };
7399     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7400 
7401     EVT VT = Op.getValueType();
7402 
7403     auto *M = cast<MemSDNode>(Op);
7404     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7405     unsigned Opcode = 0;
7406 
7407     switch (IntrID) {
7408     case Intrinsic::amdgcn_buffer_atomic_swap:
7409       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7410       break;
7411     case Intrinsic::amdgcn_buffer_atomic_add:
7412       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7413       break;
7414     case Intrinsic::amdgcn_buffer_atomic_sub:
7415       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7416       break;
7417     case Intrinsic::amdgcn_buffer_atomic_csub:
7418       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7419       break;
7420     case Intrinsic::amdgcn_buffer_atomic_smin:
7421       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7422       break;
7423     case Intrinsic::amdgcn_buffer_atomic_umin:
7424       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7425       break;
7426     case Intrinsic::amdgcn_buffer_atomic_smax:
7427       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7428       break;
7429     case Intrinsic::amdgcn_buffer_atomic_umax:
7430       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7431       break;
7432     case Intrinsic::amdgcn_buffer_atomic_and:
7433       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7434       break;
7435     case Intrinsic::amdgcn_buffer_atomic_or:
7436       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7437       break;
7438     case Intrinsic::amdgcn_buffer_atomic_xor:
7439       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7440       break;
7441     case Intrinsic::amdgcn_buffer_atomic_fadd:
7442       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7443         DiagnosticInfoUnsupported
7444           NoFpRet(DAG.getMachineFunction().getFunction(),
7445                   "return versions of fp atomics not supported",
7446                   DL.getDebugLoc(), DS_Error);
7447         DAG.getContext()->diagnose(NoFpRet);
7448         return SDValue();
7449       }
7450       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7451       break;
7452     default:
7453       llvm_unreachable("unhandled atomic opcode");
7454     }
7455 
7456     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7457                                    M->getMemOperand());
7458   }
7459   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7460     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7461   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7462     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7463   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7464     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7465   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7466     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7467   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7468     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7469   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7470     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7471   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7472     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7473   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7474     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7475   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7476     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7477   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7478     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7479   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7480     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7481   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7482     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7483   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7484     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7485   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7486     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7487   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7488     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7489   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7490     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7491   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7492     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7493   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7494     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7495   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7496     return lowerStructBufferAtomicIntrin(Op, DAG,
7497                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7498   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7499     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7500   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7501     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7502   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7503     return lowerStructBufferAtomicIntrin(Op, DAG,
7504                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7505   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7506     return lowerStructBufferAtomicIntrin(Op, DAG,
7507                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7508   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7509     return lowerStructBufferAtomicIntrin(Op, DAG,
7510                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7511   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7512     return lowerStructBufferAtomicIntrin(Op, DAG,
7513                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7514   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7515     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7516   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7517     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7518   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7519     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7520   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7521     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7522   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7523     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7524 
7525   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7526     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7527     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7528     SDValue Ops[] = {
7529       Op.getOperand(0), // Chain
7530       Op.getOperand(2), // src
7531       Op.getOperand(3), // cmp
7532       Op.getOperand(4), // rsrc
7533       Op.getOperand(5), // vindex
7534       SDValue(),        // voffset -- will be set by setBufferOffsets
7535       SDValue(),        // soffset -- will be set by setBufferOffsets
7536       SDValue(),        // offset -- will be set by setBufferOffsets
7537       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7538       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7539     };
7540     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7541 
7542     EVT VT = Op.getValueType();
7543     auto *M = cast<MemSDNode>(Op);
7544     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7545 
7546     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7547                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7548   }
7549   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7550     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7551     SDValue Ops[] = {
7552       Op.getOperand(0), // Chain
7553       Op.getOperand(2), // src
7554       Op.getOperand(3), // cmp
7555       Op.getOperand(4), // rsrc
7556       DAG.getConstant(0, DL, MVT::i32), // vindex
7557       Offsets.first,    // voffset
7558       Op.getOperand(6), // soffset
7559       Offsets.second,   // offset
7560       Op.getOperand(7), // cachepolicy
7561       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7562     };
7563     EVT VT = Op.getValueType();
7564     auto *M = cast<MemSDNode>(Op);
7565     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7566 
7567     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7568                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7569   }
7570   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7571     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7572     SDValue Ops[] = {
7573       Op.getOperand(0), // Chain
7574       Op.getOperand(2), // src
7575       Op.getOperand(3), // cmp
7576       Op.getOperand(4), // rsrc
7577       Op.getOperand(5), // vindex
7578       Offsets.first,    // voffset
7579       Op.getOperand(7), // soffset
7580       Offsets.second,   // offset
7581       Op.getOperand(8), // cachepolicy
7582       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7583     };
7584     EVT VT = Op.getValueType();
7585     auto *M = cast<MemSDNode>(Op);
7586     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7587 
7588     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7589                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7590   }
7591   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7592     MemSDNode *M = cast<MemSDNode>(Op);
7593     SDValue NodePtr = M->getOperand(2);
7594     SDValue RayExtent = M->getOperand(3);
7595     SDValue RayOrigin = M->getOperand(4);
7596     SDValue RayDir = M->getOperand(5);
7597     SDValue RayInvDir = M->getOperand(6);
7598     SDValue TDescr = M->getOperand(7);
7599 
7600     assert(NodePtr.getValueType() == MVT::i32 ||
7601            NodePtr.getValueType() == MVT::i64);
7602     assert(RayDir.getValueType() == MVT::v3f16 ||
7603            RayDir.getValueType() == MVT::v3f32);
7604 
7605     if (!Subtarget->hasGFX10_AEncoding()) {
7606       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7607       return SDValue();
7608     }
7609 
7610     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7611     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7612     const unsigned NumVDataDwords = 4;
7613     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7614     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7615                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7616     const unsigned BaseOpcodes[2][2] = {
7617         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7618         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7619          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7620     int Opcode;
7621     if (UseNSA) {
7622       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7623                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7624                                      NumVAddrDwords);
7625     } else {
7626       Opcode = AMDGPU::getMIMGOpcode(
7627           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7628           PowerOf2Ceil(NumVAddrDwords));
7629     }
7630     assert(Opcode != -1);
7631 
7632     SmallVector<SDValue, 16> Ops;
7633 
7634     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7635       SmallVector<SDValue, 3> Lanes;
7636       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7637       if (Lanes[0].getValueSizeInBits() == 32) {
7638         for (unsigned I = 0; I < 3; ++I)
7639           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7640       } else {
7641         if (IsAligned) {
7642           Ops.push_back(
7643             DAG.getBitcast(MVT::i32,
7644                            DAG.getBuildVector(MVT::v2f16, DL,
7645                                               { Lanes[0], Lanes[1] })));
7646           Ops.push_back(Lanes[2]);
7647         } else {
7648           SDValue Elt0 = Ops.pop_back_val();
7649           Ops.push_back(
7650             DAG.getBitcast(MVT::i32,
7651                            DAG.getBuildVector(MVT::v2f16, DL,
7652                                               { Elt0, Lanes[0] })));
7653           Ops.push_back(
7654             DAG.getBitcast(MVT::i32,
7655                            DAG.getBuildVector(MVT::v2f16, DL,
7656                                               { Lanes[1], Lanes[2] })));
7657         }
7658       }
7659     };
7660 
7661     if (Is64)
7662       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7663     else
7664       Ops.push_back(NodePtr);
7665 
7666     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7667     packLanes(RayOrigin, true);
7668     packLanes(RayDir, true);
7669     packLanes(RayInvDir, false);
7670 
7671     if (!UseNSA) {
7672       // Build a single vector containing all the operands so far prepared.
7673       if (NumVAddrDwords > 8) {
7674         SDValue Undef = DAG.getUNDEF(MVT::i32);
7675         Ops.append(16 - Ops.size(), Undef);
7676       }
7677       assert(Ops.size() == 8 || Ops.size() == 16);
7678       SDValue MergedOps = DAG.getBuildVector(
7679           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7680       Ops.clear();
7681       Ops.push_back(MergedOps);
7682     }
7683 
7684     Ops.push_back(TDescr);
7685     if (IsA16)
7686       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7687     Ops.push_back(M->getChain());
7688 
7689     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7690     MachineMemOperand *MemRef = M->getMemOperand();
7691     DAG.setNodeMemRefs(NewNode, {MemRef});
7692     return SDValue(NewNode, 0);
7693   }
7694   case Intrinsic::amdgcn_global_atomic_fadd:
7695     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7696       DiagnosticInfoUnsupported
7697         NoFpRet(DAG.getMachineFunction().getFunction(),
7698                 "return versions of fp atomics not supported",
7699                 DL.getDebugLoc(), DS_Error);
7700       DAG.getContext()->diagnose(NoFpRet);
7701       return SDValue();
7702     }
7703     LLVM_FALLTHROUGH;
7704   case Intrinsic::amdgcn_global_atomic_fmin:
7705   case Intrinsic::amdgcn_global_atomic_fmax:
7706   case Intrinsic::amdgcn_flat_atomic_fadd:
7707   case Intrinsic::amdgcn_flat_atomic_fmin:
7708   case Intrinsic::amdgcn_flat_atomic_fmax: {
7709     MemSDNode *M = cast<MemSDNode>(Op);
7710     SDValue Ops[] = {
7711       M->getOperand(0), // Chain
7712       M->getOperand(2), // Ptr
7713       M->getOperand(3)  // Value
7714     };
7715     unsigned Opcode = 0;
7716     switch (IntrID) {
7717     case Intrinsic::amdgcn_global_atomic_fadd:
7718     case Intrinsic::amdgcn_flat_atomic_fadd: {
7719       EVT VT = Op.getOperand(3).getValueType();
7720       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7721                            DAG.getVTList(VT, MVT::Other), Ops,
7722                            M->getMemOperand());
7723     }
7724     case Intrinsic::amdgcn_global_atomic_fmin:
7725     case Intrinsic::amdgcn_flat_atomic_fmin: {
7726       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7727       break;
7728     }
7729     case Intrinsic::amdgcn_global_atomic_fmax:
7730     case Intrinsic::amdgcn_flat_atomic_fmax: {
7731       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7732       break;
7733     }
7734     default:
7735       llvm_unreachable("unhandled atomic opcode");
7736     }
7737     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7738                                    M->getVTList(), Ops, M->getMemoryVT(),
7739                                    M->getMemOperand());
7740   }
7741   default:
7742 
7743     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7744             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7745       return lowerImage(Op, ImageDimIntr, DAG, true);
7746 
7747     return SDValue();
7748   }
7749 }
7750 
7751 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7752 // dwordx4 if on SI.
7753 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7754                                               SDVTList VTList,
7755                                               ArrayRef<SDValue> Ops, EVT MemVT,
7756                                               MachineMemOperand *MMO,
7757                                               SelectionDAG &DAG) const {
7758   EVT VT = VTList.VTs[0];
7759   EVT WidenedVT = VT;
7760   EVT WidenedMemVT = MemVT;
7761   if (!Subtarget->hasDwordx3LoadStores() &&
7762       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7763     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7764                                  WidenedVT.getVectorElementType(), 4);
7765     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7766                                     WidenedMemVT.getVectorElementType(), 4);
7767     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7768   }
7769 
7770   assert(VTList.NumVTs == 2);
7771   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7772 
7773   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7774                                        WidenedMemVT, MMO);
7775   if (WidenedVT != VT) {
7776     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7777                                DAG.getVectorIdxConstant(0, DL));
7778     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7779   }
7780   return NewOp;
7781 }
7782 
7783 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7784                                          bool ImageStore) const {
7785   EVT StoreVT = VData.getValueType();
7786 
7787   // No change for f16 and legal vector D16 types.
7788   if (!StoreVT.isVector())
7789     return VData;
7790 
7791   SDLoc DL(VData);
7792   unsigned NumElements = StoreVT.getVectorNumElements();
7793 
7794   if (Subtarget->hasUnpackedD16VMem()) {
7795     // We need to unpack the packed data to store.
7796     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7797     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7798 
7799     EVT EquivStoreVT =
7800         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7801     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7802     return DAG.UnrollVectorOp(ZExt.getNode());
7803   }
7804 
7805   // The sq block of gfx8.1 does not estimate register use correctly for d16
7806   // image store instructions. The data operand is computed as if it were not a
7807   // d16 image instruction.
7808   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7809     // Bitcast to i16
7810     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7811     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7812 
7813     // Decompose into scalars
7814     SmallVector<SDValue, 4> Elts;
7815     DAG.ExtractVectorElements(IntVData, Elts);
7816 
7817     // Group pairs of i16 into v2i16 and bitcast to i32
7818     SmallVector<SDValue, 4> PackedElts;
7819     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7820       SDValue Pair =
7821           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7822       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7823       PackedElts.push_back(IntPair);
7824     }
7825     if ((NumElements % 2) == 1) {
7826       // Handle v3i16
7827       unsigned I = Elts.size() / 2;
7828       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7829                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7830       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7831       PackedElts.push_back(IntPair);
7832     }
7833 
7834     // Pad using UNDEF
7835     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7836 
7837     // Build final vector
7838     EVT VecVT =
7839         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7840     return DAG.getBuildVector(VecVT, DL, PackedElts);
7841   }
7842 
7843   if (NumElements == 3) {
7844     EVT IntStoreVT =
7845         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7846     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7847 
7848     EVT WidenedStoreVT = EVT::getVectorVT(
7849         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7850     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7851                                          WidenedStoreVT.getStoreSizeInBits());
7852     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7853     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7854   }
7855 
7856   assert(isTypeLegal(StoreVT));
7857   return VData;
7858 }
7859 
7860 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7861                                               SelectionDAG &DAG) const {
7862   SDLoc DL(Op);
7863   SDValue Chain = Op.getOperand(0);
7864   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7865   MachineFunction &MF = DAG.getMachineFunction();
7866 
7867   switch (IntrinsicID) {
7868   case Intrinsic::amdgcn_exp_compr: {
7869     SDValue Src0 = Op.getOperand(4);
7870     SDValue Src1 = Op.getOperand(5);
7871     // Hack around illegal type on SI by directly selecting it.
7872     if (isTypeLegal(Src0.getValueType()))
7873       return SDValue();
7874 
7875     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7876     SDValue Undef = DAG.getUNDEF(MVT::f32);
7877     const SDValue Ops[] = {
7878       Op.getOperand(2), // tgt
7879       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7880       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7881       Undef, // src2
7882       Undef, // src3
7883       Op.getOperand(7), // vm
7884       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7885       Op.getOperand(3), // en
7886       Op.getOperand(0) // Chain
7887     };
7888 
7889     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7890     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7891   }
7892   case Intrinsic::amdgcn_s_barrier: {
7893     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7894       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7895       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7896       if (WGSize <= ST.getWavefrontSize())
7897         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7898                                           Op.getOperand(0)), 0);
7899     }
7900     return SDValue();
7901   };
7902   case Intrinsic::amdgcn_tbuffer_store: {
7903     SDValue VData = Op.getOperand(2);
7904     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7905     if (IsD16)
7906       VData = handleD16VData(VData, DAG);
7907     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7908     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7909     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7910     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7911     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7912     SDValue Ops[] = {
7913       Chain,
7914       VData,             // vdata
7915       Op.getOperand(3),  // rsrc
7916       Op.getOperand(4),  // vindex
7917       Op.getOperand(5),  // voffset
7918       Op.getOperand(6),  // soffset
7919       Op.getOperand(7),  // offset
7920       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7921       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7922       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7923     };
7924     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7925                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7926     MemSDNode *M = cast<MemSDNode>(Op);
7927     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7928                                    M->getMemoryVT(), M->getMemOperand());
7929   }
7930 
7931   case Intrinsic::amdgcn_struct_tbuffer_store: {
7932     SDValue VData = Op.getOperand(2);
7933     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7934     if (IsD16)
7935       VData = handleD16VData(VData, DAG);
7936     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7937     SDValue Ops[] = {
7938       Chain,
7939       VData,             // vdata
7940       Op.getOperand(3),  // rsrc
7941       Op.getOperand(4),  // vindex
7942       Offsets.first,     // voffset
7943       Op.getOperand(6),  // soffset
7944       Offsets.second,    // offset
7945       Op.getOperand(7),  // format
7946       Op.getOperand(8),  // cachepolicy, swizzled buffer
7947       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7948     };
7949     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7950                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7951     MemSDNode *M = cast<MemSDNode>(Op);
7952     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7953                                    M->getMemoryVT(), M->getMemOperand());
7954   }
7955 
7956   case Intrinsic::amdgcn_raw_tbuffer_store: {
7957     SDValue VData = Op.getOperand(2);
7958     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7959     if (IsD16)
7960       VData = handleD16VData(VData, DAG);
7961     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7962     SDValue Ops[] = {
7963       Chain,
7964       VData,             // vdata
7965       Op.getOperand(3),  // rsrc
7966       DAG.getConstant(0, DL, MVT::i32), // vindex
7967       Offsets.first,     // voffset
7968       Op.getOperand(5),  // soffset
7969       Offsets.second,    // offset
7970       Op.getOperand(6),  // format
7971       Op.getOperand(7),  // cachepolicy, swizzled buffer
7972       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7973     };
7974     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7975                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7976     MemSDNode *M = cast<MemSDNode>(Op);
7977     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7978                                    M->getMemoryVT(), M->getMemOperand());
7979   }
7980 
7981   case Intrinsic::amdgcn_buffer_store:
7982   case Intrinsic::amdgcn_buffer_store_format: {
7983     SDValue VData = Op.getOperand(2);
7984     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7985     if (IsD16)
7986       VData = handleD16VData(VData, DAG);
7987     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7988     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7989     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7990     SDValue Ops[] = {
7991       Chain,
7992       VData,
7993       Op.getOperand(3), // rsrc
7994       Op.getOperand(4), // vindex
7995       SDValue(), // voffset -- will be set by setBufferOffsets
7996       SDValue(), // soffset -- will be set by setBufferOffsets
7997       SDValue(), // offset -- will be set by setBufferOffsets
7998       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7999       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8000     };
8001     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8002 
8003     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8004                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8005     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8006     MemSDNode *M = cast<MemSDNode>(Op);
8007     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8008 
8009     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8010     EVT VDataType = VData.getValueType().getScalarType();
8011     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8012       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8013 
8014     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8015                                    M->getMemoryVT(), M->getMemOperand());
8016   }
8017 
8018   case Intrinsic::amdgcn_raw_buffer_store:
8019   case Intrinsic::amdgcn_raw_buffer_store_format: {
8020     const bool IsFormat =
8021         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8022 
8023     SDValue VData = Op.getOperand(2);
8024     EVT VDataVT = VData.getValueType();
8025     EVT EltType = VDataVT.getScalarType();
8026     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8027     if (IsD16) {
8028       VData = handleD16VData(VData, DAG);
8029       VDataVT = VData.getValueType();
8030     }
8031 
8032     if (!isTypeLegal(VDataVT)) {
8033       VData =
8034           DAG.getNode(ISD::BITCAST, DL,
8035                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8036     }
8037 
8038     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8039     SDValue Ops[] = {
8040       Chain,
8041       VData,
8042       Op.getOperand(3), // rsrc
8043       DAG.getConstant(0, DL, MVT::i32), // vindex
8044       Offsets.first,    // voffset
8045       Op.getOperand(5), // soffset
8046       Offsets.second,   // offset
8047       Op.getOperand(6), // cachepolicy, swizzled buffer
8048       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8049     };
8050     unsigned Opc =
8051         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8052     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8053     MemSDNode *M = cast<MemSDNode>(Op);
8054     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8055 
8056     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8057     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8058       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8059 
8060     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8061                                    M->getMemoryVT(), M->getMemOperand());
8062   }
8063 
8064   case Intrinsic::amdgcn_struct_buffer_store:
8065   case Intrinsic::amdgcn_struct_buffer_store_format: {
8066     const bool IsFormat =
8067         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8068 
8069     SDValue VData = Op.getOperand(2);
8070     EVT VDataVT = VData.getValueType();
8071     EVT EltType = VDataVT.getScalarType();
8072     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8073 
8074     if (IsD16) {
8075       VData = handleD16VData(VData, DAG);
8076       VDataVT = VData.getValueType();
8077     }
8078 
8079     if (!isTypeLegal(VDataVT)) {
8080       VData =
8081           DAG.getNode(ISD::BITCAST, DL,
8082                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8083     }
8084 
8085     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8086     SDValue Ops[] = {
8087       Chain,
8088       VData,
8089       Op.getOperand(3), // rsrc
8090       Op.getOperand(4), // vindex
8091       Offsets.first,    // voffset
8092       Op.getOperand(6), // soffset
8093       Offsets.second,   // offset
8094       Op.getOperand(7), // cachepolicy, swizzled buffer
8095       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8096     };
8097     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8098                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8099     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8100     MemSDNode *M = cast<MemSDNode>(Op);
8101     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8102 
8103     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8104     EVT VDataType = VData.getValueType().getScalarType();
8105     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8106       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8107 
8108     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8109                                    M->getMemoryVT(), M->getMemOperand());
8110   }
8111   case Intrinsic::amdgcn_end_cf:
8112     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8113                                       Op->getOperand(2), Chain), 0);
8114 
8115   default: {
8116     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8117             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8118       return lowerImage(Op, ImageDimIntr, DAG, true);
8119 
8120     return Op;
8121   }
8122   }
8123 }
8124 
8125 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8126 // offset (the offset that is included in bounds checking and swizzling, to be
8127 // split between the instruction's voffset and immoffset fields) and soffset
8128 // (the offset that is excluded from bounds checking and swizzling, to go in
8129 // the instruction's soffset field).  This function takes the first kind of
8130 // offset and figures out how to split it between voffset and immoffset.
8131 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8132     SDValue Offset, SelectionDAG &DAG) const {
8133   SDLoc DL(Offset);
8134   const unsigned MaxImm = 4095;
8135   SDValue N0 = Offset;
8136   ConstantSDNode *C1 = nullptr;
8137 
8138   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8139     N0 = SDValue();
8140   else if (DAG.isBaseWithConstantOffset(N0)) {
8141     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8142     N0 = N0.getOperand(0);
8143   }
8144 
8145   if (C1) {
8146     unsigned ImmOffset = C1->getZExtValue();
8147     // If the immediate value is too big for the immoffset field, put the value
8148     // and -4096 into the immoffset field so that the value that is copied/added
8149     // for the voffset field is a multiple of 4096, and it stands more chance
8150     // of being CSEd with the copy/add for another similar load/store.
8151     // However, do not do that rounding down to a multiple of 4096 if that is a
8152     // negative number, as it appears to be illegal to have a negative offset
8153     // in the vgpr, even if adding the immediate offset makes it positive.
8154     unsigned Overflow = ImmOffset & ~MaxImm;
8155     ImmOffset -= Overflow;
8156     if ((int32_t)Overflow < 0) {
8157       Overflow += ImmOffset;
8158       ImmOffset = 0;
8159     }
8160     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8161     if (Overflow) {
8162       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8163       if (!N0)
8164         N0 = OverflowVal;
8165       else {
8166         SDValue Ops[] = { N0, OverflowVal };
8167         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8168       }
8169     }
8170   }
8171   if (!N0)
8172     N0 = DAG.getConstant(0, DL, MVT::i32);
8173   if (!C1)
8174     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8175   return {N0, SDValue(C1, 0)};
8176 }
8177 
8178 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8179 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8180 // pointed to by Offsets.
8181 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8182                                         SelectionDAG &DAG, SDValue *Offsets,
8183                                         Align Alignment) const {
8184   SDLoc DL(CombinedOffset);
8185   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8186     uint32_t Imm = C->getZExtValue();
8187     uint32_t SOffset, ImmOffset;
8188     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8189                                  Alignment)) {
8190       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8191       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8192       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8193       return;
8194     }
8195   }
8196   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8197     SDValue N0 = CombinedOffset.getOperand(0);
8198     SDValue N1 = CombinedOffset.getOperand(1);
8199     uint32_t SOffset, ImmOffset;
8200     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8201     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8202                                                 Subtarget, Alignment)) {
8203       Offsets[0] = N0;
8204       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8205       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8206       return;
8207     }
8208   }
8209   Offsets[0] = CombinedOffset;
8210   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8211   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8212 }
8213 
8214 // Handle 8 bit and 16 bit buffer loads
8215 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8216                                                      EVT LoadVT, SDLoc DL,
8217                                                      ArrayRef<SDValue> Ops,
8218                                                      MemSDNode *M) const {
8219   EVT IntVT = LoadVT.changeTypeToInteger();
8220   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8221          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8222 
8223   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8224   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8225                                                Ops, IntVT,
8226                                                M->getMemOperand());
8227   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8228   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8229 
8230   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8231 }
8232 
8233 // Handle 8 bit and 16 bit buffer stores
8234 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8235                                                       EVT VDataType, SDLoc DL,
8236                                                       SDValue Ops[],
8237                                                       MemSDNode *M) const {
8238   if (VDataType == MVT::f16)
8239     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8240 
8241   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8242   Ops[1] = BufferStoreExt;
8243   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8244                                  AMDGPUISD::BUFFER_STORE_SHORT;
8245   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8246   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8247                                      M->getMemOperand());
8248 }
8249 
8250 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8251                                  ISD::LoadExtType ExtType, SDValue Op,
8252                                  const SDLoc &SL, EVT VT) {
8253   if (VT.bitsLT(Op.getValueType()))
8254     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8255 
8256   switch (ExtType) {
8257   case ISD::SEXTLOAD:
8258     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8259   case ISD::ZEXTLOAD:
8260     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8261   case ISD::EXTLOAD:
8262     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8263   case ISD::NON_EXTLOAD:
8264     return Op;
8265   }
8266 
8267   llvm_unreachable("invalid ext type");
8268 }
8269 
8270 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8271   SelectionDAG &DAG = DCI.DAG;
8272   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8273     return SDValue();
8274 
8275   // FIXME: Constant loads should all be marked invariant.
8276   unsigned AS = Ld->getAddressSpace();
8277   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8278       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8279       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8280     return SDValue();
8281 
8282   // Don't do this early, since it may interfere with adjacent load merging for
8283   // illegal types. We can avoid losing alignment information for exotic types
8284   // pre-legalize.
8285   EVT MemVT = Ld->getMemoryVT();
8286   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8287       MemVT.getSizeInBits() >= 32)
8288     return SDValue();
8289 
8290   SDLoc SL(Ld);
8291 
8292   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8293          "unexpected vector extload");
8294 
8295   // TODO: Drop only high part of range.
8296   SDValue Ptr = Ld->getBasePtr();
8297   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8298                                 MVT::i32, SL, Ld->getChain(), Ptr,
8299                                 Ld->getOffset(),
8300                                 Ld->getPointerInfo(), MVT::i32,
8301                                 Ld->getAlignment(),
8302                                 Ld->getMemOperand()->getFlags(),
8303                                 Ld->getAAInfo(),
8304                                 nullptr); // Drop ranges
8305 
8306   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8307   if (MemVT.isFloatingPoint()) {
8308     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8309            "unexpected fp extload");
8310     TruncVT = MemVT.changeTypeToInteger();
8311   }
8312 
8313   SDValue Cvt = NewLoad;
8314   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8315     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8316                       DAG.getValueType(TruncVT));
8317   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8318              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8319     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8320   } else {
8321     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8322   }
8323 
8324   EVT VT = Ld->getValueType(0);
8325   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8326 
8327   DCI.AddToWorklist(Cvt.getNode());
8328 
8329   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8330   // the appropriate extension from the 32-bit load.
8331   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8332   DCI.AddToWorklist(Cvt.getNode());
8333 
8334   // Handle conversion back to floating point if necessary.
8335   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8336 
8337   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8338 }
8339 
8340 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8341   SDLoc DL(Op);
8342   LoadSDNode *Load = cast<LoadSDNode>(Op);
8343   ISD::LoadExtType ExtType = Load->getExtensionType();
8344   EVT MemVT = Load->getMemoryVT();
8345 
8346   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8347     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8348       return SDValue();
8349 
8350     // FIXME: Copied from PPC
8351     // First, load into 32 bits, then truncate to 1 bit.
8352 
8353     SDValue Chain = Load->getChain();
8354     SDValue BasePtr = Load->getBasePtr();
8355     MachineMemOperand *MMO = Load->getMemOperand();
8356 
8357     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8358 
8359     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8360                                    BasePtr, RealMemVT, MMO);
8361 
8362     if (!MemVT.isVector()) {
8363       SDValue Ops[] = {
8364         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8365         NewLD.getValue(1)
8366       };
8367 
8368       return DAG.getMergeValues(Ops, DL);
8369     }
8370 
8371     SmallVector<SDValue, 3> Elts;
8372     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8373       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8374                                 DAG.getConstant(I, DL, MVT::i32));
8375 
8376       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8377     }
8378 
8379     SDValue Ops[] = {
8380       DAG.getBuildVector(MemVT, DL, Elts),
8381       NewLD.getValue(1)
8382     };
8383 
8384     return DAG.getMergeValues(Ops, DL);
8385   }
8386 
8387   if (!MemVT.isVector())
8388     return SDValue();
8389 
8390   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8391          "Custom lowering for non-i32 vectors hasn't been implemented.");
8392 
8393   unsigned Alignment = Load->getAlignment();
8394   unsigned AS = Load->getAddressSpace();
8395   if (Subtarget->hasLDSMisalignedBug() &&
8396       AS == AMDGPUAS::FLAT_ADDRESS &&
8397       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8398     return SplitVectorLoad(Op, DAG);
8399   }
8400 
8401   MachineFunction &MF = DAG.getMachineFunction();
8402   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8403   // If there is a possibilty that flat instruction access scratch memory
8404   // then we need to use the same legalization rules we use for private.
8405   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8406       !Subtarget->hasMultiDwordFlatScratchAddressing())
8407     AS = MFI->hasFlatScratchInit() ?
8408          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8409 
8410   unsigned NumElements = MemVT.getVectorNumElements();
8411 
8412   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8413       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8414     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8415       if (MemVT.isPow2VectorType())
8416         return SDValue();
8417       return WidenOrSplitVectorLoad(Op, DAG);
8418     }
8419     // Non-uniform loads will be selected to MUBUF instructions, so they
8420     // have the same legalization requirements as global and private
8421     // loads.
8422     //
8423   }
8424 
8425   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8426       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8427       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8428     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8429         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8430         Alignment >= 4 && NumElements < 32) {
8431       if (MemVT.isPow2VectorType())
8432         return SDValue();
8433       return WidenOrSplitVectorLoad(Op, DAG);
8434     }
8435     // Non-uniform loads will be selected to MUBUF instructions, so they
8436     // have the same legalization requirements as global and private
8437     // loads.
8438     //
8439   }
8440   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8441       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8442       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8443       AS == AMDGPUAS::FLAT_ADDRESS) {
8444     if (NumElements > 4)
8445       return SplitVectorLoad(Op, DAG);
8446     // v3 loads not supported on SI.
8447     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8448       return WidenOrSplitVectorLoad(Op, DAG);
8449 
8450     // v3 and v4 loads are supported for private and global memory.
8451     return SDValue();
8452   }
8453   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8454     // Depending on the setting of the private_element_size field in the
8455     // resource descriptor, we can only make private accesses up to a certain
8456     // size.
8457     switch (Subtarget->getMaxPrivateElementSize()) {
8458     case 4: {
8459       SDValue Ops[2];
8460       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8461       return DAG.getMergeValues(Ops, DL);
8462     }
8463     case 8:
8464       if (NumElements > 2)
8465         return SplitVectorLoad(Op, DAG);
8466       return SDValue();
8467     case 16:
8468       // Same as global/flat
8469       if (NumElements > 4)
8470         return SplitVectorLoad(Op, DAG);
8471       // v3 loads not supported on SI.
8472       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8473         return WidenOrSplitVectorLoad(Op, DAG);
8474 
8475       return SDValue();
8476     default:
8477       llvm_unreachable("unsupported private_element_size");
8478     }
8479   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8480     // Use ds_read_b128 or ds_read_b96 when possible.
8481     if (Subtarget->hasDS96AndDS128() &&
8482         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8483          MemVT.getStoreSize() == 12) &&
8484         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8485                                            Load->getAlign()))
8486       return SDValue();
8487 
8488     if (NumElements > 2)
8489       return SplitVectorLoad(Op, DAG);
8490 
8491     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8492     // address is negative, then the instruction is incorrectly treated as
8493     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8494     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8495     // load later in the SILoadStoreOptimizer.
8496     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8497         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8498         Load->getAlignment() < 8) {
8499       return SplitVectorLoad(Op, DAG);
8500     }
8501   }
8502 
8503   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8504                                       MemVT, *Load->getMemOperand())) {
8505     SDValue Ops[2];
8506     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8507     return DAG.getMergeValues(Ops, DL);
8508   }
8509 
8510   return SDValue();
8511 }
8512 
8513 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8514   EVT VT = Op.getValueType();
8515   if (VT.getSizeInBits() == 128)
8516     return splitTernaryVectorOp(Op, DAG);
8517 
8518   assert(VT.getSizeInBits() == 64);
8519 
8520   SDLoc DL(Op);
8521   SDValue Cond = Op.getOperand(0);
8522 
8523   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8524   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8525 
8526   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8527   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8528 
8529   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8530   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8531 
8532   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8533 
8534   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8535   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8536 
8537   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8538 
8539   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8540   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8541 }
8542 
8543 // Catch division cases where we can use shortcuts with rcp and rsq
8544 // instructions.
8545 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8546                                               SelectionDAG &DAG) const {
8547   SDLoc SL(Op);
8548   SDValue LHS = Op.getOperand(0);
8549   SDValue RHS = Op.getOperand(1);
8550   EVT VT = Op.getValueType();
8551   const SDNodeFlags Flags = Op->getFlags();
8552 
8553   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8554 
8555   // Without !fpmath accuracy information, we can't do more because we don't
8556   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8557   if (!AllowInaccurateRcp)
8558     return SDValue();
8559 
8560   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8561     if (CLHS->isExactlyValue(1.0)) {
8562       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8563       // the CI documentation has a worst case error of 1 ulp.
8564       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8565       // use it as long as we aren't trying to use denormals.
8566       //
8567       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8568 
8569       // 1.0 / sqrt(x) -> rsq(x)
8570 
8571       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8572       // error seems really high at 2^29 ULP.
8573       if (RHS.getOpcode() == ISD::FSQRT)
8574         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8575 
8576       // 1.0 / x -> rcp(x)
8577       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8578     }
8579 
8580     // Same as for 1.0, but expand the sign out of the constant.
8581     if (CLHS->isExactlyValue(-1.0)) {
8582       // -1.0 / x -> rcp (fneg x)
8583       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8584       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8585     }
8586   }
8587 
8588   // Turn into multiply by the reciprocal.
8589   // x / y -> x * (1.0 / y)
8590   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8591   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8592 }
8593 
8594 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8595                                                 SelectionDAG &DAG) const {
8596   SDLoc SL(Op);
8597   SDValue X = Op.getOperand(0);
8598   SDValue Y = Op.getOperand(1);
8599   EVT VT = Op.getValueType();
8600   const SDNodeFlags Flags = Op->getFlags();
8601 
8602   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8603                             DAG.getTarget().Options.UnsafeFPMath;
8604   if (!AllowInaccurateDiv)
8605     return SDValue();
8606 
8607   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8608   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8609 
8610   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8611   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8612 
8613   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8614   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8615   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8616   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8617   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8618   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8619 }
8620 
8621 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8622                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8623                           SDNodeFlags Flags) {
8624   if (GlueChain->getNumValues() <= 1) {
8625     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8626   }
8627 
8628   assert(GlueChain->getNumValues() == 3);
8629 
8630   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8631   switch (Opcode) {
8632   default: llvm_unreachable("no chain equivalent for opcode");
8633   case ISD::FMUL:
8634     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8635     break;
8636   }
8637 
8638   return DAG.getNode(Opcode, SL, VTList,
8639                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8640                      Flags);
8641 }
8642 
8643 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8644                            EVT VT, SDValue A, SDValue B, SDValue C,
8645                            SDValue GlueChain, SDNodeFlags Flags) {
8646   if (GlueChain->getNumValues() <= 1) {
8647     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8648   }
8649 
8650   assert(GlueChain->getNumValues() == 3);
8651 
8652   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8653   switch (Opcode) {
8654   default: llvm_unreachable("no chain equivalent for opcode");
8655   case ISD::FMA:
8656     Opcode = AMDGPUISD::FMA_W_CHAIN;
8657     break;
8658   }
8659 
8660   return DAG.getNode(Opcode, SL, VTList,
8661                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8662                      Flags);
8663 }
8664 
8665 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8666   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8667     return FastLowered;
8668 
8669   SDLoc SL(Op);
8670   SDValue Src0 = Op.getOperand(0);
8671   SDValue Src1 = Op.getOperand(1);
8672 
8673   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8674   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8675 
8676   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8677   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8678 
8679   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8680   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8681 
8682   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8683 }
8684 
8685 // Faster 2.5 ULP division that does not support denormals.
8686 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8687   SDLoc SL(Op);
8688   SDValue LHS = Op.getOperand(1);
8689   SDValue RHS = Op.getOperand(2);
8690 
8691   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8692 
8693   const APFloat K0Val(BitsToFloat(0x6f800000));
8694   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8695 
8696   const APFloat K1Val(BitsToFloat(0x2f800000));
8697   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8698 
8699   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8700 
8701   EVT SetCCVT =
8702     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8703 
8704   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8705 
8706   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8707 
8708   // TODO: Should this propagate fast-math-flags?
8709   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8710 
8711   // rcp does not support denormals.
8712   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8713 
8714   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8715 
8716   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8717 }
8718 
8719 // Returns immediate value for setting the F32 denorm mode when using the
8720 // S_DENORM_MODE instruction.
8721 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8722                                     const SDLoc &SL, const GCNSubtarget *ST) {
8723   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8724   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8725                                 ? FP_DENORM_FLUSH_NONE
8726                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8727 
8728   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8729   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8730 }
8731 
8732 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8733   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8734     return FastLowered;
8735 
8736   // The selection matcher assumes anything with a chain selecting to a
8737   // mayRaiseFPException machine instruction. Since we're introducing a chain
8738   // here, we need to explicitly report nofpexcept for the regular fdiv
8739   // lowering.
8740   SDNodeFlags Flags = Op->getFlags();
8741   Flags.setNoFPExcept(true);
8742 
8743   SDLoc SL(Op);
8744   SDValue LHS = Op.getOperand(0);
8745   SDValue RHS = Op.getOperand(1);
8746 
8747   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8748 
8749   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8750 
8751   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8752                                           {RHS, RHS, LHS}, Flags);
8753   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8754                                         {LHS, RHS, LHS}, Flags);
8755 
8756   // Denominator is scaled to not be denormal, so using rcp is ok.
8757   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8758                                   DenominatorScaled, Flags);
8759   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8760                                      DenominatorScaled, Flags);
8761 
8762   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8763                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8764                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8765   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8766 
8767   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8768 
8769   if (!HasFP32Denormals) {
8770     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8771     // lowering. The chain dependence is insufficient, and we need glue. We do
8772     // not need the glue variants in a strictfp function.
8773 
8774     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8775 
8776     SDNode *EnableDenorm;
8777     if (Subtarget->hasDenormModeInst()) {
8778       const SDValue EnableDenormValue =
8779           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8780 
8781       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8782                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8783     } else {
8784       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8785                                                         SL, MVT::i32);
8786       EnableDenorm =
8787           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8788                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8789     }
8790 
8791     SDValue Ops[3] = {
8792       NegDivScale0,
8793       SDValue(EnableDenorm, 0),
8794       SDValue(EnableDenorm, 1)
8795     };
8796 
8797     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8798   }
8799 
8800   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8801                              ApproxRcp, One, NegDivScale0, Flags);
8802 
8803   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8804                              ApproxRcp, Fma0, Flags);
8805 
8806   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8807                            Fma1, Fma1, Flags);
8808 
8809   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8810                              NumeratorScaled, Mul, Flags);
8811 
8812   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8813                              Fma2, Fma1, Mul, Fma2, Flags);
8814 
8815   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8816                              NumeratorScaled, Fma3, Flags);
8817 
8818   if (!HasFP32Denormals) {
8819     SDNode *DisableDenorm;
8820     if (Subtarget->hasDenormModeInst()) {
8821       const SDValue DisableDenormValue =
8822           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8823 
8824       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8825                                   Fma4.getValue(1), DisableDenormValue,
8826                                   Fma4.getValue(2)).getNode();
8827     } else {
8828       const SDValue DisableDenormValue =
8829           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8830 
8831       DisableDenorm = DAG.getMachineNode(
8832           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8833           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8834     }
8835 
8836     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8837                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8838     DAG.setRoot(OutputChain);
8839   }
8840 
8841   SDValue Scale = NumeratorScaled.getValue(1);
8842   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8843                              {Fma4, Fma1, Fma3, Scale}, Flags);
8844 
8845   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8846 }
8847 
8848 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8849   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8850     return FastLowered;
8851 
8852   SDLoc SL(Op);
8853   SDValue X = Op.getOperand(0);
8854   SDValue Y = Op.getOperand(1);
8855 
8856   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8857 
8858   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8859 
8860   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8861 
8862   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8863 
8864   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8865 
8866   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8867 
8868   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8869 
8870   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8871 
8872   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8873 
8874   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8875   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8876 
8877   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8878                              NegDivScale0, Mul, DivScale1);
8879 
8880   SDValue Scale;
8881 
8882   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8883     // Workaround a hardware bug on SI where the condition output from div_scale
8884     // is not usable.
8885 
8886     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8887 
8888     // Figure out if the scale to use for div_fmas.
8889     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8890     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8891     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8892     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8893 
8894     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8895     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8896 
8897     SDValue Scale0Hi
8898       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8899     SDValue Scale1Hi
8900       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8901 
8902     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8903     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8904     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8905   } else {
8906     Scale = DivScale1.getValue(1);
8907   }
8908 
8909   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8910                              Fma4, Fma3, Mul, Scale);
8911 
8912   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8913 }
8914 
8915 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8916   EVT VT = Op.getValueType();
8917 
8918   if (VT == MVT::f32)
8919     return LowerFDIV32(Op, DAG);
8920 
8921   if (VT == MVT::f64)
8922     return LowerFDIV64(Op, DAG);
8923 
8924   if (VT == MVT::f16)
8925     return LowerFDIV16(Op, DAG);
8926 
8927   llvm_unreachable("Unexpected type for fdiv");
8928 }
8929 
8930 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8931   SDLoc DL(Op);
8932   StoreSDNode *Store = cast<StoreSDNode>(Op);
8933   EVT VT = Store->getMemoryVT();
8934 
8935   if (VT == MVT::i1) {
8936     return DAG.getTruncStore(Store->getChain(), DL,
8937        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8938        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8939   }
8940 
8941   assert(VT.isVector() &&
8942          Store->getValue().getValueType().getScalarType() == MVT::i32);
8943 
8944   unsigned AS = Store->getAddressSpace();
8945   if (Subtarget->hasLDSMisalignedBug() &&
8946       AS == AMDGPUAS::FLAT_ADDRESS &&
8947       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8948     return SplitVectorStore(Op, DAG);
8949   }
8950 
8951   MachineFunction &MF = DAG.getMachineFunction();
8952   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8953   // If there is a possibilty that flat instruction access scratch memory
8954   // then we need to use the same legalization rules we use for private.
8955   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8956       !Subtarget->hasMultiDwordFlatScratchAddressing())
8957     AS = MFI->hasFlatScratchInit() ?
8958          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8959 
8960   unsigned NumElements = VT.getVectorNumElements();
8961   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8962       AS == AMDGPUAS::FLAT_ADDRESS) {
8963     if (NumElements > 4)
8964       return SplitVectorStore(Op, DAG);
8965     // v3 stores not supported on SI.
8966     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8967       return SplitVectorStore(Op, DAG);
8968 
8969     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8970                                         VT, *Store->getMemOperand()))
8971       return expandUnalignedStore(Store, DAG);
8972 
8973     return SDValue();
8974   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8975     switch (Subtarget->getMaxPrivateElementSize()) {
8976     case 4:
8977       return scalarizeVectorStore(Store, DAG);
8978     case 8:
8979       if (NumElements > 2)
8980         return SplitVectorStore(Op, DAG);
8981       return SDValue();
8982     case 16:
8983       if (NumElements > 4 ||
8984           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8985         return SplitVectorStore(Op, DAG);
8986       return SDValue();
8987     default:
8988       llvm_unreachable("unsupported private_element_size");
8989     }
8990   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8991     // Use ds_write_b128 or ds_write_b96 when possible.
8992     if (Subtarget->hasDS96AndDS128() &&
8993         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8994          (VT.getStoreSize() == 12)) &&
8995         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8996                                            Store->getAlign()))
8997       return SDValue();
8998 
8999     if (NumElements > 2)
9000       return SplitVectorStore(Op, DAG);
9001 
9002     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
9003     // address is negative, then the instruction is incorrectly treated as
9004     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9005     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9006     // store later in the SILoadStoreOptimizer.
9007     if (!Subtarget->hasUsableDSOffset() &&
9008         NumElements == 2 && VT.getStoreSize() == 8 &&
9009         Store->getAlignment() < 8) {
9010       return SplitVectorStore(Op, DAG);
9011     }
9012 
9013     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9014                                         VT, *Store->getMemOperand())) {
9015       if (VT.isVector())
9016         return SplitVectorStore(Op, DAG);
9017       return expandUnalignedStore(Store, DAG);
9018     }
9019 
9020     return SDValue();
9021   } else {
9022     llvm_unreachable("unhandled address space");
9023   }
9024 }
9025 
9026 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9027   SDLoc DL(Op);
9028   EVT VT = Op.getValueType();
9029   SDValue Arg = Op.getOperand(0);
9030   SDValue TrigVal;
9031 
9032   // Propagate fast-math flags so that the multiply we introduce can be folded
9033   // if Arg is already the result of a multiply by constant.
9034   auto Flags = Op->getFlags();
9035 
9036   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9037 
9038   if (Subtarget->hasTrigReducedRange()) {
9039     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9040     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9041   } else {
9042     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9043   }
9044 
9045   switch (Op.getOpcode()) {
9046   case ISD::FCOS:
9047     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9048   case ISD::FSIN:
9049     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9050   default:
9051     llvm_unreachable("Wrong trig opcode");
9052   }
9053 }
9054 
9055 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9056   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9057   assert(AtomicNode->isCompareAndSwap());
9058   unsigned AS = AtomicNode->getAddressSpace();
9059 
9060   // No custom lowering required for local address space
9061   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9062     return Op;
9063 
9064   // Non-local address space requires custom lowering for atomic compare
9065   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9066   SDLoc DL(Op);
9067   SDValue ChainIn = Op.getOperand(0);
9068   SDValue Addr = Op.getOperand(1);
9069   SDValue Old = Op.getOperand(2);
9070   SDValue New = Op.getOperand(3);
9071   EVT VT = Op.getValueType();
9072   MVT SimpleVT = VT.getSimpleVT();
9073   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9074 
9075   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9076   SDValue Ops[] = { ChainIn, Addr, NewOld };
9077 
9078   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9079                                  Ops, VT, AtomicNode->getMemOperand());
9080 }
9081 
9082 //===----------------------------------------------------------------------===//
9083 // Custom DAG optimizations
9084 //===----------------------------------------------------------------------===//
9085 
9086 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9087                                                      DAGCombinerInfo &DCI) const {
9088   EVT VT = N->getValueType(0);
9089   EVT ScalarVT = VT.getScalarType();
9090   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9091     return SDValue();
9092 
9093   SelectionDAG &DAG = DCI.DAG;
9094   SDLoc DL(N);
9095 
9096   SDValue Src = N->getOperand(0);
9097   EVT SrcVT = Src.getValueType();
9098 
9099   // TODO: We could try to match extracting the higher bytes, which would be
9100   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9101   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9102   // about in practice.
9103   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9104     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9105       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9106       DCI.AddToWorklist(Cvt.getNode());
9107 
9108       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9109       if (ScalarVT != MVT::f32) {
9110         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9111                           DAG.getTargetConstant(0, DL, MVT::i32));
9112       }
9113       return Cvt;
9114     }
9115   }
9116 
9117   return SDValue();
9118 }
9119 
9120 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9121 
9122 // This is a variant of
9123 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9124 //
9125 // The normal DAG combiner will do this, but only if the add has one use since
9126 // that would increase the number of instructions.
9127 //
9128 // This prevents us from seeing a constant offset that can be folded into a
9129 // memory instruction's addressing mode. If we know the resulting add offset of
9130 // a pointer can be folded into an addressing offset, we can replace the pointer
9131 // operand with the add of new constant offset. This eliminates one of the uses,
9132 // and may allow the remaining use to also be simplified.
9133 //
9134 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9135                                                unsigned AddrSpace,
9136                                                EVT MemVT,
9137                                                DAGCombinerInfo &DCI) const {
9138   SDValue N0 = N->getOperand(0);
9139   SDValue N1 = N->getOperand(1);
9140 
9141   // We only do this to handle cases where it's profitable when there are
9142   // multiple uses of the add, so defer to the standard combine.
9143   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9144       N0->hasOneUse())
9145     return SDValue();
9146 
9147   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9148   if (!CN1)
9149     return SDValue();
9150 
9151   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9152   if (!CAdd)
9153     return SDValue();
9154 
9155   // If the resulting offset is too large, we can't fold it into the addressing
9156   // mode offset.
9157   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9158   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9159 
9160   AddrMode AM;
9161   AM.HasBaseReg = true;
9162   AM.BaseOffs = Offset.getSExtValue();
9163   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9164     return SDValue();
9165 
9166   SelectionDAG &DAG = DCI.DAG;
9167   SDLoc SL(N);
9168   EVT VT = N->getValueType(0);
9169 
9170   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9171   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9172 
9173   SDNodeFlags Flags;
9174   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9175                           (N0.getOpcode() == ISD::OR ||
9176                            N0->getFlags().hasNoUnsignedWrap()));
9177 
9178   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9179 }
9180 
9181 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9182 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9183 /// specific intrinsic, but they all place the pointer operand first.
9184 static unsigned getBasePtrIndex(const MemSDNode *N) {
9185   switch (N->getOpcode()) {
9186   case ISD::STORE:
9187   case ISD::INTRINSIC_W_CHAIN:
9188   case ISD::INTRINSIC_VOID:
9189     return 2;
9190   default:
9191     return 1;
9192   }
9193 }
9194 
9195 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9196                                                   DAGCombinerInfo &DCI) const {
9197   SelectionDAG &DAG = DCI.DAG;
9198   SDLoc SL(N);
9199 
9200   unsigned PtrIdx = getBasePtrIndex(N);
9201   SDValue Ptr = N->getOperand(PtrIdx);
9202 
9203   // TODO: We could also do this for multiplies.
9204   if (Ptr.getOpcode() == ISD::SHL) {
9205     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9206                                           N->getMemoryVT(), DCI);
9207     if (NewPtr) {
9208       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9209 
9210       NewOps[PtrIdx] = NewPtr;
9211       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9212     }
9213   }
9214 
9215   return SDValue();
9216 }
9217 
9218 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9219   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9220          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9221          (Opc == ISD::XOR && Val == 0);
9222 }
9223 
9224 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9225 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9226 // integer combine opportunities since most 64-bit operations are decomposed
9227 // this way.  TODO: We won't want this for SALU especially if it is an inline
9228 // immediate.
9229 SDValue SITargetLowering::splitBinaryBitConstantOp(
9230   DAGCombinerInfo &DCI,
9231   const SDLoc &SL,
9232   unsigned Opc, SDValue LHS,
9233   const ConstantSDNode *CRHS) const {
9234   uint64_t Val = CRHS->getZExtValue();
9235   uint32_t ValLo = Lo_32(Val);
9236   uint32_t ValHi = Hi_32(Val);
9237   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9238 
9239     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9240          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9241         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9242     // If we need to materialize a 64-bit immediate, it will be split up later
9243     // anyway. Avoid creating the harder to understand 64-bit immediate
9244     // materialization.
9245     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9246   }
9247 
9248   return SDValue();
9249 }
9250 
9251 // Returns true if argument is a boolean value which is not serialized into
9252 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9253 static bool isBoolSGPR(SDValue V) {
9254   if (V.getValueType() != MVT::i1)
9255     return false;
9256   switch (V.getOpcode()) {
9257   default:
9258     break;
9259   case ISD::SETCC:
9260   case AMDGPUISD::FP_CLASS:
9261     return true;
9262   case ISD::AND:
9263   case ISD::OR:
9264   case ISD::XOR:
9265     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9266   }
9267   return false;
9268 }
9269 
9270 // If a constant has all zeroes or all ones within each byte return it.
9271 // Otherwise return 0.
9272 static uint32_t getConstantPermuteMask(uint32_t C) {
9273   // 0xff for any zero byte in the mask
9274   uint32_t ZeroByteMask = 0;
9275   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9276   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9277   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9278   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9279   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9280   if ((NonZeroByteMask & C) != NonZeroByteMask)
9281     return 0; // Partial bytes selected.
9282   return C;
9283 }
9284 
9285 // Check if a node selects whole bytes from its operand 0 starting at a byte
9286 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9287 // or -1 if not succeeded.
9288 // Note byte select encoding:
9289 // value 0-3 selects corresponding source byte;
9290 // value 0xc selects zero;
9291 // value 0xff selects 0xff.
9292 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9293   assert(V.getValueSizeInBits() == 32);
9294 
9295   if (V.getNumOperands() != 2)
9296     return ~0;
9297 
9298   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9299   if (!N1)
9300     return ~0;
9301 
9302   uint32_t C = N1->getZExtValue();
9303 
9304   switch (V.getOpcode()) {
9305   default:
9306     break;
9307   case ISD::AND:
9308     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9309       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9310     }
9311     break;
9312 
9313   case ISD::OR:
9314     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9315       return (0x03020100 & ~ConstMask) | ConstMask;
9316     }
9317     break;
9318 
9319   case ISD::SHL:
9320     if (C % 8)
9321       return ~0;
9322 
9323     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9324 
9325   case ISD::SRL:
9326     if (C % 8)
9327       return ~0;
9328 
9329     return uint32_t(0x0c0c0c0c03020100ull >> C);
9330   }
9331 
9332   return ~0;
9333 }
9334 
9335 SDValue SITargetLowering::performAndCombine(SDNode *N,
9336                                             DAGCombinerInfo &DCI) const {
9337   if (DCI.isBeforeLegalize())
9338     return SDValue();
9339 
9340   SelectionDAG &DAG = DCI.DAG;
9341   EVT VT = N->getValueType(0);
9342   SDValue LHS = N->getOperand(0);
9343   SDValue RHS = N->getOperand(1);
9344 
9345 
9346   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9347   if (VT == MVT::i64 && CRHS) {
9348     if (SDValue Split
9349         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9350       return Split;
9351   }
9352 
9353   if (CRHS && VT == MVT::i32) {
9354     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9355     // nb = number of trailing zeroes in mask
9356     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9357     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9358     uint64_t Mask = CRHS->getZExtValue();
9359     unsigned Bits = countPopulation(Mask);
9360     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9361         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9362       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9363         unsigned Shift = CShift->getZExtValue();
9364         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9365         unsigned Offset = NB + Shift;
9366         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9367           SDLoc SL(N);
9368           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9369                                     LHS->getOperand(0),
9370                                     DAG.getConstant(Offset, SL, MVT::i32),
9371                                     DAG.getConstant(Bits, SL, MVT::i32));
9372           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9373           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9374                                     DAG.getValueType(NarrowVT));
9375           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9376                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9377           return Shl;
9378         }
9379       }
9380     }
9381 
9382     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9383     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9384         isa<ConstantSDNode>(LHS.getOperand(2))) {
9385       uint32_t Sel = getConstantPermuteMask(Mask);
9386       if (!Sel)
9387         return SDValue();
9388 
9389       // Select 0xc for all zero bytes
9390       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9391       SDLoc DL(N);
9392       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9393                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9394     }
9395   }
9396 
9397   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9398   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9399   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9400     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9401     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9402 
9403     SDValue X = LHS.getOperand(0);
9404     SDValue Y = RHS.getOperand(0);
9405     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9406       return SDValue();
9407 
9408     if (LCC == ISD::SETO) {
9409       if (X != LHS.getOperand(1))
9410         return SDValue();
9411 
9412       if (RCC == ISD::SETUNE) {
9413         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9414         if (!C1 || !C1->isInfinity() || C1->isNegative())
9415           return SDValue();
9416 
9417         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9418                               SIInstrFlags::N_SUBNORMAL |
9419                               SIInstrFlags::N_ZERO |
9420                               SIInstrFlags::P_ZERO |
9421                               SIInstrFlags::P_SUBNORMAL |
9422                               SIInstrFlags::P_NORMAL;
9423 
9424         static_assert(((~(SIInstrFlags::S_NAN |
9425                           SIInstrFlags::Q_NAN |
9426                           SIInstrFlags::N_INFINITY |
9427                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9428                       "mask not equal");
9429 
9430         SDLoc DL(N);
9431         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9432                            X, DAG.getConstant(Mask, DL, MVT::i32));
9433       }
9434     }
9435   }
9436 
9437   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9438     std::swap(LHS, RHS);
9439 
9440   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9441       RHS.hasOneUse()) {
9442     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9443     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9444     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9445     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9446     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9447         (RHS.getOperand(0) == LHS.getOperand(0) &&
9448          LHS.getOperand(0) == LHS.getOperand(1))) {
9449       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9450       unsigned NewMask = LCC == ISD::SETO ?
9451         Mask->getZExtValue() & ~OrdMask :
9452         Mask->getZExtValue() & OrdMask;
9453 
9454       SDLoc DL(N);
9455       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9456                          DAG.getConstant(NewMask, DL, MVT::i32));
9457     }
9458   }
9459 
9460   if (VT == MVT::i32 &&
9461       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9462     // and x, (sext cc from i1) => select cc, x, 0
9463     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9464       std::swap(LHS, RHS);
9465     if (isBoolSGPR(RHS.getOperand(0)))
9466       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9467                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9468   }
9469 
9470   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9471   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9472   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9473       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9474     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9475     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9476     if (LHSMask != ~0u && RHSMask != ~0u) {
9477       // Canonicalize the expression in an attempt to have fewer unique masks
9478       // and therefore fewer registers used to hold the masks.
9479       if (LHSMask > RHSMask) {
9480         std::swap(LHSMask, RHSMask);
9481         std::swap(LHS, RHS);
9482       }
9483 
9484       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9485       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9486       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9487       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9488 
9489       // Check of we need to combine values from two sources within a byte.
9490       if (!(LHSUsedLanes & RHSUsedLanes) &&
9491           // If we select high and lower word keep it for SDWA.
9492           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9493           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9494         // Each byte in each mask is either selector mask 0-3, or has higher
9495         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9496         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9497         // mask which is not 0xff wins. By anding both masks we have a correct
9498         // result except that 0x0c shall be corrected to give 0x0c only.
9499         uint32_t Mask = LHSMask & RHSMask;
9500         for (unsigned I = 0; I < 32; I += 8) {
9501           uint32_t ByteSel = 0xff << I;
9502           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9503             Mask &= (0x0c << I) & 0xffffffff;
9504         }
9505 
9506         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9507         // or 0x0c.
9508         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9509         SDLoc DL(N);
9510 
9511         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9512                            LHS.getOperand(0), RHS.getOperand(0),
9513                            DAG.getConstant(Sel, DL, MVT::i32));
9514       }
9515     }
9516   }
9517 
9518   return SDValue();
9519 }
9520 
9521 SDValue SITargetLowering::performOrCombine(SDNode *N,
9522                                            DAGCombinerInfo &DCI) const {
9523   SelectionDAG &DAG = DCI.DAG;
9524   SDValue LHS = N->getOperand(0);
9525   SDValue RHS = N->getOperand(1);
9526 
9527   EVT VT = N->getValueType(0);
9528   if (VT == MVT::i1) {
9529     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9530     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9531         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9532       SDValue Src = LHS.getOperand(0);
9533       if (Src != RHS.getOperand(0))
9534         return SDValue();
9535 
9536       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9537       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9538       if (!CLHS || !CRHS)
9539         return SDValue();
9540 
9541       // Only 10 bits are used.
9542       static const uint32_t MaxMask = 0x3ff;
9543 
9544       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9545       SDLoc DL(N);
9546       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9547                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9548     }
9549 
9550     return SDValue();
9551   }
9552 
9553   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9554   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9555       LHS.getOpcode() == AMDGPUISD::PERM &&
9556       isa<ConstantSDNode>(LHS.getOperand(2))) {
9557     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9558     if (!Sel)
9559       return SDValue();
9560 
9561     Sel |= LHS.getConstantOperandVal(2);
9562     SDLoc DL(N);
9563     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9564                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9565   }
9566 
9567   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9568   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9569   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9570       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9571     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9572     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9573     if (LHSMask != ~0u && RHSMask != ~0u) {
9574       // Canonicalize the expression in an attempt to have fewer unique masks
9575       // and therefore fewer registers used to hold the masks.
9576       if (LHSMask > RHSMask) {
9577         std::swap(LHSMask, RHSMask);
9578         std::swap(LHS, RHS);
9579       }
9580 
9581       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9582       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9583       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9584       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9585 
9586       // Check of we need to combine values from two sources within a byte.
9587       if (!(LHSUsedLanes & RHSUsedLanes) &&
9588           // If we select high and lower word keep it for SDWA.
9589           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9590           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9591         // Kill zero bytes selected by other mask. Zero value is 0xc.
9592         LHSMask &= ~RHSUsedLanes;
9593         RHSMask &= ~LHSUsedLanes;
9594         // Add 4 to each active LHS lane
9595         LHSMask |= LHSUsedLanes & 0x04040404;
9596         // Combine masks
9597         uint32_t Sel = LHSMask | RHSMask;
9598         SDLoc DL(N);
9599 
9600         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9601                            LHS.getOperand(0), RHS.getOperand(0),
9602                            DAG.getConstant(Sel, DL, MVT::i32));
9603       }
9604     }
9605   }
9606 
9607   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9608     return SDValue();
9609 
9610   // TODO: This could be a generic combine with a predicate for extracting the
9611   // high half of an integer being free.
9612 
9613   // (or i64:x, (zero_extend i32:y)) ->
9614   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9615   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9616       RHS.getOpcode() != ISD::ZERO_EXTEND)
9617     std::swap(LHS, RHS);
9618 
9619   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9620     SDValue ExtSrc = RHS.getOperand(0);
9621     EVT SrcVT = ExtSrc.getValueType();
9622     if (SrcVT == MVT::i32) {
9623       SDLoc SL(N);
9624       SDValue LowLHS, HiBits;
9625       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9626       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9627 
9628       DCI.AddToWorklist(LowOr.getNode());
9629       DCI.AddToWorklist(HiBits.getNode());
9630 
9631       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9632                                 LowOr, HiBits);
9633       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9634     }
9635   }
9636 
9637   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9638   if (CRHS) {
9639     if (SDValue Split
9640           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9641                                      N->getOperand(0), CRHS))
9642       return Split;
9643   }
9644 
9645   return SDValue();
9646 }
9647 
9648 SDValue SITargetLowering::performXorCombine(SDNode *N,
9649                                             DAGCombinerInfo &DCI) const {
9650   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9651     return RV;
9652 
9653   EVT VT = N->getValueType(0);
9654   if (VT != MVT::i64)
9655     return SDValue();
9656 
9657   SDValue LHS = N->getOperand(0);
9658   SDValue RHS = N->getOperand(1);
9659 
9660   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9661   if (CRHS) {
9662     if (SDValue Split
9663           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9664       return Split;
9665   }
9666 
9667   return SDValue();
9668 }
9669 
9670 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9671                                                    DAGCombinerInfo &DCI) const {
9672   if (!Subtarget->has16BitInsts() ||
9673       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9674     return SDValue();
9675 
9676   EVT VT = N->getValueType(0);
9677   if (VT != MVT::i32)
9678     return SDValue();
9679 
9680   SDValue Src = N->getOperand(0);
9681   if (Src.getValueType() != MVT::i16)
9682     return SDValue();
9683 
9684   return SDValue();
9685 }
9686 
9687 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9688                                                         DAGCombinerInfo &DCI)
9689                                                         const {
9690   SDValue Src = N->getOperand(0);
9691   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9692 
9693   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9694       VTSign->getVT() == MVT::i8) ||
9695       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9696       VTSign->getVT() == MVT::i16)) &&
9697       Src.hasOneUse()) {
9698     auto *M = cast<MemSDNode>(Src);
9699     SDValue Ops[] = {
9700       Src.getOperand(0), // Chain
9701       Src.getOperand(1), // rsrc
9702       Src.getOperand(2), // vindex
9703       Src.getOperand(3), // voffset
9704       Src.getOperand(4), // soffset
9705       Src.getOperand(5), // offset
9706       Src.getOperand(6),
9707       Src.getOperand(7)
9708     };
9709     // replace with BUFFER_LOAD_BYTE/SHORT
9710     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9711                                          Src.getOperand(0).getValueType());
9712     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9713                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9714     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9715                                                           ResList,
9716                                                           Ops, M->getMemoryVT(),
9717                                                           M->getMemOperand());
9718     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9719                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9720   }
9721   return SDValue();
9722 }
9723 
9724 SDValue SITargetLowering::performClassCombine(SDNode *N,
9725                                               DAGCombinerInfo &DCI) const {
9726   SelectionDAG &DAG = DCI.DAG;
9727   SDValue Mask = N->getOperand(1);
9728 
9729   // fp_class x, 0 -> false
9730   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9731     if (CMask->isZero())
9732       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9733   }
9734 
9735   if (N->getOperand(0).isUndef())
9736     return DAG.getUNDEF(MVT::i1);
9737 
9738   return SDValue();
9739 }
9740 
9741 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9742                                             DAGCombinerInfo &DCI) const {
9743   EVT VT = N->getValueType(0);
9744   SDValue N0 = N->getOperand(0);
9745 
9746   if (N0.isUndef())
9747     return N0;
9748 
9749   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9750                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9751     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9752                            N->getFlags());
9753   }
9754 
9755   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9756     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9757                            N0.getOperand(0), N->getFlags());
9758   }
9759 
9760   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9761 }
9762 
9763 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9764                                        unsigned MaxDepth) const {
9765   unsigned Opcode = Op.getOpcode();
9766   if (Opcode == ISD::FCANONICALIZE)
9767     return true;
9768 
9769   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9770     auto F = CFP->getValueAPF();
9771     if (F.isNaN() && F.isSignaling())
9772       return false;
9773     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9774   }
9775 
9776   // If source is a result of another standard FP operation it is already in
9777   // canonical form.
9778   if (MaxDepth == 0)
9779     return false;
9780 
9781   switch (Opcode) {
9782   // These will flush denorms if required.
9783   case ISD::FADD:
9784   case ISD::FSUB:
9785   case ISD::FMUL:
9786   case ISD::FCEIL:
9787   case ISD::FFLOOR:
9788   case ISD::FMA:
9789   case ISD::FMAD:
9790   case ISD::FSQRT:
9791   case ISD::FDIV:
9792   case ISD::FREM:
9793   case ISD::FP_ROUND:
9794   case ISD::FP_EXTEND:
9795   case AMDGPUISD::FMUL_LEGACY:
9796   case AMDGPUISD::FMAD_FTZ:
9797   case AMDGPUISD::RCP:
9798   case AMDGPUISD::RSQ:
9799   case AMDGPUISD::RSQ_CLAMP:
9800   case AMDGPUISD::RCP_LEGACY:
9801   case AMDGPUISD::RCP_IFLAG:
9802   case AMDGPUISD::DIV_SCALE:
9803   case AMDGPUISD::DIV_FMAS:
9804   case AMDGPUISD::DIV_FIXUP:
9805   case AMDGPUISD::FRACT:
9806   case AMDGPUISD::LDEXP:
9807   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9808   case AMDGPUISD::CVT_F32_UBYTE0:
9809   case AMDGPUISD::CVT_F32_UBYTE1:
9810   case AMDGPUISD::CVT_F32_UBYTE2:
9811   case AMDGPUISD::CVT_F32_UBYTE3:
9812     return true;
9813 
9814   // It can/will be lowered or combined as a bit operation.
9815   // Need to check their input recursively to handle.
9816   case ISD::FNEG:
9817   case ISD::FABS:
9818   case ISD::FCOPYSIGN:
9819     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9820 
9821   case ISD::FSIN:
9822   case ISD::FCOS:
9823   case ISD::FSINCOS:
9824     return Op.getValueType().getScalarType() != MVT::f16;
9825 
9826   case ISD::FMINNUM:
9827   case ISD::FMAXNUM:
9828   case ISD::FMINNUM_IEEE:
9829   case ISD::FMAXNUM_IEEE:
9830   case AMDGPUISD::CLAMP:
9831   case AMDGPUISD::FMED3:
9832   case AMDGPUISD::FMAX3:
9833   case AMDGPUISD::FMIN3: {
9834     // FIXME: Shouldn't treat the generic operations different based these.
9835     // However, we aren't really required to flush the result from
9836     // minnum/maxnum..
9837 
9838     // snans will be quieted, so we only need to worry about denormals.
9839     if (Subtarget->supportsMinMaxDenormModes() ||
9840         denormalsEnabledForType(DAG, Op.getValueType()))
9841       return true;
9842 
9843     // Flushing may be required.
9844     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9845     // targets need to check their input recursively.
9846 
9847     // FIXME: Does this apply with clamp? It's implemented with max.
9848     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9849       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9850         return false;
9851     }
9852 
9853     return true;
9854   }
9855   case ISD::SELECT: {
9856     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9857            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9858   }
9859   case ISD::BUILD_VECTOR: {
9860     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9861       SDValue SrcOp = Op.getOperand(i);
9862       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9863         return false;
9864     }
9865 
9866     return true;
9867   }
9868   case ISD::EXTRACT_VECTOR_ELT:
9869   case ISD::EXTRACT_SUBVECTOR: {
9870     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9871   }
9872   case ISD::INSERT_VECTOR_ELT: {
9873     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9874            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9875   }
9876   case ISD::UNDEF:
9877     // Could be anything.
9878     return false;
9879 
9880   case ISD::BITCAST:
9881     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9882   case ISD::TRUNCATE: {
9883     // Hack round the mess we make when legalizing extract_vector_elt
9884     if (Op.getValueType() == MVT::i16) {
9885       SDValue TruncSrc = Op.getOperand(0);
9886       if (TruncSrc.getValueType() == MVT::i32 &&
9887           TruncSrc.getOpcode() == ISD::BITCAST &&
9888           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9889         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9890       }
9891     }
9892     return false;
9893   }
9894   case ISD::INTRINSIC_WO_CHAIN: {
9895     unsigned IntrinsicID
9896       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9897     // TODO: Handle more intrinsics
9898     switch (IntrinsicID) {
9899     case Intrinsic::amdgcn_cvt_pkrtz:
9900     case Intrinsic::amdgcn_cubeid:
9901     case Intrinsic::amdgcn_frexp_mant:
9902     case Intrinsic::amdgcn_fdot2:
9903     case Intrinsic::amdgcn_rcp:
9904     case Intrinsic::amdgcn_rsq:
9905     case Intrinsic::amdgcn_rsq_clamp:
9906     case Intrinsic::amdgcn_rcp_legacy:
9907     case Intrinsic::amdgcn_rsq_legacy:
9908     case Intrinsic::amdgcn_trig_preop:
9909       return true;
9910     default:
9911       break;
9912     }
9913 
9914     LLVM_FALLTHROUGH;
9915   }
9916   default:
9917     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9918            DAG.isKnownNeverSNaN(Op);
9919   }
9920 
9921   llvm_unreachable("invalid operation");
9922 }
9923 
9924 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9925                                        unsigned MaxDepth) const {
9926   MachineRegisterInfo &MRI = MF.getRegInfo();
9927   MachineInstr *MI = MRI.getVRegDef(Reg);
9928   unsigned Opcode = MI->getOpcode();
9929 
9930   if (Opcode == AMDGPU::G_FCANONICALIZE)
9931     return true;
9932 
9933   Optional<FPValueAndVReg> FCR;
9934   // Constant splat (can be padded with undef) or scalar constant.
9935   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9936     if (FCR->Value.isSignaling())
9937       return false;
9938     return !FCR->Value.isDenormal() ||
9939            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9940   }
9941 
9942   if (MaxDepth == 0)
9943     return false;
9944 
9945   switch (Opcode) {
9946   case AMDGPU::G_FMINNUM_IEEE:
9947   case AMDGPU::G_FMAXNUM_IEEE: {
9948     if (Subtarget->supportsMinMaxDenormModes() ||
9949         denormalsEnabledForType(MRI.getType(Reg), MF))
9950       return true;
9951     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9952       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9953         return false;
9954     return true;
9955   }
9956   default:
9957     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9958            isKnownNeverSNaN(Reg, MRI);
9959   }
9960 
9961   llvm_unreachable("invalid operation");
9962 }
9963 
9964 // Constant fold canonicalize.
9965 SDValue SITargetLowering::getCanonicalConstantFP(
9966   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9967   // Flush denormals to 0 if not enabled.
9968   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9969     return DAG.getConstantFP(0.0, SL, VT);
9970 
9971   if (C.isNaN()) {
9972     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9973     if (C.isSignaling()) {
9974       // Quiet a signaling NaN.
9975       // FIXME: Is this supposed to preserve payload bits?
9976       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9977     }
9978 
9979     // Make sure it is the canonical NaN bitpattern.
9980     //
9981     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9982     // immediate?
9983     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9984       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9985   }
9986 
9987   // Already canonical.
9988   return DAG.getConstantFP(C, SL, VT);
9989 }
9990 
9991 static bool vectorEltWillFoldAway(SDValue Op) {
9992   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9993 }
9994 
9995 SDValue SITargetLowering::performFCanonicalizeCombine(
9996   SDNode *N,
9997   DAGCombinerInfo &DCI) const {
9998   SelectionDAG &DAG = DCI.DAG;
9999   SDValue N0 = N->getOperand(0);
10000   EVT VT = N->getValueType(0);
10001 
10002   // fcanonicalize undef -> qnan
10003   if (N0.isUndef()) {
10004     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10005     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10006   }
10007 
10008   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10009     EVT VT = N->getValueType(0);
10010     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10011   }
10012 
10013   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10014   //                                                   (fcanonicalize k)
10015   //
10016   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10017 
10018   // TODO: This could be better with wider vectors that will be split to v2f16,
10019   // and to consider uses since there aren't that many packed operations.
10020   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10021       isTypeLegal(MVT::v2f16)) {
10022     SDLoc SL(N);
10023     SDValue NewElts[2];
10024     SDValue Lo = N0.getOperand(0);
10025     SDValue Hi = N0.getOperand(1);
10026     EVT EltVT = Lo.getValueType();
10027 
10028     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10029       for (unsigned I = 0; I != 2; ++I) {
10030         SDValue Op = N0.getOperand(I);
10031         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10032           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10033                                               CFP->getValueAPF());
10034         } else if (Op.isUndef()) {
10035           // Handled below based on what the other operand is.
10036           NewElts[I] = Op;
10037         } else {
10038           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10039         }
10040       }
10041 
10042       // If one half is undef, and one is constant, perfer a splat vector rather
10043       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10044       // cheaper to use and may be free with a packed operation.
10045       if (NewElts[0].isUndef()) {
10046         if (isa<ConstantFPSDNode>(NewElts[1]))
10047           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10048             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10049       }
10050 
10051       if (NewElts[1].isUndef()) {
10052         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10053           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10054       }
10055 
10056       return DAG.getBuildVector(VT, SL, NewElts);
10057     }
10058   }
10059 
10060   unsigned SrcOpc = N0.getOpcode();
10061 
10062   // If it's free to do so, push canonicalizes further up the source, which may
10063   // find a canonical source.
10064   //
10065   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10066   // sNaNs.
10067   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10068     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10069     if (CRHS && N0.hasOneUse()) {
10070       SDLoc SL(N);
10071       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10072                                    N0.getOperand(0));
10073       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10074       DCI.AddToWorklist(Canon0.getNode());
10075 
10076       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10077     }
10078   }
10079 
10080   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10081 }
10082 
10083 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10084   switch (Opc) {
10085   case ISD::FMAXNUM:
10086   case ISD::FMAXNUM_IEEE:
10087     return AMDGPUISD::FMAX3;
10088   case ISD::SMAX:
10089     return AMDGPUISD::SMAX3;
10090   case ISD::UMAX:
10091     return AMDGPUISD::UMAX3;
10092   case ISD::FMINNUM:
10093   case ISD::FMINNUM_IEEE:
10094     return AMDGPUISD::FMIN3;
10095   case ISD::SMIN:
10096     return AMDGPUISD::SMIN3;
10097   case ISD::UMIN:
10098     return AMDGPUISD::UMIN3;
10099   default:
10100     llvm_unreachable("Not a min/max opcode");
10101   }
10102 }
10103 
10104 SDValue SITargetLowering::performIntMed3ImmCombine(
10105   SelectionDAG &DAG, const SDLoc &SL,
10106   SDValue Op0, SDValue Op1, bool Signed) const {
10107   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10108   if (!K1)
10109     return SDValue();
10110 
10111   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10112   if (!K0)
10113     return SDValue();
10114 
10115   if (Signed) {
10116     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10117       return SDValue();
10118   } else {
10119     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10120       return SDValue();
10121   }
10122 
10123   EVT VT = K0->getValueType(0);
10124   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10125   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10126     return DAG.getNode(Med3Opc, SL, VT,
10127                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10128   }
10129 
10130   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10131   if (VT == MVT::i16) {
10132     MVT NVT = MVT::i32;
10133     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10134 
10135     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10136     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10137     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10138 
10139     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10140     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10141   }
10142 
10143   return SDValue();
10144 }
10145 
10146 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10147   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10148     return C;
10149 
10150   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10151     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10152       return C;
10153   }
10154 
10155   return nullptr;
10156 }
10157 
10158 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10159                                                   const SDLoc &SL,
10160                                                   SDValue Op0,
10161                                                   SDValue Op1) const {
10162   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10163   if (!K1)
10164     return SDValue();
10165 
10166   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10167   if (!K0)
10168     return SDValue();
10169 
10170   // Ordered >= (although NaN inputs should have folded away by now).
10171   if (K0->getValueAPF() > K1->getValueAPF())
10172     return SDValue();
10173 
10174   const MachineFunction &MF = DAG.getMachineFunction();
10175   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10176 
10177   // TODO: Check IEEE bit enabled?
10178   EVT VT = Op0.getValueType();
10179   if (Info->getMode().DX10Clamp) {
10180     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10181     // hardware fmed3 behavior converting to a min.
10182     // FIXME: Should this be allowing -0.0?
10183     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10184       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10185   }
10186 
10187   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10188   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10189     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10190     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10191     // then give the other result, which is different from med3 with a NaN
10192     // input.
10193     SDValue Var = Op0.getOperand(0);
10194     if (!DAG.isKnownNeverSNaN(Var))
10195       return SDValue();
10196 
10197     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10198 
10199     if ((!K0->hasOneUse() ||
10200          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10201         (!K1->hasOneUse() ||
10202          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10203       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10204                          Var, SDValue(K0, 0), SDValue(K1, 0));
10205     }
10206   }
10207 
10208   return SDValue();
10209 }
10210 
10211 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10212                                                DAGCombinerInfo &DCI) const {
10213   SelectionDAG &DAG = DCI.DAG;
10214 
10215   EVT VT = N->getValueType(0);
10216   unsigned Opc = N->getOpcode();
10217   SDValue Op0 = N->getOperand(0);
10218   SDValue Op1 = N->getOperand(1);
10219 
10220   // Only do this if the inner op has one use since this will just increases
10221   // register pressure for no benefit.
10222 
10223   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10224       !VT.isVector() &&
10225       (VT == MVT::i32 || VT == MVT::f32 ||
10226        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10227     // max(max(a, b), c) -> max3(a, b, c)
10228     // min(min(a, b), c) -> min3(a, b, c)
10229     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10230       SDLoc DL(N);
10231       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10232                          DL,
10233                          N->getValueType(0),
10234                          Op0.getOperand(0),
10235                          Op0.getOperand(1),
10236                          Op1);
10237     }
10238 
10239     // Try commuted.
10240     // max(a, max(b, c)) -> max3(a, b, c)
10241     // min(a, min(b, c)) -> min3(a, b, c)
10242     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10243       SDLoc DL(N);
10244       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10245                          DL,
10246                          N->getValueType(0),
10247                          Op0,
10248                          Op1.getOperand(0),
10249                          Op1.getOperand(1));
10250     }
10251   }
10252 
10253   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10254   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10255     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10256       return Med3;
10257   }
10258 
10259   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10260     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10261       return Med3;
10262   }
10263 
10264   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10265   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10266        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10267        (Opc == AMDGPUISD::FMIN_LEGACY &&
10268         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10269       (VT == MVT::f32 || VT == MVT::f64 ||
10270        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10271        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10272       Op0.hasOneUse()) {
10273     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10274       return Res;
10275   }
10276 
10277   return SDValue();
10278 }
10279 
10280 static bool isClampZeroToOne(SDValue A, SDValue B) {
10281   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10282     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10283       // FIXME: Should this be allowing -0.0?
10284       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10285              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10286     }
10287   }
10288 
10289   return false;
10290 }
10291 
10292 // FIXME: Should only worry about snans for version with chain.
10293 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10294                                               DAGCombinerInfo &DCI) const {
10295   EVT VT = N->getValueType(0);
10296   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10297   // NaNs. With a NaN input, the order of the operands may change the result.
10298 
10299   SelectionDAG &DAG = DCI.DAG;
10300   SDLoc SL(N);
10301 
10302   SDValue Src0 = N->getOperand(0);
10303   SDValue Src1 = N->getOperand(1);
10304   SDValue Src2 = N->getOperand(2);
10305 
10306   if (isClampZeroToOne(Src0, Src1)) {
10307     // const_a, const_b, x -> clamp is safe in all cases including signaling
10308     // nans.
10309     // FIXME: Should this be allowing -0.0?
10310     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10311   }
10312 
10313   const MachineFunction &MF = DAG.getMachineFunction();
10314   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10315 
10316   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10317   // handling no dx10-clamp?
10318   if (Info->getMode().DX10Clamp) {
10319     // If NaNs is clamped to 0, we are free to reorder the inputs.
10320 
10321     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10322       std::swap(Src0, Src1);
10323 
10324     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10325       std::swap(Src1, Src2);
10326 
10327     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10328       std::swap(Src0, Src1);
10329 
10330     if (isClampZeroToOne(Src1, Src2))
10331       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10332   }
10333 
10334   return SDValue();
10335 }
10336 
10337 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10338                                                  DAGCombinerInfo &DCI) const {
10339   SDValue Src0 = N->getOperand(0);
10340   SDValue Src1 = N->getOperand(1);
10341   if (Src0.isUndef() && Src1.isUndef())
10342     return DCI.DAG.getUNDEF(N->getValueType(0));
10343   return SDValue();
10344 }
10345 
10346 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10347 // expanded into a set of cmp/select instructions.
10348 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10349                                                 unsigned NumElem,
10350                                                 bool IsDivergentIdx) {
10351   if (UseDivergentRegisterIndexing)
10352     return false;
10353 
10354   unsigned VecSize = EltSize * NumElem;
10355 
10356   // Sub-dword vectors of size 2 dword or less have better implementation.
10357   if (VecSize <= 64 && EltSize < 32)
10358     return false;
10359 
10360   // Always expand the rest of sub-dword instructions, otherwise it will be
10361   // lowered via memory.
10362   if (EltSize < 32)
10363     return true;
10364 
10365   // Always do this if var-idx is divergent, otherwise it will become a loop.
10366   if (IsDivergentIdx)
10367     return true;
10368 
10369   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10370   unsigned NumInsts = NumElem /* Number of compares */ +
10371                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10372   return NumInsts <= 16;
10373 }
10374 
10375 static bool shouldExpandVectorDynExt(SDNode *N) {
10376   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10377   if (isa<ConstantSDNode>(Idx))
10378     return false;
10379 
10380   SDValue Vec = N->getOperand(0);
10381   EVT VecVT = Vec.getValueType();
10382   EVT EltVT = VecVT.getVectorElementType();
10383   unsigned EltSize = EltVT.getSizeInBits();
10384   unsigned NumElem = VecVT.getVectorNumElements();
10385 
10386   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10387                                                     Idx->isDivergent());
10388 }
10389 
10390 SDValue SITargetLowering::performExtractVectorEltCombine(
10391   SDNode *N, DAGCombinerInfo &DCI) const {
10392   SDValue Vec = N->getOperand(0);
10393   SelectionDAG &DAG = DCI.DAG;
10394 
10395   EVT VecVT = Vec.getValueType();
10396   EVT EltVT = VecVT.getVectorElementType();
10397 
10398   if ((Vec.getOpcode() == ISD::FNEG ||
10399        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10400     SDLoc SL(N);
10401     EVT EltVT = N->getValueType(0);
10402     SDValue Idx = N->getOperand(1);
10403     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10404                               Vec.getOperand(0), Idx);
10405     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10406   }
10407 
10408   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10409   //    =>
10410   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10411   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10412   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10413   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10414     SDLoc SL(N);
10415     EVT EltVT = N->getValueType(0);
10416     SDValue Idx = N->getOperand(1);
10417     unsigned Opc = Vec.getOpcode();
10418 
10419     switch(Opc) {
10420     default:
10421       break;
10422       // TODO: Support other binary operations.
10423     case ISD::FADD:
10424     case ISD::FSUB:
10425     case ISD::FMUL:
10426     case ISD::ADD:
10427     case ISD::UMIN:
10428     case ISD::UMAX:
10429     case ISD::SMIN:
10430     case ISD::SMAX:
10431     case ISD::FMAXNUM:
10432     case ISD::FMINNUM:
10433     case ISD::FMAXNUM_IEEE:
10434     case ISD::FMINNUM_IEEE: {
10435       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10436                                  Vec.getOperand(0), Idx);
10437       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10438                                  Vec.getOperand(1), Idx);
10439 
10440       DCI.AddToWorklist(Elt0.getNode());
10441       DCI.AddToWorklist(Elt1.getNode());
10442       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10443     }
10444     }
10445   }
10446 
10447   unsigned VecSize = VecVT.getSizeInBits();
10448   unsigned EltSize = EltVT.getSizeInBits();
10449 
10450   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10451   if (::shouldExpandVectorDynExt(N)) {
10452     SDLoc SL(N);
10453     SDValue Idx = N->getOperand(1);
10454     SDValue V;
10455     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10456       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10457       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10458       if (I == 0)
10459         V = Elt;
10460       else
10461         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10462     }
10463     return V;
10464   }
10465 
10466   if (!DCI.isBeforeLegalize())
10467     return SDValue();
10468 
10469   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10470   // elements. This exposes more load reduction opportunities by replacing
10471   // multiple small extract_vector_elements with a single 32-bit extract.
10472   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10473   if (isa<MemSDNode>(Vec) &&
10474       EltSize <= 16 &&
10475       EltVT.isByteSized() &&
10476       VecSize > 32 &&
10477       VecSize % 32 == 0 &&
10478       Idx) {
10479     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10480 
10481     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10482     unsigned EltIdx = BitIndex / 32;
10483     unsigned LeftoverBitIdx = BitIndex % 32;
10484     SDLoc SL(N);
10485 
10486     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10487     DCI.AddToWorklist(Cast.getNode());
10488 
10489     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10490                               DAG.getConstant(EltIdx, SL, MVT::i32));
10491     DCI.AddToWorklist(Elt.getNode());
10492     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10493                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10494     DCI.AddToWorklist(Srl.getNode());
10495 
10496     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10497     DCI.AddToWorklist(Trunc.getNode());
10498     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10499   }
10500 
10501   return SDValue();
10502 }
10503 
10504 SDValue
10505 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10506                                                 DAGCombinerInfo &DCI) const {
10507   SDValue Vec = N->getOperand(0);
10508   SDValue Idx = N->getOperand(2);
10509   EVT VecVT = Vec.getValueType();
10510   EVT EltVT = VecVT.getVectorElementType();
10511 
10512   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10513   // => BUILD_VECTOR n x select (e, const-idx)
10514   if (!::shouldExpandVectorDynExt(N))
10515     return SDValue();
10516 
10517   SelectionDAG &DAG = DCI.DAG;
10518   SDLoc SL(N);
10519   SDValue Ins = N->getOperand(1);
10520   EVT IdxVT = Idx.getValueType();
10521 
10522   SmallVector<SDValue, 16> Ops;
10523   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10524     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10525     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10526     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10527     Ops.push_back(V);
10528   }
10529 
10530   return DAG.getBuildVector(VecVT, SL, Ops);
10531 }
10532 
10533 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10534                                           const SDNode *N0,
10535                                           const SDNode *N1) const {
10536   EVT VT = N0->getValueType(0);
10537 
10538   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10539   // support denormals ever.
10540   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10541        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10542         getSubtarget()->hasMadF16())) &&
10543        isOperationLegal(ISD::FMAD, VT))
10544     return ISD::FMAD;
10545 
10546   const TargetOptions &Options = DAG.getTarget().Options;
10547   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10548        (N0->getFlags().hasAllowContract() &&
10549         N1->getFlags().hasAllowContract())) &&
10550       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10551     return ISD::FMA;
10552   }
10553 
10554   return 0;
10555 }
10556 
10557 // For a reassociatable opcode perform:
10558 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10559 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10560                                                SelectionDAG &DAG) const {
10561   EVT VT = N->getValueType(0);
10562   if (VT != MVT::i32 && VT != MVT::i64)
10563     return SDValue();
10564 
10565   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10566     return SDValue();
10567 
10568   unsigned Opc = N->getOpcode();
10569   SDValue Op0 = N->getOperand(0);
10570   SDValue Op1 = N->getOperand(1);
10571 
10572   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10573     return SDValue();
10574 
10575   if (Op0->isDivergent())
10576     std::swap(Op0, Op1);
10577 
10578   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10579     return SDValue();
10580 
10581   SDValue Op2 = Op1.getOperand(1);
10582   Op1 = Op1.getOperand(0);
10583   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10584     return SDValue();
10585 
10586   if (Op1->isDivergent())
10587     std::swap(Op1, Op2);
10588 
10589   SDLoc SL(N);
10590   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10591   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10592 }
10593 
10594 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10595                            EVT VT,
10596                            SDValue N0, SDValue N1, SDValue N2,
10597                            bool Signed) {
10598   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10599   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10600   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10601   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10602 }
10603 
10604 SDValue SITargetLowering::performAddCombine(SDNode *N,
10605                                             DAGCombinerInfo &DCI) const {
10606   SelectionDAG &DAG = DCI.DAG;
10607   EVT VT = N->getValueType(0);
10608   SDLoc SL(N);
10609   SDValue LHS = N->getOperand(0);
10610   SDValue RHS = N->getOperand(1);
10611 
10612   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10613       && Subtarget->hasMad64_32() &&
10614       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10615       VT.getScalarSizeInBits() <= 64) {
10616     if (LHS.getOpcode() != ISD::MUL)
10617       std::swap(LHS, RHS);
10618 
10619     SDValue MulLHS = LHS.getOperand(0);
10620     SDValue MulRHS = LHS.getOperand(1);
10621     SDValue AddRHS = RHS;
10622 
10623     // TODO: Maybe restrict if SGPR inputs.
10624     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10625         numBitsUnsigned(MulRHS, DAG) <= 32) {
10626       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10627       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10628       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10629       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10630     }
10631 
10632     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10633       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10634       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10635       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10636       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10637     }
10638 
10639     return SDValue();
10640   }
10641 
10642   if (SDValue V = reassociateScalarOps(N, DAG)) {
10643     return V;
10644   }
10645 
10646   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10647     return SDValue();
10648 
10649   // add x, zext (setcc) => addcarry x, 0, setcc
10650   // add x, sext (setcc) => subcarry x, 0, setcc
10651   unsigned Opc = LHS.getOpcode();
10652   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10653       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10654     std::swap(RHS, LHS);
10655 
10656   Opc = RHS.getOpcode();
10657   switch (Opc) {
10658   default: break;
10659   case ISD::ZERO_EXTEND:
10660   case ISD::SIGN_EXTEND:
10661   case ISD::ANY_EXTEND: {
10662     auto Cond = RHS.getOperand(0);
10663     // If this won't be a real VOPC output, we would still need to insert an
10664     // extra instruction anyway.
10665     if (!isBoolSGPR(Cond))
10666       break;
10667     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10668     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10669     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10670     return DAG.getNode(Opc, SL, VTList, Args);
10671   }
10672   case ISD::ADDCARRY: {
10673     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10674     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10675     if (!C || C->getZExtValue() != 0) break;
10676     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10677     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10678   }
10679   }
10680   return SDValue();
10681 }
10682 
10683 SDValue SITargetLowering::performSubCombine(SDNode *N,
10684                                             DAGCombinerInfo &DCI) const {
10685   SelectionDAG &DAG = DCI.DAG;
10686   EVT VT = N->getValueType(0);
10687 
10688   if (VT != MVT::i32)
10689     return SDValue();
10690 
10691   SDLoc SL(N);
10692   SDValue LHS = N->getOperand(0);
10693   SDValue RHS = N->getOperand(1);
10694 
10695   // sub x, zext (setcc) => subcarry x, 0, setcc
10696   // sub x, sext (setcc) => addcarry x, 0, setcc
10697   unsigned Opc = RHS.getOpcode();
10698   switch (Opc) {
10699   default: break;
10700   case ISD::ZERO_EXTEND:
10701   case ISD::SIGN_EXTEND:
10702   case ISD::ANY_EXTEND: {
10703     auto Cond = RHS.getOperand(0);
10704     // If this won't be a real VOPC output, we would still need to insert an
10705     // extra instruction anyway.
10706     if (!isBoolSGPR(Cond))
10707       break;
10708     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10709     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10710     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10711     return DAG.getNode(Opc, SL, VTList, Args);
10712   }
10713   }
10714 
10715   if (LHS.getOpcode() == ISD::SUBCARRY) {
10716     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10717     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10718     if (!C || !C->isZero())
10719       return SDValue();
10720     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10721     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10722   }
10723   return SDValue();
10724 }
10725 
10726 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10727   DAGCombinerInfo &DCI) const {
10728 
10729   if (N->getValueType(0) != MVT::i32)
10730     return SDValue();
10731 
10732   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10733   if (!C || C->getZExtValue() != 0)
10734     return SDValue();
10735 
10736   SelectionDAG &DAG = DCI.DAG;
10737   SDValue LHS = N->getOperand(0);
10738 
10739   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10740   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10741   unsigned LHSOpc = LHS.getOpcode();
10742   unsigned Opc = N->getOpcode();
10743   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10744       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10745     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10746     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10747   }
10748   return SDValue();
10749 }
10750 
10751 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10752                                              DAGCombinerInfo &DCI) const {
10753   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10754     return SDValue();
10755 
10756   SelectionDAG &DAG = DCI.DAG;
10757   EVT VT = N->getValueType(0);
10758 
10759   SDLoc SL(N);
10760   SDValue LHS = N->getOperand(0);
10761   SDValue RHS = N->getOperand(1);
10762 
10763   // These should really be instruction patterns, but writing patterns with
10764   // source modiifiers is a pain.
10765 
10766   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10767   if (LHS.getOpcode() == ISD::FADD) {
10768     SDValue A = LHS.getOperand(0);
10769     if (A == LHS.getOperand(1)) {
10770       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10771       if (FusedOp != 0) {
10772         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10773         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10774       }
10775     }
10776   }
10777 
10778   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10779   if (RHS.getOpcode() == ISD::FADD) {
10780     SDValue A = RHS.getOperand(0);
10781     if (A == RHS.getOperand(1)) {
10782       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10783       if (FusedOp != 0) {
10784         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10785         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10786       }
10787     }
10788   }
10789 
10790   return SDValue();
10791 }
10792 
10793 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10794                                              DAGCombinerInfo &DCI) const {
10795   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10796     return SDValue();
10797 
10798   SelectionDAG &DAG = DCI.DAG;
10799   SDLoc SL(N);
10800   EVT VT = N->getValueType(0);
10801   assert(!VT.isVector());
10802 
10803   // Try to get the fneg to fold into the source modifier. This undoes generic
10804   // DAG combines and folds them into the mad.
10805   //
10806   // Only do this if we are not trying to support denormals. v_mad_f32 does
10807   // not support denormals ever.
10808   SDValue LHS = N->getOperand(0);
10809   SDValue RHS = N->getOperand(1);
10810   if (LHS.getOpcode() == ISD::FADD) {
10811     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10812     SDValue A = LHS.getOperand(0);
10813     if (A == LHS.getOperand(1)) {
10814       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10815       if (FusedOp != 0){
10816         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10817         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10818 
10819         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10820       }
10821     }
10822   }
10823 
10824   if (RHS.getOpcode() == ISD::FADD) {
10825     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10826 
10827     SDValue A = RHS.getOperand(0);
10828     if (A == RHS.getOperand(1)) {
10829       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10830       if (FusedOp != 0){
10831         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10832         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10833       }
10834     }
10835   }
10836 
10837   return SDValue();
10838 }
10839 
10840 SDValue SITargetLowering::performFMACombine(SDNode *N,
10841                                             DAGCombinerInfo &DCI) const {
10842   SelectionDAG &DAG = DCI.DAG;
10843   EVT VT = N->getValueType(0);
10844   SDLoc SL(N);
10845 
10846   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10847     return SDValue();
10848 
10849   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10850   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10851   SDValue Op1 = N->getOperand(0);
10852   SDValue Op2 = N->getOperand(1);
10853   SDValue FMA = N->getOperand(2);
10854 
10855   if (FMA.getOpcode() != ISD::FMA ||
10856       Op1.getOpcode() != ISD::FP_EXTEND ||
10857       Op2.getOpcode() != ISD::FP_EXTEND)
10858     return SDValue();
10859 
10860   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10861   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10862   // is sufficient to allow generaing fdot2.
10863   const TargetOptions &Options = DAG.getTarget().Options;
10864   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10865       (N->getFlags().hasAllowContract() &&
10866        FMA->getFlags().hasAllowContract())) {
10867     Op1 = Op1.getOperand(0);
10868     Op2 = Op2.getOperand(0);
10869     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10870         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10871       return SDValue();
10872 
10873     SDValue Vec1 = Op1.getOperand(0);
10874     SDValue Idx1 = Op1.getOperand(1);
10875     SDValue Vec2 = Op2.getOperand(0);
10876 
10877     SDValue FMAOp1 = FMA.getOperand(0);
10878     SDValue FMAOp2 = FMA.getOperand(1);
10879     SDValue FMAAcc = FMA.getOperand(2);
10880 
10881     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10882         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10883       return SDValue();
10884 
10885     FMAOp1 = FMAOp1.getOperand(0);
10886     FMAOp2 = FMAOp2.getOperand(0);
10887     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10888         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10889       return SDValue();
10890 
10891     SDValue Vec3 = FMAOp1.getOperand(0);
10892     SDValue Vec4 = FMAOp2.getOperand(0);
10893     SDValue Idx2 = FMAOp1.getOperand(1);
10894 
10895     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10896         // Idx1 and Idx2 cannot be the same.
10897         Idx1 == Idx2)
10898       return SDValue();
10899 
10900     if (Vec1 == Vec2 || Vec3 == Vec4)
10901       return SDValue();
10902 
10903     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10904       return SDValue();
10905 
10906     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10907         (Vec1 == Vec4 && Vec2 == Vec3)) {
10908       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10909                          DAG.getTargetConstant(0, SL, MVT::i1));
10910     }
10911   }
10912   return SDValue();
10913 }
10914 
10915 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10916                                               DAGCombinerInfo &DCI) const {
10917   SelectionDAG &DAG = DCI.DAG;
10918   SDLoc SL(N);
10919 
10920   SDValue LHS = N->getOperand(0);
10921   SDValue RHS = N->getOperand(1);
10922   EVT VT = LHS.getValueType();
10923   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10924 
10925   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10926   if (!CRHS) {
10927     CRHS = dyn_cast<ConstantSDNode>(LHS);
10928     if (CRHS) {
10929       std::swap(LHS, RHS);
10930       CC = getSetCCSwappedOperands(CC);
10931     }
10932   }
10933 
10934   if (CRHS) {
10935     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10936         isBoolSGPR(LHS.getOperand(0))) {
10937       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10938       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10939       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10940       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10941       if ((CRHS->isAllOnes() &&
10942            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10943           (CRHS->isZero() &&
10944            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10945         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10946                            DAG.getConstant(-1, SL, MVT::i1));
10947       if ((CRHS->isAllOnes() &&
10948            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10949           (CRHS->isZero() &&
10950            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10951         return LHS.getOperand(0);
10952     }
10953 
10954     const APInt &CRHSVal = CRHS->getAPIntValue();
10955     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10956         LHS.getOpcode() == ISD::SELECT &&
10957         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10958         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10959         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10960         isBoolSGPR(LHS.getOperand(0))) {
10961       // Given CT != FT:
10962       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10963       // setcc (select cc, CT, CF), CF, ne => cc
10964       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10965       // setcc (select cc, CT, CF), CT, eq => cc
10966       const APInt &CT = LHS.getConstantOperandAPInt(1);
10967       const APInt &CF = LHS.getConstantOperandAPInt(2);
10968 
10969       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10970           (CT == CRHSVal && CC == ISD::SETNE))
10971         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10972                            DAG.getConstant(-1, SL, MVT::i1));
10973       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10974           (CT == CRHSVal && CC == ISD::SETEQ))
10975         return LHS.getOperand(0);
10976     }
10977   }
10978 
10979   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10980                                            VT != MVT::f16))
10981     return SDValue();
10982 
10983   // Match isinf/isfinite pattern
10984   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10985   // (fcmp one (fabs x), inf) -> (fp_class x,
10986   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10987   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10988     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10989     if (!CRHS)
10990       return SDValue();
10991 
10992     const APFloat &APF = CRHS->getValueAPF();
10993     if (APF.isInfinity() && !APF.isNegative()) {
10994       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10995                                  SIInstrFlags::N_INFINITY;
10996       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10997                                     SIInstrFlags::P_ZERO |
10998                                     SIInstrFlags::N_NORMAL |
10999                                     SIInstrFlags::P_NORMAL |
11000                                     SIInstrFlags::N_SUBNORMAL |
11001                                     SIInstrFlags::P_SUBNORMAL;
11002       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11003       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11004                          DAG.getConstant(Mask, SL, MVT::i32));
11005     }
11006   }
11007 
11008   return SDValue();
11009 }
11010 
11011 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11012                                                      DAGCombinerInfo &DCI) const {
11013   SelectionDAG &DAG = DCI.DAG;
11014   SDLoc SL(N);
11015   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11016 
11017   SDValue Src = N->getOperand(0);
11018   SDValue Shift = N->getOperand(0);
11019 
11020   // TODO: Extend type shouldn't matter (assuming legal types).
11021   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11022     Shift = Shift.getOperand(0);
11023 
11024   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11025     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11026     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11027     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11028     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11029     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11030     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11031       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11032                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11033 
11034       unsigned ShiftOffset = 8 * Offset;
11035       if (Shift.getOpcode() == ISD::SHL)
11036         ShiftOffset -= C->getZExtValue();
11037       else
11038         ShiftOffset += C->getZExtValue();
11039 
11040       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11041         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11042                            MVT::f32, Shifted);
11043       }
11044     }
11045   }
11046 
11047   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11048   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11049   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11050     // We simplified Src. If this node is not dead, visit it again so it is
11051     // folded properly.
11052     if (N->getOpcode() != ISD::DELETED_NODE)
11053       DCI.AddToWorklist(N);
11054     return SDValue(N, 0);
11055   }
11056 
11057   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11058   if (SDValue DemandedSrc =
11059           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11060     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11061 
11062   return SDValue();
11063 }
11064 
11065 SDValue SITargetLowering::performClampCombine(SDNode *N,
11066                                               DAGCombinerInfo &DCI) const {
11067   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11068   if (!CSrc)
11069     return SDValue();
11070 
11071   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11072   const APFloat &F = CSrc->getValueAPF();
11073   APFloat Zero = APFloat::getZero(F.getSemantics());
11074   if (F < Zero ||
11075       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11076     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11077   }
11078 
11079   APFloat One(F.getSemantics(), "1.0");
11080   if (F > One)
11081     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11082 
11083   return SDValue(CSrc, 0);
11084 }
11085 
11086 
11087 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11088                                             DAGCombinerInfo &DCI) const {
11089   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11090     return SDValue();
11091   switch (N->getOpcode()) {
11092   case ISD::ADD:
11093     return performAddCombine(N, DCI);
11094   case ISD::SUB:
11095     return performSubCombine(N, DCI);
11096   case ISD::ADDCARRY:
11097   case ISD::SUBCARRY:
11098     return performAddCarrySubCarryCombine(N, DCI);
11099   case ISD::FADD:
11100     return performFAddCombine(N, DCI);
11101   case ISD::FSUB:
11102     return performFSubCombine(N, DCI);
11103   case ISD::SETCC:
11104     return performSetCCCombine(N, DCI);
11105   case ISD::FMAXNUM:
11106   case ISD::FMINNUM:
11107   case ISD::FMAXNUM_IEEE:
11108   case ISD::FMINNUM_IEEE:
11109   case ISD::SMAX:
11110   case ISD::SMIN:
11111   case ISD::UMAX:
11112   case ISD::UMIN:
11113   case AMDGPUISD::FMIN_LEGACY:
11114   case AMDGPUISD::FMAX_LEGACY:
11115     return performMinMaxCombine(N, DCI);
11116   case ISD::FMA:
11117     return performFMACombine(N, DCI);
11118   case ISD::AND:
11119     return performAndCombine(N, DCI);
11120   case ISD::OR:
11121     return performOrCombine(N, DCI);
11122   case ISD::XOR:
11123     return performXorCombine(N, DCI);
11124   case ISD::ZERO_EXTEND:
11125     return performZeroExtendCombine(N, DCI);
11126   case ISD::SIGN_EXTEND_INREG:
11127     return performSignExtendInRegCombine(N , DCI);
11128   case AMDGPUISD::FP_CLASS:
11129     return performClassCombine(N, DCI);
11130   case ISD::FCANONICALIZE:
11131     return performFCanonicalizeCombine(N, DCI);
11132   case AMDGPUISD::RCP:
11133     return performRcpCombine(N, DCI);
11134   case AMDGPUISD::FRACT:
11135   case AMDGPUISD::RSQ:
11136   case AMDGPUISD::RCP_LEGACY:
11137   case AMDGPUISD::RCP_IFLAG:
11138   case AMDGPUISD::RSQ_CLAMP:
11139   case AMDGPUISD::LDEXP: {
11140     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11141     SDValue Src = N->getOperand(0);
11142     if (Src.isUndef())
11143       return Src;
11144     break;
11145   }
11146   case ISD::SINT_TO_FP:
11147   case ISD::UINT_TO_FP:
11148     return performUCharToFloatCombine(N, DCI);
11149   case AMDGPUISD::CVT_F32_UBYTE0:
11150   case AMDGPUISD::CVT_F32_UBYTE1:
11151   case AMDGPUISD::CVT_F32_UBYTE2:
11152   case AMDGPUISD::CVT_F32_UBYTE3:
11153     return performCvtF32UByteNCombine(N, DCI);
11154   case AMDGPUISD::FMED3:
11155     return performFMed3Combine(N, DCI);
11156   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11157     return performCvtPkRTZCombine(N, DCI);
11158   case AMDGPUISD::CLAMP:
11159     return performClampCombine(N, DCI);
11160   case ISD::SCALAR_TO_VECTOR: {
11161     SelectionDAG &DAG = DCI.DAG;
11162     EVT VT = N->getValueType(0);
11163 
11164     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11165     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11166       SDLoc SL(N);
11167       SDValue Src = N->getOperand(0);
11168       EVT EltVT = Src.getValueType();
11169       if (EltVT == MVT::f16)
11170         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11171 
11172       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11173       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11174     }
11175 
11176     break;
11177   }
11178   case ISD::EXTRACT_VECTOR_ELT:
11179     return performExtractVectorEltCombine(N, DCI);
11180   case ISD::INSERT_VECTOR_ELT:
11181     return performInsertVectorEltCombine(N, DCI);
11182   case ISD::LOAD: {
11183     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11184       return Widended;
11185     LLVM_FALLTHROUGH;
11186   }
11187   default: {
11188     if (!DCI.isBeforeLegalize()) {
11189       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11190         return performMemSDNodeCombine(MemNode, DCI);
11191     }
11192 
11193     break;
11194   }
11195   }
11196 
11197   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11198 }
11199 
11200 /// Helper function for adjustWritemask
11201 static unsigned SubIdx2Lane(unsigned Idx) {
11202   switch (Idx) {
11203   default: return ~0u;
11204   case AMDGPU::sub0: return 0;
11205   case AMDGPU::sub1: return 1;
11206   case AMDGPU::sub2: return 2;
11207   case AMDGPU::sub3: return 3;
11208   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11209   }
11210 }
11211 
11212 /// Adjust the writemask of MIMG instructions
11213 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11214                                           SelectionDAG &DAG) const {
11215   unsigned Opcode = Node->getMachineOpcode();
11216 
11217   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11218   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11219   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11220     return Node; // not implemented for D16
11221 
11222   SDNode *Users[5] = { nullptr };
11223   unsigned Lane = 0;
11224   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11225   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11226   unsigned NewDmask = 0;
11227   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11228   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11229   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11230                   Node->getConstantOperandVal(LWEIdx))
11231                      ? true
11232                      : false;
11233   unsigned TFCLane = 0;
11234   bool HasChain = Node->getNumValues() > 1;
11235 
11236   if (OldDmask == 0) {
11237     // These are folded out, but on the chance it happens don't assert.
11238     return Node;
11239   }
11240 
11241   unsigned OldBitsSet = countPopulation(OldDmask);
11242   // Work out which is the TFE/LWE lane if that is enabled.
11243   if (UsesTFC) {
11244     TFCLane = OldBitsSet;
11245   }
11246 
11247   // Try to figure out the used register components
11248   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11249        I != E; ++I) {
11250 
11251     // Don't look at users of the chain.
11252     if (I.getUse().getResNo() != 0)
11253       continue;
11254 
11255     // Abort if we can't understand the usage
11256     if (!I->isMachineOpcode() ||
11257         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11258       return Node;
11259 
11260     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11261     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11262     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11263     // set, etc.
11264     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11265     if (Lane == ~0u)
11266       return Node;
11267 
11268     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11269     if (UsesTFC && Lane == TFCLane) {
11270       Users[Lane] = *I;
11271     } else {
11272       // Set which texture component corresponds to the lane.
11273       unsigned Comp;
11274       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11275         Comp = countTrailingZeros(Dmask);
11276         Dmask &= ~(1 << Comp);
11277       }
11278 
11279       // Abort if we have more than one user per component.
11280       if (Users[Lane])
11281         return Node;
11282 
11283       Users[Lane] = *I;
11284       NewDmask |= 1 << Comp;
11285     }
11286   }
11287 
11288   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11289   bool NoChannels = !NewDmask;
11290   if (NoChannels) {
11291     if (!UsesTFC) {
11292       // No uses of the result and not using TFC. Then do nothing.
11293       return Node;
11294     }
11295     // If the original dmask has one channel - then nothing to do
11296     if (OldBitsSet == 1)
11297       return Node;
11298     // Use an arbitrary dmask - required for the instruction to work
11299     NewDmask = 1;
11300   }
11301   // Abort if there's no change
11302   if (NewDmask == OldDmask)
11303     return Node;
11304 
11305   unsigned BitsSet = countPopulation(NewDmask);
11306 
11307   // Check for TFE or LWE - increase the number of channels by one to account
11308   // for the extra return value
11309   // This will need adjustment for D16 if this is also included in
11310   // adjustWriteMask (this function) but at present D16 are excluded.
11311   unsigned NewChannels = BitsSet + UsesTFC;
11312 
11313   int NewOpcode =
11314       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11315   assert(NewOpcode != -1 &&
11316          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11317          "failed to find equivalent MIMG op");
11318 
11319   // Adjust the writemask in the node
11320   SmallVector<SDValue, 12> Ops;
11321   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11322   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11323   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11324 
11325   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11326 
11327   MVT ResultVT = NewChannels == 1 ?
11328     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11329                            NewChannels == 5 ? 8 : NewChannels);
11330   SDVTList NewVTList = HasChain ?
11331     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11332 
11333 
11334   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11335                                               NewVTList, Ops);
11336 
11337   if (HasChain) {
11338     // Update chain.
11339     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11340     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11341   }
11342 
11343   if (NewChannels == 1) {
11344     assert(Node->hasNUsesOfValue(1, 0));
11345     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11346                                       SDLoc(Node), Users[Lane]->getValueType(0),
11347                                       SDValue(NewNode, 0));
11348     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11349     return nullptr;
11350   }
11351 
11352   // Update the users of the node with the new indices
11353   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11354     SDNode *User = Users[i];
11355     if (!User) {
11356       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11357       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11358       if (i || !NoChannels)
11359         continue;
11360     } else {
11361       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11362       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11363     }
11364 
11365     switch (Idx) {
11366     default: break;
11367     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11368     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11369     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11370     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11371     }
11372   }
11373 
11374   DAG.RemoveDeadNode(Node);
11375   return nullptr;
11376 }
11377 
11378 static bool isFrameIndexOp(SDValue Op) {
11379   if (Op.getOpcode() == ISD::AssertZext)
11380     Op = Op.getOperand(0);
11381 
11382   return isa<FrameIndexSDNode>(Op);
11383 }
11384 
11385 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11386 /// with frame index operands.
11387 /// LLVM assumes that inputs are to these instructions are registers.
11388 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11389                                                         SelectionDAG &DAG) const {
11390   if (Node->getOpcode() == ISD::CopyToReg) {
11391     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11392     SDValue SrcVal = Node->getOperand(2);
11393 
11394     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11395     // to try understanding copies to physical registers.
11396     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11397       SDLoc SL(Node);
11398       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11399       SDValue VReg = DAG.getRegister(
11400         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11401 
11402       SDNode *Glued = Node->getGluedNode();
11403       SDValue ToVReg
11404         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11405                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11406       SDValue ToResultReg
11407         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11408                            VReg, ToVReg.getValue(1));
11409       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11410       DAG.RemoveDeadNode(Node);
11411       return ToResultReg.getNode();
11412     }
11413   }
11414 
11415   SmallVector<SDValue, 8> Ops;
11416   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11417     if (!isFrameIndexOp(Node->getOperand(i))) {
11418       Ops.push_back(Node->getOperand(i));
11419       continue;
11420     }
11421 
11422     SDLoc DL(Node);
11423     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11424                                      Node->getOperand(i).getValueType(),
11425                                      Node->getOperand(i)), 0));
11426   }
11427 
11428   return DAG.UpdateNodeOperands(Node, Ops);
11429 }
11430 
11431 /// Fold the instructions after selecting them.
11432 /// Returns null if users were already updated.
11433 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11434                                           SelectionDAG &DAG) const {
11435   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11436   unsigned Opcode = Node->getMachineOpcode();
11437 
11438   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11439       !TII->isGather4(Opcode) &&
11440       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11441     return adjustWritemask(Node, DAG);
11442   }
11443 
11444   if (Opcode == AMDGPU::INSERT_SUBREG ||
11445       Opcode == AMDGPU::REG_SEQUENCE) {
11446     legalizeTargetIndependentNode(Node, DAG);
11447     return Node;
11448   }
11449 
11450   switch (Opcode) {
11451   case AMDGPU::V_DIV_SCALE_F32_e64:
11452   case AMDGPU::V_DIV_SCALE_F64_e64: {
11453     // Satisfy the operand register constraint when one of the inputs is
11454     // undefined. Ordinarily each undef value will have its own implicit_def of
11455     // a vreg, so force these to use a single register.
11456     SDValue Src0 = Node->getOperand(1);
11457     SDValue Src1 = Node->getOperand(3);
11458     SDValue Src2 = Node->getOperand(5);
11459 
11460     if ((Src0.isMachineOpcode() &&
11461          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11462         (Src0 == Src1 || Src0 == Src2))
11463       break;
11464 
11465     MVT VT = Src0.getValueType().getSimpleVT();
11466     const TargetRegisterClass *RC =
11467         getRegClassFor(VT, Src0.getNode()->isDivergent());
11468 
11469     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11470     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11471 
11472     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11473                                       UndefReg, Src0, SDValue());
11474 
11475     // src0 must be the same register as src1 or src2, even if the value is
11476     // undefined, so make sure we don't violate this constraint.
11477     if (Src0.isMachineOpcode() &&
11478         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11479       if (Src1.isMachineOpcode() &&
11480           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11481         Src0 = Src1;
11482       else if (Src2.isMachineOpcode() &&
11483                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11484         Src0 = Src2;
11485       else {
11486         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11487         Src0 = UndefReg;
11488         Src1 = UndefReg;
11489       }
11490     } else
11491       break;
11492 
11493     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11494     Ops[1] = Src0;
11495     Ops[3] = Src1;
11496     Ops[5] = Src2;
11497     Ops.push_back(ImpDef.getValue(1));
11498     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11499   }
11500   default:
11501     break;
11502   }
11503 
11504   return Node;
11505 }
11506 
11507 // Any MIMG instructions that use tfe or lwe require an initialization of the
11508 // result register that will be written in the case of a memory access failure.
11509 // The required code is also added to tie this init code to the result of the
11510 // img instruction.
11511 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11512   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11513   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11514   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11515   MachineBasicBlock &MBB = *MI.getParent();
11516 
11517   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11518   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11519   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11520 
11521   if (!TFE && !LWE) // intersect_ray
11522     return;
11523 
11524   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11525   unsigned LWEVal = LWE->getImm();
11526   unsigned D16Val = D16 ? D16->getImm() : 0;
11527 
11528   if (!TFEVal && !LWEVal)
11529     return;
11530 
11531   // At least one of TFE or LWE are non-zero
11532   // We have to insert a suitable initialization of the result value and
11533   // tie this to the dest of the image instruction.
11534 
11535   const DebugLoc &DL = MI.getDebugLoc();
11536 
11537   int DstIdx =
11538       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11539 
11540   // Calculate which dword we have to initialize to 0.
11541   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11542 
11543   // check that dmask operand is found.
11544   assert(MO_Dmask && "Expected dmask operand in instruction");
11545 
11546   unsigned dmask = MO_Dmask->getImm();
11547   // Determine the number of active lanes taking into account the
11548   // Gather4 special case
11549   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11550 
11551   bool Packed = !Subtarget->hasUnpackedD16VMem();
11552 
11553   unsigned InitIdx =
11554       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11555 
11556   // Abandon attempt if the dst size isn't large enough
11557   // - this is in fact an error but this is picked up elsewhere and
11558   // reported correctly.
11559   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11560   if (DstSize < InitIdx)
11561     return;
11562 
11563   // Create a register for the intialization value.
11564   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11565   unsigned NewDst = 0; // Final initialized value will be in here
11566 
11567   // If PRTStrictNull feature is enabled (the default) then initialize
11568   // all the result registers to 0, otherwise just the error indication
11569   // register (VGPRn+1)
11570   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11571   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11572 
11573   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11574   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11575     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11576     // Initialize dword
11577     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11578     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11579       .addImm(0);
11580     // Insert into the super-reg
11581     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11582       .addReg(PrevDst)
11583       .addReg(SubReg)
11584       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11585 
11586     PrevDst = NewDst;
11587   }
11588 
11589   // Add as an implicit operand
11590   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11591 
11592   // Tie the just added implicit operand to the dst
11593   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11594 }
11595 
11596 /// Assign the register class depending on the number of
11597 /// bits set in the writemask
11598 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11599                                                      SDNode *Node) const {
11600   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11601 
11602   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11603 
11604   if (TII->isVOP3(MI.getOpcode())) {
11605     // Make sure constant bus requirements are respected.
11606     TII->legalizeOperandsVOP3(MRI, MI);
11607 
11608     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11609     // This saves a chain-copy of registers and better ballance register
11610     // use between vgpr and agpr as agpr tuples tend to be big.
11611     if (MI.getDesc().OpInfo) {
11612       unsigned Opc = MI.getOpcode();
11613       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11614       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11615                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11616         if (I == -1)
11617           break;
11618         MachineOperand &Op = MI.getOperand(I);
11619         if (!Op.isReg() || !Op.getReg().isVirtual())
11620           continue;
11621         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11622         if (!TRI->hasAGPRs(RC))
11623           continue;
11624         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11625         if (!Src || !Src->isCopy() ||
11626             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11627           continue;
11628         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11629         // All uses of agpr64 and agpr32 can also accept vgpr except for
11630         // v_accvgpr_read, but we do not produce agpr reads during selection,
11631         // so no use checks are needed.
11632         MRI.setRegClass(Op.getReg(), NewRC);
11633       }
11634     }
11635 
11636     return;
11637   }
11638 
11639   // Replace unused atomics with the no return version.
11640   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11641   if (NoRetAtomicOp != -1) {
11642     if (!Node->hasAnyUseOfValue(0)) {
11643       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11644                                                AMDGPU::OpName::cpol);
11645       if (CPolIdx != -1) {
11646         MachineOperand &CPol = MI.getOperand(CPolIdx);
11647         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11648       }
11649       MI.RemoveOperand(0);
11650       MI.setDesc(TII->get(NoRetAtomicOp));
11651       return;
11652     }
11653 
11654     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11655     // instruction, because the return type of these instructions is a vec2 of
11656     // the memory type, so it can be tied to the input operand.
11657     // This means these instructions always have a use, so we need to add a
11658     // special case to check if the atomic has only one extract_subreg use,
11659     // which itself has no uses.
11660     if ((Node->hasNUsesOfValue(1, 0) &&
11661          Node->use_begin()->isMachineOpcode() &&
11662          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11663          !Node->use_begin()->hasAnyUseOfValue(0))) {
11664       Register Def = MI.getOperand(0).getReg();
11665 
11666       // Change this into a noret atomic.
11667       MI.setDesc(TII->get(NoRetAtomicOp));
11668       MI.RemoveOperand(0);
11669 
11670       // If we only remove the def operand from the atomic instruction, the
11671       // extract_subreg will be left with a use of a vreg without a def.
11672       // So we need to insert an implicit_def to avoid machine verifier
11673       // errors.
11674       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11675               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11676     }
11677     return;
11678   }
11679 
11680   if (TII->isMIMG(MI) && !MI.mayStore())
11681     AddIMGInit(MI);
11682 }
11683 
11684 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11685                               uint64_t Val) {
11686   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11687   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11688 }
11689 
11690 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11691                                                 const SDLoc &DL,
11692                                                 SDValue Ptr) const {
11693   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11694 
11695   // Build the half of the subregister with the constants before building the
11696   // full 128-bit register. If we are building multiple resource descriptors,
11697   // this will allow CSEing of the 2-component register.
11698   const SDValue Ops0[] = {
11699     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11700     buildSMovImm32(DAG, DL, 0),
11701     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11702     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11703     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11704   };
11705 
11706   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11707                                                 MVT::v2i32, Ops0), 0);
11708 
11709   // Combine the constants and the pointer.
11710   const SDValue Ops1[] = {
11711     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11712     Ptr,
11713     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11714     SubRegHi,
11715     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11716   };
11717 
11718   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11719 }
11720 
11721 /// Return a resource descriptor with the 'Add TID' bit enabled
11722 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11723 ///        of the resource descriptor) to create an offset, which is added to
11724 ///        the resource pointer.
11725 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11726                                            SDValue Ptr, uint32_t RsrcDword1,
11727                                            uint64_t RsrcDword2And3) const {
11728   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11729   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11730   if (RsrcDword1) {
11731     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11732                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11733                     0);
11734   }
11735 
11736   SDValue DataLo = buildSMovImm32(DAG, DL,
11737                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11738   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11739 
11740   const SDValue Ops[] = {
11741     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11742     PtrLo,
11743     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11744     PtrHi,
11745     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11746     DataLo,
11747     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11748     DataHi,
11749     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11750   };
11751 
11752   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11753 }
11754 
11755 //===----------------------------------------------------------------------===//
11756 //                         SI Inline Assembly Support
11757 //===----------------------------------------------------------------------===//
11758 
11759 std::pair<unsigned, const TargetRegisterClass *>
11760 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11761                                                StringRef Constraint,
11762                                                MVT VT) const {
11763   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11764 
11765   const TargetRegisterClass *RC = nullptr;
11766   if (Constraint.size() == 1) {
11767     const unsigned BitWidth = VT.getSizeInBits();
11768     switch (Constraint[0]) {
11769     default:
11770       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11771     case 's':
11772     case 'r':
11773       switch (BitWidth) {
11774       case 16:
11775         RC = &AMDGPU::SReg_32RegClass;
11776         break;
11777       case 64:
11778         RC = &AMDGPU::SGPR_64RegClass;
11779         break;
11780       default:
11781         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11782         if (!RC)
11783           return std::make_pair(0U, nullptr);
11784         break;
11785       }
11786       break;
11787     case 'v':
11788       switch (BitWidth) {
11789       case 16:
11790         RC = &AMDGPU::VGPR_32RegClass;
11791         break;
11792       default:
11793         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11794         if (!RC)
11795           return std::make_pair(0U, nullptr);
11796         break;
11797       }
11798       break;
11799     case 'a':
11800       if (!Subtarget->hasMAIInsts())
11801         break;
11802       switch (BitWidth) {
11803       case 16:
11804         RC = &AMDGPU::AGPR_32RegClass;
11805         break;
11806       default:
11807         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11808         if (!RC)
11809           return std::make_pair(0U, nullptr);
11810         break;
11811       }
11812       break;
11813     }
11814     // We actually support i128, i16 and f16 as inline parameters
11815     // even if they are not reported as legal
11816     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11817                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11818       return std::make_pair(0U, RC);
11819   }
11820 
11821   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11822     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11823     if (RegName.consume_front("v")) {
11824       RC = &AMDGPU::VGPR_32RegClass;
11825     } else if (RegName.consume_front("s")) {
11826       RC = &AMDGPU::SGPR_32RegClass;
11827     } else if (RegName.consume_front("a")) {
11828       RC = &AMDGPU::AGPR_32RegClass;
11829     }
11830 
11831     if (RC) {
11832       uint32_t Idx;
11833       if (RegName.consume_front("[")) {
11834         uint32_t End;
11835         bool Failed = RegName.consumeInteger(10, Idx);
11836         Failed |= !RegName.consume_front(":");
11837         Failed |= RegName.consumeInteger(10, End);
11838         Failed |= !RegName.consume_back("]");
11839         if (!Failed) {
11840           uint32_t Width = (End - Idx + 1) * 32;
11841           MCRegister Reg = RC->getRegister(Idx);
11842           if (SIRegisterInfo::isVGPRClass(RC))
11843             RC = TRI->getVGPRClassForBitWidth(Width);
11844           else if (SIRegisterInfo::isSGPRClass(RC))
11845             RC = TRI->getSGPRClassForBitWidth(Width);
11846           else if (SIRegisterInfo::isAGPRClass(RC))
11847             RC = TRI->getAGPRClassForBitWidth(Width);
11848           if (RC) {
11849             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11850             return std::make_pair(Reg, RC);
11851           }
11852         }
11853       } else {
11854         bool Failed = RegName.getAsInteger(10, Idx);
11855         if (!Failed && Idx < RC->getNumRegs())
11856           return std::make_pair(RC->getRegister(Idx), RC);
11857       }
11858     }
11859   }
11860 
11861   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11862   if (Ret.first)
11863     Ret.second = TRI->getPhysRegClass(Ret.first);
11864 
11865   return Ret;
11866 }
11867 
11868 static bool isImmConstraint(StringRef Constraint) {
11869   if (Constraint.size() == 1) {
11870     switch (Constraint[0]) {
11871     default: break;
11872     case 'I':
11873     case 'J':
11874     case 'A':
11875     case 'B':
11876     case 'C':
11877       return true;
11878     }
11879   } else if (Constraint == "DA" ||
11880              Constraint == "DB") {
11881     return true;
11882   }
11883   return false;
11884 }
11885 
11886 SITargetLowering::ConstraintType
11887 SITargetLowering::getConstraintType(StringRef Constraint) const {
11888   if (Constraint.size() == 1) {
11889     switch (Constraint[0]) {
11890     default: break;
11891     case 's':
11892     case 'v':
11893     case 'a':
11894       return C_RegisterClass;
11895     }
11896   }
11897   if (isImmConstraint(Constraint)) {
11898     return C_Other;
11899   }
11900   return TargetLowering::getConstraintType(Constraint);
11901 }
11902 
11903 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11904   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11905     Val = Val & maskTrailingOnes<uint64_t>(Size);
11906   }
11907   return Val;
11908 }
11909 
11910 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11911                                                     std::string &Constraint,
11912                                                     std::vector<SDValue> &Ops,
11913                                                     SelectionDAG &DAG) const {
11914   if (isImmConstraint(Constraint)) {
11915     uint64_t Val;
11916     if (getAsmOperandConstVal(Op, Val) &&
11917         checkAsmConstraintVal(Op, Constraint, Val)) {
11918       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11919       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11920     }
11921   } else {
11922     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11923   }
11924 }
11925 
11926 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11927   unsigned Size = Op.getScalarValueSizeInBits();
11928   if (Size > 64)
11929     return false;
11930 
11931   if (Size == 16 && !Subtarget->has16BitInsts())
11932     return false;
11933 
11934   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11935     Val = C->getSExtValue();
11936     return true;
11937   }
11938   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11939     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11940     return true;
11941   }
11942   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11943     if (Size != 16 || Op.getNumOperands() != 2)
11944       return false;
11945     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11946       return false;
11947     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11948       Val = C->getSExtValue();
11949       return true;
11950     }
11951     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11952       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11953       return true;
11954     }
11955   }
11956 
11957   return false;
11958 }
11959 
11960 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11961                                              const std::string &Constraint,
11962                                              uint64_t Val) const {
11963   if (Constraint.size() == 1) {
11964     switch (Constraint[0]) {
11965     case 'I':
11966       return AMDGPU::isInlinableIntLiteral(Val);
11967     case 'J':
11968       return isInt<16>(Val);
11969     case 'A':
11970       return checkAsmConstraintValA(Op, Val);
11971     case 'B':
11972       return isInt<32>(Val);
11973     case 'C':
11974       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11975              AMDGPU::isInlinableIntLiteral(Val);
11976     default:
11977       break;
11978     }
11979   } else if (Constraint.size() == 2) {
11980     if (Constraint == "DA") {
11981       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11982       int64_t LoBits = static_cast<int32_t>(Val);
11983       return checkAsmConstraintValA(Op, HiBits, 32) &&
11984              checkAsmConstraintValA(Op, LoBits, 32);
11985     }
11986     if (Constraint == "DB") {
11987       return true;
11988     }
11989   }
11990   llvm_unreachable("Invalid asm constraint");
11991 }
11992 
11993 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11994                                               uint64_t Val,
11995                                               unsigned MaxSize) const {
11996   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11997   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11998   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11999       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12000       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12001     return true;
12002   }
12003   return false;
12004 }
12005 
12006 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12007   switch (UnalignedClassID) {
12008   case AMDGPU::VReg_64RegClassID:
12009     return AMDGPU::VReg_64_Align2RegClassID;
12010   case AMDGPU::VReg_96RegClassID:
12011     return AMDGPU::VReg_96_Align2RegClassID;
12012   case AMDGPU::VReg_128RegClassID:
12013     return AMDGPU::VReg_128_Align2RegClassID;
12014   case AMDGPU::VReg_160RegClassID:
12015     return AMDGPU::VReg_160_Align2RegClassID;
12016   case AMDGPU::VReg_192RegClassID:
12017     return AMDGPU::VReg_192_Align2RegClassID;
12018   case AMDGPU::VReg_224RegClassID:
12019     return AMDGPU::VReg_224_Align2RegClassID;
12020   case AMDGPU::VReg_256RegClassID:
12021     return AMDGPU::VReg_256_Align2RegClassID;
12022   case AMDGPU::VReg_512RegClassID:
12023     return AMDGPU::VReg_512_Align2RegClassID;
12024   case AMDGPU::VReg_1024RegClassID:
12025     return AMDGPU::VReg_1024_Align2RegClassID;
12026   case AMDGPU::AReg_64RegClassID:
12027     return AMDGPU::AReg_64_Align2RegClassID;
12028   case AMDGPU::AReg_96RegClassID:
12029     return AMDGPU::AReg_96_Align2RegClassID;
12030   case AMDGPU::AReg_128RegClassID:
12031     return AMDGPU::AReg_128_Align2RegClassID;
12032   case AMDGPU::AReg_160RegClassID:
12033     return AMDGPU::AReg_160_Align2RegClassID;
12034   case AMDGPU::AReg_192RegClassID:
12035     return AMDGPU::AReg_192_Align2RegClassID;
12036   case AMDGPU::AReg_256RegClassID:
12037     return AMDGPU::AReg_256_Align2RegClassID;
12038   case AMDGPU::AReg_512RegClassID:
12039     return AMDGPU::AReg_512_Align2RegClassID;
12040   case AMDGPU::AReg_1024RegClassID:
12041     return AMDGPU::AReg_1024_Align2RegClassID;
12042   default:
12043     return -1;
12044   }
12045 }
12046 
12047 // Figure out which registers should be reserved for stack access. Only after
12048 // the function is legalized do we know all of the non-spill stack objects or if
12049 // calls are present.
12050 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12051   MachineRegisterInfo &MRI = MF.getRegInfo();
12052   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12053   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12054   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12055   const SIInstrInfo *TII = ST.getInstrInfo();
12056 
12057   if (Info->isEntryFunction()) {
12058     // Callable functions have fixed registers used for stack access.
12059     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12060   }
12061 
12062   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12063                              Info->getStackPtrOffsetReg()));
12064   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12065     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12066 
12067   // We need to worry about replacing the default register with itself in case
12068   // of MIR testcases missing the MFI.
12069   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12070     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12071 
12072   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12073     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12074 
12075   Info->limitOccupancy(MF);
12076 
12077   if (ST.isWave32() && !MF.empty()) {
12078     for (auto &MBB : MF) {
12079       for (auto &MI : MBB) {
12080         TII->fixImplicitOperands(MI);
12081       }
12082     }
12083   }
12084 
12085   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12086   // classes if required. Ideally the register class constraints would differ
12087   // per-subtarget, but there's no easy way to achieve that right now. This is
12088   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12089   // from using them as the register class for legal types.
12090   if (ST.needsAlignedVGPRs()) {
12091     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12092       const Register Reg = Register::index2VirtReg(I);
12093       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12094       if (!RC)
12095         continue;
12096       int NewClassID = getAlignedAGPRClassID(RC->getID());
12097       if (NewClassID != -1)
12098         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12099     }
12100   }
12101 
12102   TargetLoweringBase::finalizeLowering(MF);
12103 }
12104 
12105 void SITargetLowering::computeKnownBitsForFrameIndex(
12106   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12107   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12108 
12109   // Set the high bits to zero based on the maximum allowed scratch size per
12110   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12111   // calculation won't overflow, so assume the sign bit is never set.
12112   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12113 }
12114 
12115 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12116                                    KnownBits &Known, unsigned Dim) {
12117   unsigned MaxValue =
12118       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12119   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12120 }
12121 
12122 void SITargetLowering::computeKnownBitsForTargetInstr(
12123     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12124     const MachineRegisterInfo &MRI, unsigned Depth) const {
12125   const MachineInstr *MI = MRI.getVRegDef(R);
12126   switch (MI->getOpcode()) {
12127   case AMDGPU::G_INTRINSIC: {
12128     switch (MI->getIntrinsicID()) {
12129     case Intrinsic::amdgcn_workitem_id_x:
12130       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12131       break;
12132     case Intrinsic::amdgcn_workitem_id_y:
12133       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12134       break;
12135     case Intrinsic::amdgcn_workitem_id_z:
12136       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12137       break;
12138     case Intrinsic::amdgcn_mbcnt_lo:
12139     case Intrinsic::amdgcn_mbcnt_hi: {
12140       // These return at most the wavefront size - 1.
12141       unsigned Size = MRI.getType(R).getSizeInBits();
12142       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12143       break;
12144     }
12145     case Intrinsic::amdgcn_groupstaticsize: {
12146       // We can report everything over the maximum size as 0. We can't report
12147       // based on the actual size because we don't know if it's accurate or not
12148       // at any given point.
12149       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12150       break;
12151     }
12152     }
12153     break;
12154   }
12155   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12156     Known.Zero.setHighBits(24);
12157     break;
12158   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12159     Known.Zero.setHighBits(16);
12160     break;
12161   }
12162 }
12163 
12164 Align SITargetLowering::computeKnownAlignForTargetInstr(
12165   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12166   unsigned Depth) const {
12167   const MachineInstr *MI = MRI.getVRegDef(R);
12168   switch (MI->getOpcode()) {
12169   case AMDGPU::G_INTRINSIC:
12170   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12171     // FIXME: Can this move to generic code? What about the case where the call
12172     // site specifies a lower alignment?
12173     Intrinsic::ID IID = MI->getIntrinsicID();
12174     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12175     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12176     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12177       return *RetAlign;
12178     return Align(1);
12179   }
12180   default:
12181     return Align(1);
12182   }
12183 }
12184 
12185 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12186   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12187   const Align CacheLineAlign = Align(64);
12188 
12189   // Pre-GFX10 target did not benefit from loop alignment
12190   if (!ML || DisableLoopAlignment ||
12191       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12192       getSubtarget()->hasInstFwdPrefetchBug())
12193     return PrefAlign;
12194 
12195   // On GFX10 I$ is 4 x 64 bytes cache lines.
12196   // By default prefetcher keeps one cache line behind and reads two ahead.
12197   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12198   // behind and one ahead.
12199   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12200   // If loop fits 64 bytes it always spans no more than two cache lines and
12201   // does not need an alignment.
12202   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12203   // Else if loop is less or equal 192 bytes we need two lines behind.
12204 
12205   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12206   const MachineBasicBlock *Header = ML->getHeader();
12207   if (Header->getAlignment() != PrefAlign)
12208     return Header->getAlignment(); // Already processed.
12209 
12210   unsigned LoopSize = 0;
12211   for (const MachineBasicBlock *MBB : ML->blocks()) {
12212     // If inner loop block is aligned assume in average half of the alignment
12213     // size to be added as nops.
12214     if (MBB != Header)
12215       LoopSize += MBB->getAlignment().value() / 2;
12216 
12217     for (const MachineInstr &MI : *MBB) {
12218       LoopSize += TII->getInstSizeInBytes(MI);
12219       if (LoopSize > 192)
12220         return PrefAlign;
12221     }
12222   }
12223 
12224   if (LoopSize <= 64)
12225     return PrefAlign;
12226 
12227   if (LoopSize <= 128)
12228     return CacheLineAlign;
12229 
12230   // If any of parent loops is surrounded by prefetch instructions do not
12231   // insert new for inner loop, which would reset parent's settings.
12232   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12233     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12234       auto I = Exit->getFirstNonDebugInstr();
12235       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12236         return CacheLineAlign;
12237     }
12238   }
12239 
12240   MachineBasicBlock *Pre = ML->getLoopPreheader();
12241   MachineBasicBlock *Exit = ML->getExitBlock();
12242 
12243   if (Pre && Exit) {
12244     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12245             TII->get(AMDGPU::S_INST_PREFETCH))
12246       .addImm(1); // prefetch 2 lines behind PC
12247 
12248     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12249             TII->get(AMDGPU::S_INST_PREFETCH))
12250       .addImm(2); // prefetch 1 line behind PC
12251   }
12252 
12253   return CacheLineAlign;
12254 }
12255 
12256 LLVM_ATTRIBUTE_UNUSED
12257 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12258   assert(N->getOpcode() == ISD::CopyFromReg);
12259   do {
12260     // Follow the chain until we find an INLINEASM node.
12261     N = N->getOperand(0).getNode();
12262     if (N->getOpcode() == ISD::INLINEASM ||
12263         N->getOpcode() == ISD::INLINEASM_BR)
12264       return true;
12265   } while (N->getOpcode() == ISD::CopyFromReg);
12266   return false;
12267 }
12268 
12269 bool SITargetLowering::isSDNodeSourceOfDivergence(
12270     const SDNode *N, FunctionLoweringInfo *FLI,
12271     LegacyDivergenceAnalysis *KDA) const {
12272   switch (N->getOpcode()) {
12273   case ISD::CopyFromReg: {
12274     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12275     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12276     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12277     Register Reg = R->getReg();
12278 
12279     // FIXME: Why does this need to consider isLiveIn?
12280     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12281       return !TRI->isSGPRReg(MRI, Reg);
12282 
12283     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12284       return KDA->isDivergent(V);
12285 
12286     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12287     return !TRI->isSGPRReg(MRI, Reg);
12288   }
12289   case ISD::LOAD: {
12290     const LoadSDNode *L = cast<LoadSDNode>(N);
12291     unsigned AS = L->getAddressSpace();
12292     // A flat load may access private memory.
12293     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12294   }
12295   case ISD::CALLSEQ_END:
12296     return true;
12297   case ISD::INTRINSIC_WO_CHAIN:
12298     return AMDGPU::isIntrinsicSourceOfDivergence(
12299         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12300   case ISD::INTRINSIC_W_CHAIN:
12301     return AMDGPU::isIntrinsicSourceOfDivergence(
12302         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12303   case AMDGPUISD::ATOMIC_CMP_SWAP:
12304   case AMDGPUISD::ATOMIC_INC:
12305   case AMDGPUISD::ATOMIC_DEC:
12306   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12307   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12308   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12309   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12310   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12311   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12312   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12313   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12314   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12315   case AMDGPUISD::BUFFER_ATOMIC_AND:
12316   case AMDGPUISD::BUFFER_ATOMIC_OR:
12317   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12318   case AMDGPUISD::BUFFER_ATOMIC_INC:
12319   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12320   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12321   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12322   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12323   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12324   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12325     // Target-specific read-modify-write atomics are sources of divergence.
12326     return true;
12327   default:
12328     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12329       // Generic read-modify-write atomics are sources of divergence.
12330       return A->readMem() && A->writeMem();
12331     }
12332     return false;
12333   }
12334 }
12335 
12336 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12337                                                EVT VT) const {
12338   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12339   case MVT::f32:
12340     return hasFP32Denormals(DAG.getMachineFunction());
12341   case MVT::f64:
12342   case MVT::f16:
12343     return hasFP64FP16Denormals(DAG.getMachineFunction());
12344   default:
12345     return false;
12346   }
12347 }
12348 
12349 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12350                                                MachineFunction &MF) const {
12351   switch (Ty.getScalarSizeInBits()) {
12352   case 32:
12353     return hasFP32Denormals(MF);
12354   case 64:
12355   case 16:
12356     return hasFP64FP16Denormals(MF);
12357   default:
12358     return false;
12359   }
12360 }
12361 
12362 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12363                                                     const SelectionDAG &DAG,
12364                                                     bool SNaN,
12365                                                     unsigned Depth) const {
12366   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12367     const MachineFunction &MF = DAG.getMachineFunction();
12368     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12369 
12370     if (Info->getMode().DX10Clamp)
12371       return true; // Clamped to 0.
12372     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12373   }
12374 
12375   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12376                                                             SNaN, Depth);
12377 }
12378 
12379 // Global FP atomic instructions have a hardcoded FP mode and do not support
12380 // FP32 denormals, and only support v2f16 denormals.
12381 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12382   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12383   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12384   if (&Flt == &APFloat::IEEEsingle())
12385     return DenormMode == DenormalMode::getPreserveSign();
12386   return DenormMode == DenormalMode::getIEEE();
12387 }
12388 
12389 TargetLowering::AtomicExpansionKind
12390 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12391 
12392   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12393     OptimizationRemarkEmitter ORE(RMW->getFunction());
12394     LLVMContext &Ctx = RMW->getFunction()->getContext();
12395     SmallVector<StringRef> SSNs;
12396     Ctx.getSyncScopeNames(SSNs);
12397     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12398                         ? "system"
12399                         : SSNs[RMW->getSyncScopeID()];
12400     ORE.emit([&]() {
12401       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12402              << "Hardware instruction generated for atomic "
12403              << RMW->getOperationName(RMW->getOperation())
12404              << " operation at memory scope " << MemScope
12405              << " due to an unsafe request.";
12406     });
12407     return Kind;
12408   };
12409 
12410   switch (RMW->getOperation()) {
12411   case AtomicRMWInst::FAdd: {
12412     Type *Ty = RMW->getType();
12413 
12414     // We don't have a way to support 16-bit atomics now, so just leave them
12415     // as-is.
12416     if (Ty->isHalfTy())
12417       return AtomicExpansionKind::None;
12418 
12419     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12420       return AtomicExpansionKind::CmpXChg;
12421 
12422     unsigned AS = RMW->getPointerAddressSpace();
12423 
12424     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12425          Subtarget->hasAtomicFaddInsts()) {
12426       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12427       // floating point atomic instructions. May generate more efficient code,
12428       // but may not respect rounding and denormal modes, and may give incorrect
12429       // results for certain memory destinations.
12430       if (RMW->getFunction()
12431               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12432               .getValueAsString() != "true")
12433         return AtomicExpansionKind::CmpXChg;
12434 
12435       if (Subtarget->hasGFX90AInsts()) {
12436         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12437           return AtomicExpansionKind::CmpXChg;
12438 
12439         auto SSID = RMW->getSyncScopeID();
12440         if (SSID == SyncScope::System ||
12441             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12442           return AtomicExpansionKind::CmpXChg;
12443 
12444         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12445       }
12446 
12447       if (AS == AMDGPUAS::FLAT_ADDRESS)
12448         return AtomicExpansionKind::CmpXChg;
12449 
12450       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12451                               : AtomicExpansionKind::CmpXChg;
12452     }
12453 
12454     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12455     // to round-to-nearest-even.
12456     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12457     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12458       if (!Ty->isDoubleTy())
12459         return AtomicExpansionKind::None;
12460 
12461       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12462         return AtomicExpansionKind::None;
12463 
12464       return RMW->getFunction()
12465                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12466                          .getValueAsString() == "true"
12467                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12468                  : AtomicExpansionKind::CmpXChg;
12469     }
12470 
12471     return AtomicExpansionKind::CmpXChg;
12472   }
12473   default:
12474     break;
12475   }
12476 
12477   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12478 }
12479 
12480 const TargetRegisterClass *
12481 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12482   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12483   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12484   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12485     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12486                                                : &AMDGPU::SReg_32RegClass;
12487   if (!TRI->isSGPRClass(RC) && !isDivergent)
12488     return TRI->getEquivalentSGPRClass(RC);
12489   else if (TRI->isSGPRClass(RC) && isDivergent)
12490     return TRI->getEquivalentVGPRClass(RC);
12491 
12492   return RC;
12493 }
12494 
12495 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12496 // uniform values (as produced by the mask results of control flow intrinsics)
12497 // used outside of divergent blocks. The phi users need to also be treated as
12498 // always uniform.
12499 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12500                       unsigned WaveSize) {
12501   // FIXME: We asssume we never cast the mask results of a control flow
12502   // intrinsic.
12503   // Early exit if the type won't be consistent as a compile time hack.
12504   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12505   if (!IT || IT->getBitWidth() != WaveSize)
12506     return false;
12507 
12508   if (!isa<Instruction>(V))
12509     return false;
12510   if (!Visited.insert(V).second)
12511     return false;
12512   bool Result = false;
12513   for (auto U : V->users()) {
12514     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12515       if (V == U->getOperand(1)) {
12516         switch (Intrinsic->getIntrinsicID()) {
12517         default:
12518           Result = false;
12519           break;
12520         case Intrinsic::amdgcn_if_break:
12521         case Intrinsic::amdgcn_if:
12522         case Intrinsic::amdgcn_else:
12523           Result = true;
12524           break;
12525         }
12526       }
12527       if (V == U->getOperand(0)) {
12528         switch (Intrinsic->getIntrinsicID()) {
12529         default:
12530           Result = false;
12531           break;
12532         case Intrinsic::amdgcn_end_cf:
12533         case Intrinsic::amdgcn_loop:
12534           Result = true;
12535           break;
12536         }
12537       }
12538     } else {
12539       Result = hasCFUser(U, Visited, WaveSize);
12540     }
12541     if (Result)
12542       break;
12543   }
12544   return Result;
12545 }
12546 
12547 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12548                                                const Value *V) const {
12549   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12550     if (CI->isInlineAsm()) {
12551       // FIXME: This cannot give a correct answer. This should only trigger in
12552       // the case where inline asm returns mixed SGPR and VGPR results, used
12553       // outside the defining block. We don't have a specific result to
12554       // consider, so this assumes if any value is SGPR, the overall register
12555       // also needs to be SGPR.
12556       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12557       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12558           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12559       for (auto &TC : TargetConstraints) {
12560         if (TC.Type == InlineAsm::isOutput) {
12561           ComputeConstraintToUse(TC, SDValue());
12562           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12563               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12564           if (RC && SIRI->isSGPRClass(RC))
12565             return true;
12566         }
12567       }
12568     }
12569   }
12570   SmallPtrSet<const Value *, 16> Visited;
12571   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12572 }
12573 
12574 std::pair<InstructionCost, MVT>
12575 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12576                                           Type *Ty) const {
12577   std::pair<InstructionCost, MVT> Cost =
12578       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12579   auto Size = DL.getTypeSizeInBits(Ty);
12580   // Maximum load or store can handle 8 dwords for scalar and 4 for
12581   // vector ALU. Let's assume anything above 8 dwords is expensive
12582   // even if legal.
12583   if (Size <= 256)
12584     return Cost;
12585 
12586   Cost.first += (Size + 255) / 256;
12587   return Cost;
12588 }
12589 
12590 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12591   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12592   for (; I != E; ++I) {
12593     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12594       if (getBasePtrIndex(M) == I.getOperandNo())
12595         return true;
12596     }
12597   }
12598   return false;
12599 }
12600 
12601 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12602                                            SDValue N1) const {
12603   if (!N0.hasOneUse())
12604     return false;
12605   // Take care of the oportunity to keep N0 uniform
12606   if (N0->isDivergent() || !N1->isDivergent())
12607     return true;
12608   // Check if we have a good chance to form the memory access pattern with the
12609   // base and offset
12610   return (DAG.isBaseWithConstantOffset(N0) &&
12611           hasMemSDNodeUser(*N0->use_begin()));
12612 }
12613 
12614 MachineMemOperand::Flags
12615 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12616   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12617   if (I.getMetadata("amdgpu.noclobber"))
12618     return MONoClobber;
12619   return MachineMemOperand::MONone;
12620 }
12621