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   const Value *Ptr = MemNode->getMemOperand()->getValue();
1643   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1644   return I && I->getMetadata("amdgpu.noclobber");
1645 }
1646 
1647 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1648   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1649          AS == AMDGPUAS::PRIVATE_ADDRESS;
1650 }
1651 
1652 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1653                                            unsigned DestAS) const {
1654   // Flat -> private/local is a simple truncate.
1655   // Flat -> global is no-op
1656   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1657     return true;
1658 
1659   const GCNTargetMachine &TM =
1660       static_cast<const GCNTargetMachine &>(getTargetMachine());
1661   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1662 }
1663 
1664 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1665   const MemSDNode *MemNode = cast<MemSDNode>(N);
1666 
1667   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1668 }
1669 
1670 TargetLoweringBase::LegalizeTypeAction
1671 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1672   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1673       VT.getScalarType().bitsLE(MVT::i16))
1674     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1675   return TargetLoweringBase::getPreferredVectorAction(VT);
1676 }
1677 
1678 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1679                                                          Type *Ty) const {
1680   // FIXME: Could be smarter if called for vector constants.
1681   return true;
1682 }
1683 
1684 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1685   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1686     switch (Op) {
1687     case ISD::LOAD:
1688     case ISD::STORE:
1689 
1690     // These operations are done with 32-bit instructions anyway.
1691     case ISD::AND:
1692     case ISD::OR:
1693     case ISD::XOR:
1694     case ISD::SELECT:
1695       // TODO: Extensions?
1696       return true;
1697     default:
1698       return false;
1699     }
1700   }
1701 
1702   // SimplifySetCC uses this function to determine whether or not it should
1703   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1704   if (VT == MVT::i1 && Op == ISD::SETCC)
1705     return false;
1706 
1707   return TargetLowering::isTypeDesirableForOp(Op, VT);
1708 }
1709 
1710 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1711                                                    const SDLoc &SL,
1712                                                    SDValue Chain,
1713                                                    uint64_t Offset) const {
1714   const DataLayout &DL = DAG.getDataLayout();
1715   MachineFunction &MF = DAG.getMachineFunction();
1716   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1717 
1718   const ArgDescriptor *InputPtrReg;
1719   const TargetRegisterClass *RC;
1720   LLT ArgTy;
1721   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1722 
1723   std::tie(InputPtrReg, RC, ArgTy) =
1724       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1725 
1726   // We may not have the kernarg segment argument if we have no kernel
1727   // arguments.
1728   if (!InputPtrReg)
1729     return DAG.getConstant(0, SL, PtrVT);
1730 
1731   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1732   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1733     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1734 
1735   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1736 }
1737 
1738 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1739                                             const SDLoc &SL) const {
1740   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1741                                                FIRST_IMPLICIT);
1742   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1743 }
1744 
1745 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1746                                          const SDLoc &SL, SDValue Val,
1747                                          bool Signed,
1748                                          const ISD::InputArg *Arg) const {
1749   // First, if it is a widened vector, narrow it.
1750   if (VT.isVector() &&
1751       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1752     EVT NarrowedVT =
1753         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1754                          VT.getVectorNumElements());
1755     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1756                       DAG.getConstant(0, SL, MVT::i32));
1757   }
1758 
1759   // Then convert the vector elements or scalar value.
1760   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1761       VT.bitsLT(MemVT)) {
1762     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1763     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1764   }
1765 
1766   if (MemVT.isFloatingPoint())
1767     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1768   else if (Signed)
1769     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1770   else
1771     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1772 
1773   return Val;
1774 }
1775 
1776 SDValue SITargetLowering::lowerKernargMemParameter(
1777     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1778     uint64_t Offset, Align Alignment, bool Signed,
1779     const ISD::InputArg *Arg) const {
1780   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1781 
1782   // Try to avoid using an extload by loading earlier than the argument address,
1783   // and extracting the relevant bits. The load should hopefully be merged with
1784   // the previous argument.
1785   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1786     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1787     int64_t AlignDownOffset = alignDown(Offset, 4);
1788     int64_t OffsetDiff = Offset - AlignDownOffset;
1789 
1790     EVT IntVT = MemVT.changeTypeToInteger();
1791 
1792     // TODO: If we passed in the base kernel offset we could have a better
1793     // alignment than 4, but we don't really need it.
1794     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1795     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1796                                MachineMemOperand::MODereferenceable |
1797                                    MachineMemOperand::MOInvariant);
1798 
1799     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1800     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1801 
1802     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1803     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1804     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1805 
1806 
1807     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1808   }
1809 
1810   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1811   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1812                              MachineMemOperand::MODereferenceable |
1813                                  MachineMemOperand::MOInvariant);
1814 
1815   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1816   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1817 }
1818 
1819 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1820                                               const SDLoc &SL, SDValue Chain,
1821                                               const ISD::InputArg &Arg) const {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   MachineFrameInfo &MFI = MF.getFrameInfo();
1824 
1825   if (Arg.Flags.isByVal()) {
1826     unsigned Size = Arg.Flags.getByValSize();
1827     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1828     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1829   }
1830 
1831   unsigned ArgOffset = VA.getLocMemOffset();
1832   unsigned ArgSize = VA.getValVT().getStoreSize();
1833 
1834   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1835 
1836   // Create load nodes to retrieve arguments from the stack.
1837   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1838   SDValue ArgValue;
1839 
1840   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1841   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1842   MVT MemVT = VA.getValVT();
1843 
1844   switch (VA.getLocInfo()) {
1845   default:
1846     break;
1847   case CCValAssign::BCvt:
1848     MemVT = VA.getLocVT();
1849     break;
1850   case CCValAssign::SExt:
1851     ExtType = ISD::SEXTLOAD;
1852     break;
1853   case CCValAssign::ZExt:
1854     ExtType = ISD::ZEXTLOAD;
1855     break;
1856   case CCValAssign::AExt:
1857     ExtType = ISD::EXTLOAD;
1858     break;
1859   }
1860 
1861   ArgValue = DAG.getExtLoad(
1862     ExtType, SL, VA.getLocVT(), Chain, FIN,
1863     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1864     MemVT);
1865   return ArgValue;
1866 }
1867 
1868 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1869   const SIMachineFunctionInfo &MFI,
1870   EVT VT,
1871   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1872   const ArgDescriptor *Reg;
1873   const TargetRegisterClass *RC;
1874   LLT Ty;
1875 
1876   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1877   if (!Reg) {
1878     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1879       // It's possible for a kernarg intrinsic call to appear in a kernel with
1880       // no allocated segment, in which case we do not add the user sgpr
1881       // argument, so just return null.
1882       return DAG.getConstant(0, SDLoc(), VT);
1883     }
1884 
1885     // It's undefined behavior if a function marked with the amdgpu-no-*
1886     // attributes uses the corresponding intrinsic.
1887     return DAG.getUNDEF(VT);
1888   }
1889 
1890   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1891 }
1892 
1893 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1894                                CallingConv::ID CallConv,
1895                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1896                                FunctionType *FType,
1897                                SIMachineFunctionInfo *Info) {
1898   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1899     const ISD::InputArg *Arg = &Ins[I];
1900 
1901     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1902            "vector type argument should have been split");
1903 
1904     // First check if it's a PS input addr.
1905     if (CallConv == CallingConv::AMDGPU_PS &&
1906         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1907       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1908 
1909       // Inconveniently only the first part of the split is marked as isSplit,
1910       // so skip to the end. We only want to increment PSInputNum once for the
1911       // entire split argument.
1912       if (Arg->Flags.isSplit()) {
1913         while (!Arg->Flags.isSplitEnd()) {
1914           assert((!Arg->VT.isVector() ||
1915                   Arg->VT.getScalarSizeInBits() == 16) &&
1916                  "unexpected vector split in ps argument type");
1917           if (!SkipArg)
1918             Splits.push_back(*Arg);
1919           Arg = &Ins[++I];
1920         }
1921       }
1922 
1923       if (SkipArg) {
1924         // We can safely skip PS inputs.
1925         Skipped.set(Arg->getOrigArgIndex());
1926         ++PSInputNum;
1927         continue;
1928       }
1929 
1930       Info->markPSInputAllocated(PSInputNum);
1931       if (Arg->Used)
1932         Info->markPSInputEnabled(PSInputNum);
1933 
1934       ++PSInputNum;
1935     }
1936 
1937     Splits.push_back(*Arg);
1938   }
1939 }
1940 
1941 // Allocate special inputs passed in VGPRs.
1942 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1943                                                       MachineFunction &MF,
1944                                                       const SIRegisterInfo &TRI,
1945                                                       SIMachineFunctionInfo &Info) const {
1946   const LLT S32 = LLT::scalar(32);
1947   MachineRegisterInfo &MRI = MF.getRegInfo();
1948 
1949   if (Info.hasWorkItemIDX()) {
1950     Register Reg = AMDGPU::VGPR0;
1951     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1952 
1953     CCInfo.AllocateReg(Reg);
1954     unsigned Mask = (Subtarget->hasPackedTID() &&
1955                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1956     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1957   }
1958 
1959   if (Info.hasWorkItemIDY()) {
1960     assert(Info.hasWorkItemIDX());
1961     if (Subtarget->hasPackedTID()) {
1962       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1963                                                         0x3ff << 10));
1964     } else {
1965       unsigned Reg = AMDGPU::VGPR1;
1966       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1967 
1968       CCInfo.AllocateReg(Reg);
1969       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1970     }
1971   }
1972 
1973   if (Info.hasWorkItemIDZ()) {
1974     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1975     if (Subtarget->hasPackedTID()) {
1976       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1977                                                         0x3ff << 20));
1978     } else {
1979       unsigned Reg = AMDGPU::VGPR2;
1980       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1981 
1982       CCInfo.AllocateReg(Reg);
1983       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1984     }
1985   }
1986 }
1987 
1988 // Try to allocate a VGPR at the end of the argument list, or if no argument
1989 // VGPRs are left allocating a stack slot.
1990 // If \p Mask is is given it indicates bitfield position in the register.
1991 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1992 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1993                                          ArgDescriptor Arg = ArgDescriptor()) {
1994   if (Arg.isSet())
1995     return ArgDescriptor::createArg(Arg, Mask);
1996 
1997   ArrayRef<MCPhysReg> ArgVGPRs
1998     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1999   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2000   if (RegIdx == ArgVGPRs.size()) {
2001     // Spill to stack required.
2002     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2003 
2004     return ArgDescriptor::createStack(Offset, Mask);
2005   }
2006 
2007   unsigned Reg = ArgVGPRs[RegIdx];
2008   Reg = CCInfo.AllocateReg(Reg);
2009   assert(Reg != AMDGPU::NoRegister);
2010 
2011   MachineFunction &MF = CCInfo.getMachineFunction();
2012   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2013   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2014   return ArgDescriptor::createRegister(Reg, Mask);
2015 }
2016 
2017 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2018                                              const TargetRegisterClass *RC,
2019                                              unsigned NumArgRegs) {
2020   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2021   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2022   if (RegIdx == ArgSGPRs.size())
2023     report_fatal_error("ran out of SGPRs for arguments");
2024 
2025   unsigned Reg = ArgSGPRs[RegIdx];
2026   Reg = CCInfo.AllocateReg(Reg);
2027   assert(Reg != AMDGPU::NoRegister);
2028 
2029   MachineFunction &MF = CCInfo.getMachineFunction();
2030   MF.addLiveIn(Reg, RC);
2031   return ArgDescriptor::createRegister(Reg);
2032 }
2033 
2034 // If this has a fixed position, we still should allocate the register in the
2035 // CCInfo state. Technically we could get away with this for values passed
2036 // outside of the normal argument range.
2037 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2038                                        const TargetRegisterClass *RC,
2039                                        MCRegister Reg) {
2040   Reg = CCInfo.AllocateReg(Reg);
2041   assert(Reg != AMDGPU::NoRegister);
2042   MachineFunction &MF = CCInfo.getMachineFunction();
2043   MF.addLiveIn(Reg, RC);
2044 }
2045 
2046 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2047   if (Arg) {
2048     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2049                                Arg.getRegister());
2050   } else
2051     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2052 }
2053 
2054 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2055   if (Arg) {
2056     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2057                                Arg.getRegister());
2058   } else
2059     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2060 }
2061 
2062 /// Allocate implicit function VGPR arguments at the end of allocated user
2063 /// arguments.
2064 void SITargetLowering::allocateSpecialInputVGPRs(
2065   CCState &CCInfo, MachineFunction &MF,
2066   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2067   const unsigned Mask = 0x3ff;
2068   ArgDescriptor Arg;
2069 
2070   if (Info.hasWorkItemIDX()) {
2071     Arg = allocateVGPR32Input(CCInfo, Mask);
2072     Info.setWorkItemIDX(Arg);
2073   }
2074 
2075   if (Info.hasWorkItemIDY()) {
2076     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2077     Info.setWorkItemIDY(Arg);
2078   }
2079 
2080   if (Info.hasWorkItemIDZ())
2081     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2082 }
2083 
2084 /// Allocate implicit function VGPR arguments in fixed registers.
2085 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2086   CCState &CCInfo, MachineFunction &MF,
2087   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2088   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2089   if (!Reg)
2090     report_fatal_error("failed to allocated VGPR for implicit arguments");
2091 
2092   const unsigned Mask = 0x3ff;
2093   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2094   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2095   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2096 }
2097 
2098 void SITargetLowering::allocateSpecialInputSGPRs(
2099   CCState &CCInfo,
2100   MachineFunction &MF,
2101   const SIRegisterInfo &TRI,
2102   SIMachineFunctionInfo &Info) const {
2103   auto &ArgInfo = Info.getArgInfo();
2104 
2105   // TODO: Unify handling with private memory pointers.
2106   if (Info.hasDispatchPtr())
2107     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2108 
2109   if (Info.hasQueuePtr())
2110     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2111 
2112   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2113   // constant offset from the kernarg segment.
2114   if (Info.hasImplicitArgPtr())
2115     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2116 
2117   if (Info.hasDispatchID())
2118     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2119 
2120   // flat_scratch_init is not applicable for non-kernel functions.
2121 
2122   if (Info.hasWorkGroupIDX())
2123     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2124 
2125   if (Info.hasWorkGroupIDY())
2126     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2127 
2128   if (Info.hasWorkGroupIDZ())
2129     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2130 }
2131 
2132 // Allocate special inputs passed in user SGPRs.
2133 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2134                                             MachineFunction &MF,
2135                                             const SIRegisterInfo &TRI,
2136                                             SIMachineFunctionInfo &Info) const {
2137   if (Info.hasImplicitBufferPtr()) {
2138     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2139     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2140     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2141   }
2142 
2143   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2144   if (Info.hasPrivateSegmentBuffer()) {
2145     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2146     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2147     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2148   }
2149 
2150   if (Info.hasDispatchPtr()) {
2151     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2152     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2153     CCInfo.AllocateReg(DispatchPtrReg);
2154   }
2155 
2156   if (Info.hasQueuePtr()) {
2157     Register QueuePtrReg = Info.addQueuePtr(TRI);
2158     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2159     CCInfo.AllocateReg(QueuePtrReg);
2160   }
2161 
2162   if (Info.hasKernargSegmentPtr()) {
2163     MachineRegisterInfo &MRI = MF.getRegInfo();
2164     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2165     CCInfo.AllocateReg(InputPtrReg);
2166 
2167     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2168     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2169   }
2170 
2171   if (Info.hasDispatchID()) {
2172     Register DispatchIDReg = Info.addDispatchID(TRI);
2173     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2174     CCInfo.AllocateReg(DispatchIDReg);
2175   }
2176 
2177   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2178     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2179     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2180     CCInfo.AllocateReg(FlatScratchInitReg);
2181   }
2182 
2183   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2184   // these from the dispatch pointer.
2185 }
2186 
2187 // Allocate special input registers that are initialized per-wave.
2188 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2189                                            MachineFunction &MF,
2190                                            SIMachineFunctionInfo &Info,
2191                                            CallingConv::ID CallConv,
2192                                            bool IsShader) const {
2193   if (Info.hasWorkGroupIDX()) {
2194     Register Reg = Info.addWorkGroupIDX();
2195     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(Reg);
2197   }
2198 
2199   if (Info.hasWorkGroupIDY()) {
2200     Register Reg = Info.addWorkGroupIDY();
2201     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2202     CCInfo.AllocateReg(Reg);
2203   }
2204 
2205   if (Info.hasWorkGroupIDZ()) {
2206     Register Reg = Info.addWorkGroupIDZ();
2207     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2208     CCInfo.AllocateReg(Reg);
2209   }
2210 
2211   if (Info.hasWorkGroupInfo()) {
2212     Register Reg = Info.addWorkGroupInfo();
2213     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2214     CCInfo.AllocateReg(Reg);
2215   }
2216 
2217   if (Info.hasPrivateSegmentWaveByteOffset()) {
2218     // Scratch wave offset passed in system SGPR.
2219     unsigned PrivateSegmentWaveByteOffsetReg;
2220 
2221     if (IsShader) {
2222       PrivateSegmentWaveByteOffsetReg =
2223         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2224 
2225       // This is true if the scratch wave byte offset doesn't have a fixed
2226       // location.
2227       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2228         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2229         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2230       }
2231     } else
2232       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2233 
2234     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2235     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2236   }
2237 }
2238 
2239 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2240                                      MachineFunction &MF,
2241                                      const SIRegisterInfo &TRI,
2242                                      SIMachineFunctionInfo &Info) {
2243   // Now that we've figured out where the scratch register inputs are, see if
2244   // should reserve the arguments and use them directly.
2245   MachineFrameInfo &MFI = MF.getFrameInfo();
2246   bool HasStackObjects = MFI.hasStackObjects();
2247   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2248 
2249   // Record that we know we have non-spill stack objects so we don't need to
2250   // check all stack objects later.
2251   if (HasStackObjects)
2252     Info.setHasNonSpillStackObjects(true);
2253 
2254   // Everything live out of a block is spilled with fast regalloc, so it's
2255   // almost certain that spilling will be required.
2256   if (TM.getOptLevel() == CodeGenOpt::None)
2257     HasStackObjects = true;
2258 
2259   // For now assume stack access is needed in any callee functions, so we need
2260   // the scratch registers to pass in.
2261   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2262 
2263   if (!ST.enableFlatScratch()) {
2264     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2265       // If we have stack objects, we unquestionably need the private buffer
2266       // resource. For the Code Object V2 ABI, this will be the first 4 user
2267       // SGPR inputs. We can reserve those and use them directly.
2268 
2269       Register PrivateSegmentBufferReg =
2270           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2271       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2272     } else {
2273       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2274       // We tentatively reserve the last registers (skipping the last registers
2275       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2276       // we'll replace these with the ones immediately after those which were
2277       // really allocated. In the prologue copies will be inserted from the
2278       // argument to these reserved registers.
2279 
2280       // Without HSA, relocations are used for the scratch pointer and the
2281       // buffer resource setup is always inserted in the prologue. Scratch wave
2282       // offset is still in an input SGPR.
2283       Info.setScratchRSrcReg(ReservedBufferReg);
2284     }
2285   }
2286 
2287   MachineRegisterInfo &MRI = MF.getRegInfo();
2288 
2289   // For entry functions we have to set up the stack pointer if we use it,
2290   // whereas non-entry functions get this "for free". This means there is no
2291   // intrinsic advantage to using S32 over S34 in cases where we do not have
2292   // calls but do need a frame pointer (i.e. if we are requested to have one
2293   // because frame pointer elimination is disabled). To keep things simple we
2294   // only ever use S32 as the call ABI stack pointer, and so using it does not
2295   // imply we need a separate frame pointer.
2296   //
2297   // Try to use s32 as the SP, but move it if it would interfere with input
2298   // arguments. This won't work with calls though.
2299   //
2300   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2301   // registers.
2302   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2303     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2304   } else {
2305     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2306 
2307     if (MFI.hasCalls())
2308       report_fatal_error("call in graphics shader with too many input SGPRs");
2309 
2310     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2311       if (!MRI.isLiveIn(Reg)) {
2312         Info.setStackPtrOffsetReg(Reg);
2313         break;
2314       }
2315     }
2316 
2317     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2318       report_fatal_error("failed to find register for SP");
2319   }
2320 
2321   // hasFP should be accurate for entry functions even before the frame is
2322   // finalized, because it does not rely on the known stack size, only
2323   // properties like whether variable sized objects are present.
2324   if (ST.getFrameLowering()->hasFP(MF)) {
2325     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2326   }
2327 }
2328 
2329 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2330   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2331   return !Info->isEntryFunction();
2332 }
2333 
2334 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2335 
2336 }
2337 
2338 void SITargetLowering::insertCopiesSplitCSR(
2339   MachineBasicBlock *Entry,
2340   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2341   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2342 
2343   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2344   if (!IStart)
2345     return;
2346 
2347   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2348   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2349   MachineBasicBlock::iterator MBBI = Entry->begin();
2350   for (const MCPhysReg *I = IStart; *I; ++I) {
2351     const TargetRegisterClass *RC = nullptr;
2352     if (AMDGPU::SReg_64RegClass.contains(*I))
2353       RC = &AMDGPU::SGPR_64RegClass;
2354     else if (AMDGPU::SReg_32RegClass.contains(*I))
2355       RC = &AMDGPU::SGPR_32RegClass;
2356     else
2357       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2358 
2359     Register NewVR = MRI->createVirtualRegister(RC);
2360     // Create copy from CSR to a virtual register.
2361     Entry->addLiveIn(*I);
2362     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2363       .addReg(*I);
2364 
2365     // Insert the copy-back instructions right before the terminator.
2366     for (auto *Exit : Exits)
2367       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2368               TII->get(TargetOpcode::COPY), *I)
2369         .addReg(NewVR);
2370   }
2371 }
2372 
2373 SDValue SITargetLowering::LowerFormalArguments(
2374     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2375     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2376     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2377   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2378 
2379   MachineFunction &MF = DAG.getMachineFunction();
2380   const Function &Fn = MF.getFunction();
2381   FunctionType *FType = MF.getFunction().getFunctionType();
2382   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2383 
2384   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2385     DiagnosticInfoUnsupported NoGraphicsHSA(
2386         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2387     DAG.getContext()->diagnose(NoGraphicsHSA);
2388     return DAG.getEntryNode();
2389   }
2390 
2391   Info->allocateModuleLDSGlobal(Fn.getParent());
2392 
2393   SmallVector<ISD::InputArg, 16> Splits;
2394   SmallVector<CCValAssign, 16> ArgLocs;
2395   BitVector Skipped(Ins.size());
2396   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2397                  *DAG.getContext());
2398 
2399   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2400   bool IsKernel = AMDGPU::isKernel(CallConv);
2401   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2402 
2403   if (IsGraphics) {
2404     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2405            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2406            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2407            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2408            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2409            !Info->hasWorkItemIDZ());
2410   }
2411 
2412   if (CallConv == CallingConv::AMDGPU_PS) {
2413     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2414 
2415     // At least one interpolation mode must be enabled or else the GPU will
2416     // hang.
2417     //
2418     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2419     // set PSInputAddr, the user wants to enable some bits after the compilation
2420     // based on run-time states. Since we can't know what the final PSInputEna
2421     // will look like, so we shouldn't do anything here and the user should take
2422     // responsibility for the correct programming.
2423     //
2424     // Otherwise, the following restrictions apply:
2425     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2426     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2427     //   enabled too.
2428     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2429         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2430       CCInfo.AllocateReg(AMDGPU::VGPR0);
2431       CCInfo.AllocateReg(AMDGPU::VGPR1);
2432       Info->markPSInputAllocated(0);
2433       Info->markPSInputEnabled(0);
2434     }
2435     if (Subtarget->isAmdPalOS()) {
2436       // For isAmdPalOS, the user does not enable some bits after compilation
2437       // based on run-time states; the register values being generated here are
2438       // the final ones set in hardware. Therefore we need to apply the
2439       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2440       // a bit is set in PSInputAddr but not PSInputEnable is where the
2441       // frontend set up an input arg for a particular interpolation mode, but
2442       // nothing uses that input arg. Really we should have an earlier pass
2443       // that removes such an arg.)
2444       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2445       if ((PsInputBits & 0x7F) == 0 ||
2446           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2447         Info->markPSInputEnabled(
2448             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2449     }
2450   } else if (IsKernel) {
2451     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2452   } else {
2453     Splits.append(Ins.begin(), Ins.end());
2454   }
2455 
2456   if (IsEntryFunc) {
2457     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2458     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2459   } else if (!IsGraphics) {
2460     // For the fixed ABI, pass workitem IDs in the last argument register.
2461     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2462   }
2463 
2464   if (IsKernel) {
2465     analyzeFormalArgumentsCompute(CCInfo, Ins);
2466   } else {
2467     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2468     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2469   }
2470 
2471   SmallVector<SDValue, 16> Chains;
2472 
2473   // FIXME: This is the minimum kernel argument alignment. We should improve
2474   // this to the maximum alignment of the arguments.
2475   //
2476   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2477   // kern arg offset.
2478   const Align KernelArgBaseAlign = Align(16);
2479 
2480   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2481     const ISD::InputArg &Arg = Ins[i];
2482     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2483       InVals.push_back(DAG.getUNDEF(Arg.VT));
2484       continue;
2485     }
2486 
2487     CCValAssign &VA = ArgLocs[ArgIdx++];
2488     MVT VT = VA.getLocVT();
2489 
2490     if (IsEntryFunc && VA.isMemLoc()) {
2491       VT = Ins[i].VT;
2492       EVT MemVT = VA.getLocVT();
2493 
2494       const uint64_t Offset = VA.getLocMemOffset();
2495       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2496 
2497       if (Arg.Flags.isByRef()) {
2498         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2499 
2500         const GCNTargetMachine &TM =
2501             static_cast<const GCNTargetMachine &>(getTargetMachine());
2502         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2503                                     Arg.Flags.getPointerAddrSpace())) {
2504           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2505                                      Arg.Flags.getPointerAddrSpace());
2506         }
2507 
2508         InVals.push_back(Ptr);
2509         continue;
2510       }
2511 
2512       SDValue Arg = lowerKernargMemParameter(
2513         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2514       Chains.push_back(Arg.getValue(1));
2515 
2516       auto *ParamTy =
2517         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2518       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2519           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2520                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2521         // On SI local pointers are just offsets into LDS, so they are always
2522         // less than 16-bits.  On CI and newer they could potentially be
2523         // real pointers, so we can't guarantee their size.
2524         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2525                           DAG.getValueType(MVT::i16));
2526       }
2527 
2528       InVals.push_back(Arg);
2529       continue;
2530     } else if (!IsEntryFunc && VA.isMemLoc()) {
2531       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2532       InVals.push_back(Val);
2533       if (!Arg.Flags.isByVal())
2534         Chains.push_back(Val.getValue(1));
2535       continue;
2536     }
2537 
2538     assert(VA.isRegLoc() && "Parameter must be in a register!");
2539 
2540     Register Reg = VA.getLocReg();
2541     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2542     EVT ValVT = VA.getValVT();
2543 
2544     Reg = MF.addLiveIn(Reg, RC);
2545     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2546 
2547     if (Arg.Flags.isSRet()) {
2548       // The return object should be reasonably addressable.
2549 
2550       // FIXME: This helps when the return is a real sret. If it is a
2551       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2552       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2553       unsigned NumBits
2554         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2555       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2556         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2557     }
2558 
2559     // If this is an 8 or 16-bit value, it is really passed promoted
2560     // to 32 bits. Insert an assert[sz]ext to capture this, then
2561     // truncate to the right size.
2562     switch (VA.getLocInfo()) {
2563     case CCValAssign::Full:
2564       break;
2565     case CCValAssign::BCvt:
2566       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2567       break;
2568     case CCValAssign::SExt:
2569       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2570                         DAG.getValueType(ValVT));
2571       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2572       break;
2573     case CCValAssign::ZExt:
2574       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2575                         DAG.getValueType(ValVT));
2576       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2577       break;
2578     case CCValAssign::AExt:
2579       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2580       break;
2581     default:
2582       llvm_unreachable("Unknown loc info!");
2583     }
2584 
2585     InVals.push_back(Val);
2586   }
2587 
2588   // Start adding system SGPRs.
2589   if (IsEntryFunc) {
2590     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2591   } else {
2592     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2593     if (!IsGraphics)
2594       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2595   }
2596 
2597   auto &ArgUsageInfo =
2598     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2599   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2600 
2601   unsigned StackArgSize = CCInfo.getNextStackOffset();
2602   Info->setBytesInStackArgArea(StackArgSize);
2603 
2604   return Chains.empty() ? Chain :
2605     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2606 }
2607 
2608 // TODO: If return values can't fit in registers, we should return as many as
2609 // possible in registers before passing on stack.
2610 bool SITargetLowering::CanLowerReturn(
2611   CallingConv::ID CallConv,
2612   MachineFunction &MF, bool IsVarArg,
2613   const SmallVectorImpl<ISD::OutputArg> &Outs,
2614   LLVMContext &Context) const {
2615   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2616   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2617   // for shaders. Vector types should be explicitly handled by CC.
2618   if (AMDGPU::isEntryFunctionCC(CallConv))
2619     return true;
2620 
2621   SmallVector<CCValAssign, 16> RVLocs;
2622   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2623   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2624 }
2625 
2626 SDValue
2627 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2628                               bool isVarArg,
2629                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2630                               const SmallVectorImpl<SDValue> &OutVals,
2631                               const SDLoc &DL, SelectionDAG &DAG) const {
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2634 
2635   if (AMDGPU::isKernel(CallConv)) {
2636     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2637                                              OutVals, DL, DAG);
2638   }
2639 
2640   bool IsShader = AMDGPU::isShader(CallConv);
2641 
2642   Info->setIfReturnsVoid(Outs.empty());
2643   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2644 
2645   // CCValAssign - represent the assignment of the return value to a location.
2646   SmallVector<CCValAssign, 48> RVLocs;
2647   SmallVector<ISD::OutputArg, 48> Splits;
2648 
2649   // CCState - Info about the registers and stack slots.
2650   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2651                  *DAG.getContext());
2652 
2653   // Analyze outgoing return values.
2654   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2655 
2656   SDValue Flag;
2657   SmallVector<SDValue, 48> RetOps;
2658   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2659 
2660   // Add return address for callable functions.
2661   if (!Info->isEntryFunction()) {
2662     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2663     SDValue ReturnAddrReg = CreateLiveInRegister(
2664       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2665 
2666     SDValue ReturnAddrVirtualReg =
2667         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2668                             CallConv != CallingConv::AMDGPU_Gfx
2669                                 ? &AMDGPU::CCR_SGPR_64RegClass
2670                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2671                         MVT::i64);
2672     Chain =
2673         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2674     Flag = Chain.getValue(1);
2675     RetOps.push_back(ReturnAddrVirtualReg);
2676   }
2677 
2678   // Copy the result values into the output registers.
2679   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2680        ++I, ++RealRVLocIdx) {
2681     CCValAssign &VA = RVLocs[I];
2682     assert(VA.isRegLoc() && "Can only return in registers!");
2683     // TODO: Partially return in registers if return values don't fit.
2684     SDValue Arg = OutVals[RealRVLocIdx];
2685 
2686     // Copied from other backends.
2687     switch (VA.getLocInfo()) {
2688     case CCValAssign::Full:
2689       break;
2690     case CCValAssign::BCvt:
2691       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2692       break;
2693     case CCValAssign::SExt:
2694       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2695       break;
2696     case CCValAssign::ZExt:
2697       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2698       break;
2699     case CCValAssign::AExt:
2700       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2701       break;
2702     default:
2703       llvm_unreachable("Unknown loc info!");
2704     }
2705 
2706     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2707     Flag = Chain.getValue(1);
2708     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2709   }
2710 
2711   // FIXME: Does sret work properly?
2712   if (!Info->isEntryFunction()) {
2713     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2714     const MCPhysReg *I =
2715       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2716     if (I) {
2717       for (; *I; ++I) {
2718         if (AMDGPU::SReg_64RegClass.contains(*I))
2719           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2720         else if (AMDGPU::SReg_32RegClass.contains(*I))
2721           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2722         else
2723           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2724       }
2725     }
2726   }
2727 
2728   // Update chain and glue.
2729   RetOps[0] = Chain;
2730   if (Flag.getNode())
2731     RetOps.push_back(Flag);
2732 
2733   unsigned Opc = AMDGPUISD::ENDPGM;
2734   if (!IsWaveEnd) {
2735     if (IsShader)
2736       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2737     else if (CallConv == CallingConv::AMDGPU_Gfx)
2738       Opc = AMDGPUISD::RET_GFX_FLAG;
2739     else
2740       Opc = AMDGPUISD::RET_FLAG;
2741   }
2742 
2743   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2744 }
2745 
2746 SDValue SITargetLowering::LowerCallResult(
2747     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2748     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2749     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2750     SDValue ThisVal) const {
2751   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2752 
2753   // Assign locations to each value returned by this call.
2754   SmallVector<CCValAssign, 16> RVLocs;
2755   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2756                  *DAG.getContext());
2757   CCInfo.AnalyzeCallResult(Ins, RetCC);
2758 
2759   // Copy all of the result registers out of their specified physreg.
2760   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761     CCValAssign VA = RVLocs[i];
2762     SDValue Val;
2763 
2764     if (VA.isRegLoc()) {
2765       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2766       Chain = Val.getValue(1);
2767       InFlag = Val.getValue(2);
2768     } else if (VA.isMemLoc()) {
2769       report_fatal_error("TODO: return values in memory");
2770     } else
2771       llvm_unreachable("unknown argument location type");
2772 
2773     switch (VA.getLocInfo()) {
2774     case CCValAssign::Full:
2775       break;
2776     case CCValAssign::BCvt:
2777       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2778       break;
2779     case CCValAssign::ZExt:
2780       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2781                         DAG.getValueType(VA.getValVT()));
2782       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2783       break;
2784     case CCValAssign::SExt:
2785       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2786                         DAG.getValueType(VA.getValVT()));
2787       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2788       break;
2789     case CCValAssign::AExt:
2790       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2791       break;
2792     default:
2793       llvm_unreachable("Unknown loc info!");
2794     }
2795 
2796     InVals.push_back(Val);
2797   }
2798 
2799   return Chain;
2800 }
2801 
2802 // Add code to pass special inputs required depending on used features separate
2803 // from the explicit user arguments present in the IR.
2804 void SITargetLowering::passSpecialInputs(
2805     CallLoweringInfo &CLI,
2806     CCState &CCInfo,
2807     const SIMachineFunctionInfo &Info,
2808     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2809     SmallVectorImpl<SDValue> &MemOpChains,
2810     SDValue Chain) const {
2811   // If we don't have a call site, this was a call inserted by
2812   // legalization. These can never use special inputs.
2813   if (!CLI.CB)
2814     return;
2815 
2816   SelectionDAG &DAG = CLI.DAG;
2817   const SDLoc &DL = CLI.DL;
2818   const Function &F = DAG.getMachineFunction().getFunction();
2819 
2820   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2821   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2822 
2823   const AMDGPUFunctionArgInfo *CalleeArgInfo
2824     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2825   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2826     auto &ArgUsageInfo =
2827       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2828     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2829   }
2830 
2831   // TODO: Unify with private memory register handling. This is complicated by
2832   // the fact that at least in kernels, the input argument is not necessarily
2833   // in the same location as the input.
2834   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2835                              StringLiteral> ImplicitAttrs[] = {
2836     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2837     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2838     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2839     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2840     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2841     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2842     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2843   };
2844 
2845   for (auto Attr : ImplicitAttrs) {
2846     const ArgDescriptor *OutgoingArg;
2847     const TargetRegisterClass *ArgRC;
2848     LLT ArgTy;
2849 
2850     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2851 
2852     // If the callee does not use the attribute value, skip copying the value.
2853     if (CLI.CB->hasFnAttr(Attr.second))
2854       continue;
2855 
2856     std::tie(OutgoingArg, ArgRC, ArgTy) =
2857         CalleeArgInfo->getPreloadedValue(InputID);
2858     if (!OutgoingArg)
2859       continue;
2860 
2861     const ArgDescriptor *IncomingArg;
2862     const TargetRegisterClass *IncomingArgRC;
2863     LLT Ty;
2864     std::tie(IncomingArg, IncomingArgRC, Ty) =
2865         CallerArgInfo.getPreloadedValue(InputID);
2866     assert(IncomingArgRC == ArgRC);
2867 
2868     // All special arguments are ints for now.
2869     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2870     SDValue InputReg;
2871 
2872     if (IncomingArg) {
2873       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2874     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2875       // The implicit arg ptr is special because it doesn't have a corresponding
2876       // input for kernels, and is computed from the kernarg segment pointer.
2877       InputReg = getImplicitArgPtr(DAG, DL);
2878     } else {
2879       // We may have proven the input wasn't needed, although the ABI is
2880       // requiring it. We just need to allocate the register appropriately.
2881       InputReg = DAG.getUNDEF(ArgVT);
2882     }
2883 
2884     if (OutgoingArg->isRegister()) {
2885       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2886       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2887         report_fatal_error("failed to allocate implicit input argument");
2888     } else {
2889       unsigned SpecialArgOffset =
2890           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2891       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2892                                               SpecialArgOffset);
2893       MemOpChains.push_back(ArgStore);
2894     }
2895   }
2896 
2897   // Pack workitem IDs into a single register or pass it as is if already
2898   // packed.
2899   const ArgDescriptor *OutgoingArg;
2900   const TargetRegisterClass *ArgRC;
2901   LLT Ty;
2902 
2903   std::tie(OutgoingArg, ArgRC, Ty) =
2904       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2905   if (!OutgoingArg)
2906     std::tie(OutgoingArg, ArgRC, Ty) =
2907         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2908   if (!OutgoingArg)
2909     std::tie(OutgoingArg, ArgRC, Ty) =
2910         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2911   if (!OutgoingArg)
2912     return;
2913 
2914   const ArgDescriptor *IncomingArgX = std::get<0>(
2915       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2916   const ArgDescriptor *IncomingArgY = std::get<0>(
2917       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2918   const ArgDescriptor *IncomingArgZ = std::get<0>(
2919       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2920 
2921   SDValue InputReg;
2922   SDLoc SL;
2923 
2924   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2925   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2926   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2927 
2928   // If incoming ids are not packed we need to pack them.
2929   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2930       NeedWorkItemIDX) {
2931     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2932       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2933     } else {
2934       InputReg = DAG.getConstant(0, DL, MVT::i32);
2935     }
2936   }
2937 
2938   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2939       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2940     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2941     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2942                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2943     InputReg = InputReg.getNode() ?
2944                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2945   }
2946 
2947   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2948       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2949     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2950     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2951                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2952     InputReg = InputReg.getNode() ?
2953                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2954   }
2955 
2956   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2957     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2958       // We're in a situation where the outgoing function requires the workitem
2959       // ID, but the calling function does not have it (e.g a graphics function
2960       // calling a C calling convention function). This is illegal, but we need
2961       // to produce something.
2962       InputReg = DAG.getUNDEF(MVT::i32);
2963     } else {
2964       // Workitem ids are already packed, any of present incoming arguments
2965       // will carry all required fields.
2966       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2967         IncomingArgX ? *IncomingArgX :
2968         IncomingArgY ? *IncomingArgY :
2969         *IncomingArgZ, ~0u);
2970       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2971     }
2972   }
2973 
2974   if (OutgoingArg->isRegister()) {
2975     if (InputReg)
2976       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2977 
2978     CCInfo.AllocateReg(OutgoingArg->getRegister());
2979   } else {
2980     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2981     if (InputReg) {
2982       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2983                                               SpecialArgOffset);
2984       MemOpChains.push_back(ArgStore);
2985     }
2986   }
2987 }
2988 
2989 static bool canGuaranteeTCO(CallingConv::ID CC) {
2990   return CC == CallingConv::Fast;
2991 }
2992 
2993 /// Return true if we might ever do TCO for calls with this calling convention.
2994 static bool mayTailCallThisCC(CallingConv::ID CC) {
2995   switch (CC) {
2996   case CallingConv::C:
2997   case CallingConv::AMDGPU_Gfx:
2998     return true;
2999   default:
3000     return canGuaranteeTCO(CC);
3001   }
3002 }
3003 
3004 bool SITargetLowering::isEligibleForTailCallOptimization(
3005     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3006     const SmallVectorImpl<ISD::OutputArg> &Outs,
3007     const SmallVectorImpl<SDValue> &OutVals,
3008     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3009   if (!mayTailCallThisCC(CalleeCC))
3010     return false;
3011 
3012   // For a divergent call target, we need to do a waterfall loop over the
3013   // possible callees which precludes us from using a simple jump.
3014   if (Callee->isDivergent())
3015     return false;
3016 
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   const Function &CallerF = MF.getFunction();
3019   CallingConv::ID CallerCC = CallerF.getCallingConv();
3020   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3021   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3022 
3023   // Kernels aren't callable, and don't have a live in return address so it
3024   // doesn't make sense to do a tail call with entry functions.
3025   if (!CallerPreserved)
3026     return false;
3027 
3028   bool CCMatch = CallerCC == CalleeCC;
3029 
3030   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3031     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3032       return true;
3033     return false;
3034   }
3035 
3036   // TODO: Can we handle var args?
3037   if (IsVarArg)
3038     return false;
3039 
3040   for (const Argument &Arg : CallerF.args()) {
3041     if (Arg.hasByValAttr())
3042       return false;
3043   }
3044 
3045   LLVMContext &Ctx = *DAG.getContext();
3046 
3047   // Check that the call results are passed in the same way.
3048   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3049                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3050                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3051     return false;
3052 
3053   // The callee has to preserve all registers the caller needs to preserve.
3054   if (!CCMatch) {
3055     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3056     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3057       return false;
3058   }
3059 
3060   // Nothing more to check if the callee is taking no arguments.
3061   if (Outs.empty())
3062     return true;
3063 
3064   SmallVector<CCValAssign, 16> ArgLocs;
3065   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3066 
3067   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3068 
3069   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3070   // If the stack arguments for this call do not fit into our own save area then
3071   // the call cannot be made tail.
3072   // TODO: Is this really necessary?
3073   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3074     return false;
3075 
3076   const MachineRegisterInfo &MRI = MF.getRegInfo();
3077   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3078 }
3079 
3080 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3081   if (!CI->isTailCall())
3082     return false;
3083 
3084   const Function *ParentFn = CI->getParent()->getParent();
3085   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3086     return false;
3087   return true;
3088 }
3089 
3090 // The wave scratch offset register is used as the global base pointer.
3091 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3092                                     SmallVectorImpl<SDValue> &InVals) const {
3093   SelectionDAG &DAG = CLI.DAG;
3094   const SDLoc &DL = CLI.DL;
3095   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3096   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3097   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3098   SDValue Chain = CLI.Chain;
3099   SDValue Callee = CLI.Callee;
3100   bool &IsTailCall = CLI.IsTailCall;
3101   CallingConv::ID CallConv = CLI.CallConv;
3102   bool IsVarArg = CLI.IsVarArg;
3103   bool IsSibCall = false;
3104   bool IsThisReturn = false;
3105   MachineFunction &MF = DAG.getMachineFunction();
3106 
3107   if (Callee.isUndef() || isNullConstant(Callee)) {
3108     if (!CLI.IsTailCall) {
3109       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3110         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3111     }
3112 
3113     return Chain;
3114   }
3115 
3116   if (IsVarArg) {
3117     return lowerUnhandledCall(CLI, InVals,
3118                               "unsupported call to variadic function ");
3119   }
3120 
3121   if (!CLI.CB)
3122     report_fatal_error("unsupported libcall legalization");
3123 
3124   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3125     return lowerUnhandledCall(CLI, InVals,
3126                               "unsupported required tail call to function ");
3127   }
3128 
3129   if (AMDGPU::isShader(CallConv)) {
3130     // Note the issue is with the CC of the called function, not of the call
3131     // itself.
3132     return lowerUnhandledCall(CLI, InVals,
3133                               "unsupported call to a shader function ");
3134   }
3135 
3136   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3137       CallConv != CallingConv::AMDGPU_Gfx) {
3138     // Only allow calls with specific calling conventions.
3139     return lowerUnhandledCall(CLI, InVals,
3140                               "unsupported calling convention for call from "
3141                               "graphics shader of function ");
3142   }
3143 
3144   if (IsTailCall) {
3145     IsTailCall = isEligibleForTailCallOptimization(
3146       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3147     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3148       report_fatal_error("failed to perform tail call elimination on a call "
3149                          "site marked musttail");
3150     }
3151 
3152     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3153 
3154     // A sibling call is one where we're under the usual C ABI and not planning
3155     // to change that but can still do a tail call:
3156     if (!TailCallOpt && IsTailCall)
3157       IsSibCall = true;
3158 
3159     if (IsTailCall)
3160       ++NumTailCalls;
3161   }
3162 
3163   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3164   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3165   SmallVector<SDValue, 8> MemOpChains;
3166 
3167   // Analyze operands of the call, assigning locations to each operand.
3168   SmallVector<CCValAssign, 16> ArgLocs;
3169   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3170   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3171 
3172   if (CallConv != CallingConv::AMDGPU_Gfx) {
3173     // With a fixed ABI, allocate fixed registers before user arguments.
3174     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3175   }
3176 
3177   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3178 
3179   // Get a count of how many bytes are to be pushed on the stack.
3180   unsigned NumBytes = CCInfo.getNextStackOffset();
3181 
3182   if (IsSibCall) {
3183     // Since we're not changing the ABI to make this a tail call, the memory
3184     // operands are already available in the caller's incoming argument space.
3185     NumBytes = 0;
3186   }
3187 
3188   // FPDiff is the byte offset of the call's argument area from the callee's.
3189   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3190   // by this amount for a tail call. In a sibling call it must be 0 because the
3191   // caller will deallocate the entire stack and the callee still expects its
3192   // arguments to begin at SP+0. Completely unused for non-tail calls.
3193   int32_t FPDiff = 0;
3194   MachineFrameInfo &MFI = MF.getFrameInfo();
3195 
3196   // Adjust the stack pointer for the new arguments...
3197   // These operations are automatically eliminated by the prolog/epilog pass
3198   if (!IsSibCall) {
3199     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3200 
3201     if (!Subtarget->enableFlatScratch()) {
3202       SmallVector<SDValue, 4> CopyFromChains;
3203 
3204       // In the HSA case, this should be an identity copy.
3205       SDValue ScratchRSrcReg
3206         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3207       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3208       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3209       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3210     }
3211   }
3212 
3213   MVT PtrVT = MVT::i32;
3214 
3215   // Walk the register/memloc assignments, inserting copies/loads.
3216   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3217     CCValAssign &VA = ArgLocs[i];
3218     SDValue Arg = OutVals[i];
3219 
3220     // Promote the value if needed.
3221     switch (VA.getLocInfo()) {
3222     case CCValAssign::Full:
3223       break;
3224     case CCValAssign::BCvt:
3225       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3226       break;
3227     case CCValAssign::ZExt:
3228       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3229       break;
3230     case CCValAssign::SExt:
3231       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3232       break;
3233     case CCValAssign::AExt:
3234       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3235       break;
3236     case CCValAssign::FPExt:
3237       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3238       break;
3239     default:
3240       llvm_unreachable("Unknown loc info!");
3241     }
3242 
3243     if (VA.isRegLoc()) {
3244       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3245     } else {
3246       assert(VA.isMemLoc());
3247 
3248       SDValue DstAddr;
3249       MachinePointerInfo DstInfo;
3250 
3251       unsigned LocMemOffset = VA.getLocMemOffset();
3252       int32_t Offset = LocMemOffset;
3253 
3254       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3255       MaybeAlign Alignment;
3256 
3257       if (IsTailCall) {
3258         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3259         unsigned OpSize = Flags.isByVal() ?
3260           Flags.getByValSize() : VA.getValVT().getStoreSize();
3261 
3262         // FIXME: We can have better than the minimum byval required alignment.
3263         Alignment =
3264             Flags.isByVal()
3265                 ? Flags.getNonZeroByValAlign()
3266                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3267 
3268         Offset = Offset + FPDiff;
3269         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3270 
3271         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3272         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3273 
3274         // Make sure any stack arguments overlapping with where we're storing
3275         // are loaded before this eventual operation. Otherwise they'll be
3276         // clobbered.
3277 
3278         // FIXME: Why is this really necessary? This seems to just result in a
3279         // lot of code to copy the stack and write them back to the same
3280         // locations, which are supposed to be immutable?
3281         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3282       } else {
3283         // Stores to the argument stack area are relative to the stack pointer.
3284         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3285                                         MVT::i32);
3286         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3287         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3288         Alignment =
3289             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3290       }
3291 
3292       if (Outs[i].Flags.isByVal()) {
3293         SDValue SizeNode =
3294             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3295         SDValue Cpy =
3296             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3297                           Outs[i].Flags.getNonZeroByValAlign(),
3298                           /*isVol = */ false, /*AlwaysInline = */ true,
3299                           /*isTailCall = */ false, DstInfo,
3300                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3301 
3302         MemOpChains.push_back(Cpy);
3303       } else {
3304         SDValue Store =
3305             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3306         MemOpChains.push_back(Store);
3307       }
3308     }
3309   }
3310 
3311   if (!MemOpChains.empty())
3312     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3313 
3314   // Build a sequence of copy-to-reg nodes chained together with token chain
3315   // and flag operands which copy the outgoing args into the appropriate regs.
3316   SDValue InFlag;
3317   for (auto &RegToPass : RegsToPass) {
3318     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3319                              RegToPass.second, InFlag);
3320     InFlag = Chain.getValue(1);
3321   }
3322 
3323 
3324   SDValue PhysReturnAddrReg;
3325   if (IsTailCall) {
3326     // Since the return is being combined with the call, we need to pass on the
3327     // return address.
3328 
3329     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3330     SDValue ReturnAddrReg = CreateLiveInRegister(
3331       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3332 
3333     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3334                                         MVT::i64);
3335     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3336     InFlag = Chain.getValue(1);
3337   }
3338 
3339   // We don't usually want to end the call-sequence here because we would tidy
3340   // the frame up *after* the call, however in the ABI-changing tail-call case
3341   // we've carefully laid out the parameters so that when sp is reset they'll be
3342   // in the correct location.
3343   if (IsTailCall && !IsSibCall) {
3344     Chain = DAG.getCALLSEQ_END(Chain,
3345                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3346                                DAG.getTargetConstant(0, DL, MVT::i32),
3347                                InFlag, DL);
3348     InFlag = Chain.getValue(1);
3349   }
3350 
3351   std::vector<SDValue> Ops;
3352   Ops.push_back(Chain);
3353   Ops.push_back(Callee);
3354   // Add a redundant copy of the callee global which will not be legalized, as
3355   // we need direct access to the callee later.
3356   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357     const GlobalValue *GV = GSD->getGlobal();
3358     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3359   } else {
3360     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3361   }
3362 
3363   if (IsTailCall) {
3364     // Each tail call may have to adjust the stack by a different amount, so
3365     // this information must travel along with the operation for eventual
3366     // consumption by emitEpilogue.
3367     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3368 
3369     Ops.push_back(PhysReturnAddrReg);
3370   }
3371 
3372   // Add argument registers to the end of the list so that they are known live
3373   // into the call.
3374   for (auto &RegToPass : RegsToPass) {
3375     Ops.push_back(DAG.getRegister(RegToPass.first,
3376                                   RegToPass.second.getValueType()));
3377   }
3378 
3379   // Add a register mask operand representing the call-preserved registers.
3380 
3381   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3382   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3383   assert(Mask && "Missing call preserved mask for calling convention");
3384   Ops.push_back(DAG.getRegisterMask(Mask));
3385 
3386   if (InFlag.getNode())
3387     Ops.push_back(InFlag);
3388 
3389   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3390 
3391   // If we're doing a tall call, use a TC_RETURN here rather than an
3392   // actual call instruction.
3393   if (IsTailCall) {
3394     MFI.setHasTailCall();
3395     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3396   }
3397 
3398   // Returns a chain and a flag for retval copy to use.
3399   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3400   Chain = Call.getValue(0);
3401   InFlag = Call.getValue(1);
3402 
3403   uint64_t CalleePopBytes = NumBytes;
3404   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3405                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3406                              InFlag, DL);
3407   if (!Ins.empty())
3408     InFlag = Chain.getValue(1);
3409 
3410   // Handle result values, copying them out of physregs into vregs that we
3411   // return.
3412   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3413                          InVals, IsThisReturn,
3414                          IsThisReturn ? OutVals[0] : SDValue());
3415 }
3416 
3417 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3418 // except for applying the wave size scale to the increment amount.
3419 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3420     SDValue Op, SelectionDAG &DAG) const {
3421   const MachineFunction &MF = DAG.getMachineFunction();
3422   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3423 
3424   SDLoc dl(Op);
3425   EVT VT = Op.getValueType();
3426   SDValue Tmp1 = Op;
3427   SDValue Tmp2 = Op.getValue(1);
3428   SDValue Tmp3 = Op.getOperand(2);
3429   SDValue Chain = Tmp1.getOperand(0);
3430 
3431   Register SPReg = Info->getStackPtrOffsetReg();
3432 
3433   // Chain the dynamic stack allocation so that it doesn't modify the stack
3434   // pointer when other instructions are using the stack.
3435   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3436 
3437   SDValue Size  = Tmp2.getOperand(1);
3438   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3439   Chain = SP.getValue(1);
3440   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3441   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3442   const TargetFrameLowering *TFL = ST.getFrameLowering();
3443   unsigned Opc =
3444     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3445     ISD::ADD : ISD::SUB;
3446 
3447   SDValue ScaledSize = DAG.getNode(
3448       ISD::SHL, dl, VT, Size,
3449       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3450 
3451   Align StackAlign = TFL->getStackAlign();
3452   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3453   if (Alignment && *Alignment > StackAlign) {
3454     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3455                        DAG.getConstant(-(uint64_t)Alignment->value()
3456                                            << ST.getWavefrontSizeLog2(),
3457                                        dl, VT));
3458   }
3459 
3460   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3461   Tmp2 = DAG.getCALLSEQ_END(
3462       Chain, DAG.getIntPtrConstant(0, dl, true),
3463       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3464 
3465   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3466 }
3467 
3468 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3469                                                   SelectionDAG &DAG) const {
3470   // We only handle constant sizes here to allow non-entry block, static sized
3471   // allocas. A truly dynamic value is more difficult to support because we
3472   // don't know if the size value is uniform or not. If the size isn't uniform,
3473   // we would need to do a wave reduction to get the maximum size to know how
3474   // much to increment the uniform stack pointer.
3475   SDValue Size = Op.getOperand(1);
3476   if (isa<ConstantSDNode>(Size))
3477       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3478 
3479   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3480 }
3481 
3482 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3483                                              const MachineFunction &MF) const {
3484   Register Reg = StringSwitch<Register>(RegName)
3485     .Case("m0", AMDGPU::M0)
3486     .Case("exec", AMDGPU::EXEC)
3487     .Case("exec_lo", AMDGPU::EXEC_LO)
3488     .Case("exec_hi", AMDGPU::EXEC_HI)
3489     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3490     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3491     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3492     .Default(Register());
3493 
3494   if (Reg == AMDGPU::NoRegister) {
3495     report_fatal_error(Twine("invalid register name \""
3496                              + StringRef(RegName)  + "\"."));
3497 
3498   }
3499 
3500   if (!Subtarget->hasFlatScrRegister() &&
3501        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3502     report_fatal_error(Twine("invalid register \""
3503                              + StringRef(RegName)  + "\" for subtarget."));
3504   }
3505 
3506   switch (Reg) {
3507   case AMDGPU::M0:
3508   case AMDGPU::EXEC_LO:
3509   case AMDGPU::EXEC_HI:
3510   case AMDGPU::FLAT_SCR_LO:
3511   case AMDGPU::FLAT_SCR_HI:
3512     if (VT.getSizeInBits() == 32)
3513       return Reg;
3514     break;
3515   case AMDGPU::EXEC:
3516   case AMDGPU::FLAT_SCR:
3517     if (VT.getSizeInBits() == 64)
3518       return Reg;
3519     break;
3520   default:
3521     llvm_unreachable("missing register type checking");
3522   }
3523 
3524   report_fatal_error(Twine("invalid type for register \""
3525                            + StringRef(RegName) + "\"."));
3526 }
3527 
3528 // If kill is not the last instruction, split the block so kill is always a
3529 // proper terminator.
3530 MachineBasicBlock *
3531 SITargetLowering::splitKillBlock(MachineInstr &MI,
3532                                  MachineBasicBlock *BB) const {
3533   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3534   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3535   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3536   return SplitBB;
3537 }
3538 
3539 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3540 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3541 // be the first instruction in the remainder block.
3542 //
3543 /// \returns { LoopBody, Remainder }
3544 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3545 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3546   MachineFunction *MF = MBB.getParent();
3547   MachineBasicBlock::iterator I(&MI);
3548 
3549   // To insert the loop we need to split the block. Move everything after this
3550   // point to a new block, and insert a new empty block between the two.
3551   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3552   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3553   MachineFunction::iterator MBBI(MBB);
3554   ++MBBI;
3555 
3556   MF->insert(MBBI, LoopBB);
3557   MF->insert(MBBI, RemainderBB);
3558 
3559   LoopBB->addSuccessor(LoopBB);
3560   LoopBB->addSuccessor(RemainderBB);
3561 
3562   // Move the rest of the block into a new block.
3563   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3564 
3565   if (InstInLoop) {
3566     auto Next = std::next(I);
3567 
3568     // Move instruction to loop body.
3569     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3570 
3571     // Move the rest of the block.
3572     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3573   } else {
3574     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3575   }
3576 
3577   MBB.addSuccessor(LoopBB);
3578 
3579   return std::make_pair(LoopBB, RemainderBB);
3580 }
3581 
3582 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3583 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3584   MachineBasicBlock *MBB = MI.getParent();
3585   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3586   auto I = MI.getIterator();
3587   auto E = std::next(I);
3588 
3589   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3590     .addImm(0);
3591 
3592   MIBundleBuilder Bundler(*MBB, I, E);
3593   finalizeBundle(*MBB, Bundler.begin());
3594 }
3595 
3596 MachineBasicBlock *
3597 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3598                                          MachineBasicBlock *BB) const {
3599   const DebugLoc &DL = MI.getDebugLoc();
3600 
3601   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3602 
3603   MachineBasicBlock *LoopBB;
3604   MachineBasicBlock *RemainderBB;
3605   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3606 
3607   // Apparently kill flags are only valid if the def is in the same block?
3608   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3609     Src->setIsKill(false);
3610 
3611   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3612 
3613   MachineBasicBlock::iterator I = LoopBB->end();
3614 
3615   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3616     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3617 
3618   // Clear TRAP_STS.MEM_VIOL
3619   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3620     .addImm(0)
3621     .addImm(EncodedReg);
3622 
3623   bundleInstWithWaitcnt(MI);
3624 
3625   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3626 
3627   // Load and check TRAP_STS.MEM_VIOL
3628   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3629     .addImm(EncodedReg);
3630 
3631   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3632   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3633     .addReg(Reg, RegState::Kill)
3634     .addImm(0);
3635   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3636     .addMBB(LoopBB);
3637 
3638   return RemainderBB;
3639 }
3640 
3641 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3642 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3643 // will only do one iteration. In the worst case, this will loop 64 times.
3644 //
3645 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3646 static MachineBasicBlock::iterator
3647 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3648                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3649                        const DebugLoc &DL, const MachineOperand &Idx,
3650                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3651                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3652                        Register &SGPRIdxReg) {
3653 
3654   MachineFunction *MF = OrigBB.getParent();
3655   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3656   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3657   MachineBasicBlock::iterator I = LoopBB.begin();
3658 
3659   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3660   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3661   Register NewExec = MRI.createVirtualRegister(BoolRC);
3662   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3663   Register CondReg = MRI.createVirtualRegister(BoolRC);
3664 
3665   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3666     .addReg(InitReg)
3667     .addMBB(&OrigBB)
3668     .addReg(ResultReg)
3669     .addMBB(&LoopBB);
3670 
3671   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3672     .addReg(InitSaveExecReg)
3673     .addMBB(&OrigBB)
3674     .addReg(NewExec)
3675     .addMBB(&LoopBB);
3676 
3677   // Read the next variant <- also loop target.
3678   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3679       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3680 
3681   // Compare the just read M0 value to all possible Idx values.
3682   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3683       .addReg(CurrentIdxReg)
3684       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3685 
3686   // Update EXEC, save the original EXEC value to VCC.
3687   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3688                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3689           NewExec)
3690     .addReg(CondReg, RegState::Kill);
3691 
3692   MRI.setSimpleHint(NewExec, CondReg);
3693 
3694   if (UseGPRIdxMode) {
3695     if (Offset == 0) {
3696       SGPRIdxReg = CurrentIdxReg;
3697     } else {
3698       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3699       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3700           .addReg(CurrentIdxReg, RegState::Kill)
3701           .addImm(Offset);
3702     }
3703   } else {
3704     // Move index from VCC into M0
3705     if (Offset == 0) {
3706       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3707         .addReg(CurrentIdxReg, RegState::Kill);
3708     } else {
3709       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3710         .addReg(CurrentIdxReg, RegState::Kill)
3711         .addImm(Offset);
3712     }
3713   }
3714 
3715   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3716   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3717   MachineInstr *InsertPt =
3718     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3719                                                   : AMDGPU::S_XOR_B64_term), Exec)
3720       .addReg(Exec)
3721       .addReg(NewExec);
3722 
3723   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3724   // s_cbranch_scc0?
3725 
3726   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3727   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3728     .addMBB(&LoopBB);
3729 
3730   return InsertPt->getIterator();
3731 }
3732 
3733 // This has slightly sub-optimal regalloc when the source vector is killed by
3734 // the read. The register allocator does not understand that the kill is
3735 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3736 // subregister from it, using 1 more VGPR than necessary. This was saved when
3737 // this was expanded after register allocation.
3738 static MachineBasicBlock::iterator
3739 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3740                unsigned InitResultReg, unsigned PhiReg, int Offset,
3741                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3742   MachineFunction *MF = MBB.getParent();
3743   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3744   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3745   MachineRegisterInfo &MRI = MF->getRegInfo();
3746   const DebugLoc &DL = MI.getDebugLoc();
3747   MachineBasicBlock::iterator I(&MI);
3748 
3749   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3750   Register DstReg = MI.getOperand(0).getReg();
3751   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3752   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3753   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3754   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3755 
3756   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3757 
3758   // Save the EXEC mask
3759   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3760     .addReg(Exec);
3761 
3762   MachineBasicBlock *LoopBB;
3763   MachineBasicBlock *RemainderBB;
3764   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3765 
3766   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3767 
3768   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3769                                       InitResultReg, DstReg, PhiReg, TmpExec,
3770                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3771 
3772   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3773   MachineFunction::iterator MBBI(LoopBB);
3774   ++MBBI;
3775   MF->insert(MBBI, LandingPad);
3776   LoopBB->removeSuccessor(RemainderBB);
3777   LandingPad->addSuccessor(RemainderBB);
3778   LoopBB->addSuccessor(LandingPad);
3779   MachineBasicBlock::iterator First = LandingPad->begin();
3780   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3781     .addReg(SaveExec);
3782 
3783   return InsPt;
3784 }
3785 
3786 // Returns subreg index, offset
3787 static std::pair<unsigned, int>
3788 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3789                             const TargetRegisterClass *SuperRC,
3790                             unsigned VecReg,
3791                             int Offset) {
3792   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3793 
3794   // Skip out of bounds offsets, or else we would end up using an undefined
3795   // register.
3796   if (Offset >= NumElts || Offset < 0)
3797     return std::make_pair(AMDGPU::sub0, Offset);
3798 
3799   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3800 }
3801 
3802 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3803                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3804                                  int Offset) {
3805   MachineBasicBlock *MBB = MI.getParent();
3806   const DebugLoc &DL = MI.getDebugLoc();
3807   MachineBasicBlock::iterator I(&MI);
3808 
3809   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3810 
3811   assert(Idx->getReg() != AMDGPU::NoRegister);
3812 
3813   if (Offset == 0) {
3814     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3815   } else {
3816     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3817         .add(*Idx)
3818         .addImm(Offset);
3819   }
3820 }
3821 
3822 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3823                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3824                                    int Offset) {
3825   MachineBasicBlock *MBB = MI.getParent();
3826   const DebugLoc &DL = MI.getDebugLoc();
3827   MachineBasicBlock::iterator I(&MI);
3828 
3829   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3830 
3831   if (Offset == 0)
3832     return Idx->getReg();
3833 
3834   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3835   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3836       .add(*Idx)
3837       .addImm(Offset);
3838   return Tmp;
3839 }
3840 
3841 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3842                                           MachineBasicBlock &MBB,
3843                                           const GCNSubtarget &ST) {
3844   const SIInstrInfo *TII = ST.getInstrInfo();
3845   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3846   MachineFunction *MF = MBB.getParent();
3847   MachineRegisterInfo &MRI = MF->getRegInfo();
3848 
3849   Register Dst = MI.getOperand(0).getReg();
3850   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3851   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3852   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3853 
3854   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3855   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3856 
3857   unsigned SubReg;
3858   std::tie(SubReg, Offset)
3859     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3860 
3861   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3862 
3863   // Check for a SGPR index.
3864   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3865     MachineBasicBlock::iterator I(&MI);
3866     const DebugLoc &DL = MI.getDebugLoc();
3867 
3868     if (UseGPRIdxMode) {
3869       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3870       // to avoid interfering with other uses, so probably requires a new
3871       // optimization pass.
3872       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3873 
3874       const MCInstrDesc &GPRIDXDesc =
3875           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3876       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3877           .addReg(SrcReg)
3878           .addReg(Idx)
3879           .addImm(SubReg);
3880     } else {
3881       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3882 
3883       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3884         .addReg(SrcReg, 0, SubReg)
3885         .addReg(SrcReg, RegState::Implicit);
3886     }
3887 
3888     MI.eraseFromParent();
3889 
3890     return &MBB;
3891   }
3892 
3893   // Control flow needs to be inserted if indexing with a VGPR.
3894   const DebugLoc &DL = MI.getDebugLoc();
3895   MachineBasicBlock::iterator I(&MI);
3896 
3897   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3898   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3899 
3900   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3901 
3902   Register SGPRIdxReg;
3903   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3904                               UseGPRIdxMode, SGPRIdxReg);
3905 
3906   MachineBasicBlock *LoopBB = InsPt->getParent();
3907 
3908   if (UseGPRIdxMode) {
3909     const MCInstrDesc &GPRIDXDesc =
3910         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3911 
3912     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3913         .addReg(SrcReg)
3914         .addReg(SGPRIdxReg)
3915         .addImm(SubReg);
3916   } else {
3917     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3918       .addReg(SrcReg, 0, SubReg)
3919       .addReg(SrcReg, RegState::Implicit);
3920   }
3921 
3922   MI.eraseFromParent();
3923 
3924   return LoopBB;
3925 }
3926 
3927 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3928                                           MachineBasicBlock &MBB,
3929                                           const GCNSubtarget &ST) {
3930   const SIInstrInfo *TII = ST.getInstrInfo();
3931   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3932   MachineFunction *MF = MBB.getParent();
3933   MachineRegisterInfo &MRI = MF->getRegInfo();
3934 
3935   Register Dst = MI.getOperand(0).getReg();
3936   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3937   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3938   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3939   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3940   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3941   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3942 
3943   // This can be an immediate, but will be folded later.
3944   assert(Val->getReg());
3945 
3946   unsigned SubReg;
3947   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3948                                                          SrcVec->getReg(),
3949                                                          Offset);
3950   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3951 
3952   if (Idx->getReg() == AMDGPU::NoRegister) {
3953     MachineBasicBlock::iterator I(&MI);
3954     const DebugLoc &DL = MI.getDebugLoc();
3955 
3956     assert(Offset == 0);
3957 
3958     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3959         .add(*SrcVec)
3960         .add(*Val)
3961         .addImm(SubReg);
3962 
3963     MI.eraseFromParent();
3964     return &MBB;
3965   }
3966 
3967   // Check for a SGPR index.
3968   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3969     MachineBasicBlock::iterator I(&MI);
3970     const DebugLoc &DL = MI.getDebugLoc();
3971 
3972     if (UseGPRIdxMode) {
3973       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3974 
3975       const MCInstrDesc &GPRIDXDesc =
3976           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3977       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3978           .addReg(SrcVec->getReg())
3979           .add(*Val)
3980           .addReg(Idx)
3981           .addImm(SubReg);
3982     } else {
3983       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3984 
3985       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3986           TRI.getRegSizeInBits(*VecRC), 32, false);
3987       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3988           .addReg(SrcVec->getReg())
3989           .add(*Val)
3990           .addImm(SubReg);
3991     }
3992     MI.eraseFromParent();
3993     return &MBB;
3994   }
3995 
3996   // Control flow needs to be inserted if indexing with a VGPR.
3997   if (Val->isReg())
3998     MRI.clearKillFlags(Val->getReg());
3999 
4000   const DebugLoc &DL = MI.getDebugLoc();
4001 
4002   Register PhiReg = MRI.createVirtualRegister(VecRC);
4003 
4004   Register SGPRIdxReg;
4005   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4006                               UseGPRIdxMode, SGPRIdxReg);
4007   MachineBasicBlock *LoopBB = InsPt->getParent();
4008 
4009   if (UseGPRIdxMode) {
4010     const MCInstrDesc &GPRIDXDesc =
4011         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4012 
4013     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4014         .addReg(PhiReg)
4015         .add(*Val)
4016         .addReg(SGPRIdxReg)
4017         .addImm(AMDGPU::sub0);
4018   } else {
4019     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4020         TRI.getRegSizeInBits(*VecRC), 32, false);
4021     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4022         .addReg(PhiReg)
4023         .add(*Val)
4024         .addImm(AMDGPU::sub0);
4025   }
4026 
4027   MI.eraseFromParent();
4028   return LoopBB;
4029 }
4030 
4031 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4032   MachineInstr &MI, MachineBasicBlock *BB) const {
4033 
4034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4035   MachineFunction *MF = BB->getParent();
4036   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4037 
4038   switch (MI.getOpcode()) {
4039   case AMDGPU::S_UADDO_PSEUDO:
4040   case AMDGPU::S_USUBO_PSEUDO: {
4041     const DebugLoc &DL = MI.getDebugLoc();
4042     MachineOperand &Dest0 = MI.getOperand(0);
4043     MachineOperand &Dest1 = MI.getOperand(1);
4044     MachineOperand &Src0 = MI.getOperand(2);
4045     MachineOperand &Src1 = MI.getOperand(3);
4046 
4047     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4048                        ? AMDGPU::S_ADD_I32
4049                        : AMDGPU::S_SUB_I32;
4050     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4051 
4052     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4053         .addImm(1)
4054         .addImm(0);
4055 
4056     MI.eraseFromParent();
4057     return BB;
4058   }
4059   case AMDGPU::S_ADD_U64_PSEUDO:
4060   case AMDGPU::S_SUB_U64_PSEUDO: {
4061     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4062     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4063     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4064     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4065     const DebugLoc &DL = MI.getDebugLoc();
4066 
4067     MachineOperand &Dest = MI.getOperand(0);
4068     MachineOperand &Src0 = MI.getOperand(1);
4069     MachineOperand &Src1 = MI.getOperand(2);
4070 
4071     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4072     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4073 
4074     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4075         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4076     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4077         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4078 
4079     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4080         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4081     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4082         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4083 
4084     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4085 
4086     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4087     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4088     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4089     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4090     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4091         .addReg(DestSub0)
4092         .addImm(AMDGPU::sub0)
4093         .addReg(DestSub1)
4094         .addImm(AMDGPU::sub1);
4095     MI.eraseFromParent();
4096     return BB;
4097   }
4098   case AMDGPU::V_ADD_U64_PSEUDO:
4099   case AMDGPU::V_SUB_U64_PSEUDO: {
4100     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4101     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4102     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4103     const DebugLoc &DL = MI.getDebugLoc();
4104 
4105     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4106 
4107     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4108 
4109     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4110     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4111 
4112     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4113     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4114 
4115     MachineOperand &Dest = MI.getOperand(0);
4116     MachineOperand &Src0 = MI.getOperand(1);
4117     MachineOperand &Src1 = MI.getOperand(2);
4118 
4119     const TargetRegisterClass *Src0RC = Src0.isReg()
4120                                             ? MRI.getRegClass(Src0.getReg())
4121                                             : &AMDGPU::VReg_64RegClass;
4122     const TargetRegisterClass *Src1RC = Src1.isReg()
4123                                             ? MRI.getRegClass(Src1.getReg())
4124                                             : &AMDGPU::VReg_64RegClass;
4125 
4126     const TargetRegisterClass *Src0SubRC =
4127         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4128     const TargetRegisterClass *Src1SubRC =
4129         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4130 
4131     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4132         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4133     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4134         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4135 
4136     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4137         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4138     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4139         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4140 
4141     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4142     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4143                                .addReg(CarryReg, RegState::Define)
4144                                .add(SrcReg0Sub0)
4145                                .add(SrcReg1Sub0)
4146                                .addImm(0); // clamp bit
4147 
4148     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4149     MachineInstr *HiHalf =
4150         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4151             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4152             .add(SrcReg0Sub1)
4153             .add(SrcReg1Sub1)
4154             .addReg(CarryReg, RegState::Kill)
4155             .addImm(0); // clamp bit
4156 
4157     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4158         .addReg(DestSub0)
4159         .addImm(AMDGPU::sub0)
4160         .addReg(DestSub1)
4161         .addImm(AMDGPU::sub1);
4162     TII->legalizeOperands(*LoHalf);
4163     TII->legalizeOperands(*HiHalf);
4164     MI.eraseFromParent();
4165     return BB;
4166   }
4167   case AMDGPU::S_ADD_CO_PSEUDO:
4168   case AMDGPU::S_SUB_CO_PSEUDO: {
4169     // This pseudo has a chance to be selected
4170     // only from uniform add/subcarry node. All the VGPR operands
4171     // therefore assumed to be splat vectors.
4172     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4173     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4174     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4175     MachineBasicBlock::iterator MII = MI;
4176     const DebugLoc &DL = MI.getDebugLoc();
4177     MachineOperand &Dest = MI.getOperand(0);
4178     MachineOperand &CarryDest = MI.getOperand(1);
4179     MachineOperand &Src0 = MI.getOperand(2);
4180     MachineOperand &Src1 = MI.getOperand(3);
4181     MachineOperand &Src2 = MI.getOperand(4);
4182     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4183                        ? AMDGPU::S_ADDC_U32
4184                        : AMDGPU::S_SUBB_U32;
4185     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4186       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4187       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4188           .addReg(Src0.getReg());
4189       Src0.setReg(RegOp0);
4190     }
4191     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4192       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4193       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4194           .addReg(Src1.getReg());
4195       Src1.setReg(RegOp1);
4196     }
4197     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4198     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4199       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4200           .addReg(Src2.getReg());
4201       Src2.setReg(RegOp2);
4202     }
4203 
4204     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4205     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4206     assert(WaveSize == 64 || WaveSize == 32);
4207 
4208     if (WaveSize == 64) {
4209       if (ST.hasScalarCompareEq64()) {
4210         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4211             .addReg(Src2.getReg())
4212             .addImm(0);
4213       } else {
4214         const TargetRegisterClass *SubRC =
4215             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4216         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4217             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4218         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4219             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4220         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4221 
4222         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4223             .add(Src2Sub0)
4224             .add(Src2Sub1);
4225 
4226         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4227             .addReg(Src2_32, RegState::Kill)
4228             .addImm(0);
4229       }
4230     } else {
4231       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4232           .addReg(Src2.getReg())
4233           .addImm(0);
4234     }
4235 
4236     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4237 
4238     unsigned SelOpc =
4239         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4240 
4241     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4242         .addImm(-1)
4243         .addImm(0);
4244 
4245     MI.eraseFromParent();
4246     return BB;
4247   }
4248   case AMDGPU::SI_INIT_M0: {
4249     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4250             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4251         .add(MI.getOperand(0));
4252     MI.eraseFromParent();
4253     return BB;
4254   }
4255   case AMDGPU::GET_GROUPSTATICSIZE: {
4256     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4257            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4258     DebugLoc DL = MI.getDebugLoc();
4259     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4260         .add(MI.getOperand(0))
4261         .addImm(MFI->getLDSSize());
4262     MI.eraseFromParent();
4263     return BB;
4264   }
4265   case AMDGPU::SI_INDIRECT_SRC_V1:
4266   case AMDGPU::SI_INDIRECT_SRC_V2:
4267   case AMDGPU::SI_INDIRECT_SRC_V4:
4268   case AMDGPU::SI_INDIRECT_SRC_V8:
4269   case AMDGPU::SI_INDIRECT_SRC_V16:
4270   case AMDGPU::SI_INDIRECT_SRC_V32:
4271     return emitIndirectSrc(MI, *BB, *getSubtarget());
4272   case AMDGPU::SI_INDIRECT_DST_V1:
4273   case AMDGPU::SI_INDIRECT_DST_V2:
4274   case AMDGPU::SI_INDIRECT_DST_V4:
4275   case AMDGPU::SI_INDIRECT_DST_V8:
4276   case AMDGPU::SI_INDIRECT_DST_V16:
4277   case AMDGPU::SI_INDIRECT_DST_V32:
4278     return emitIndirectDst(MI, *BB, *getSubtarget());
4279   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4280   case AMDGPU::SI_KILL_I1_PSEUDO:
4281     return splitKillBlock(MI, BB);
4282   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4283     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4284     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4285     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4286 
4287     Register Dst = MI.getOperand(0).getReg();
4288     Register Src0 = MI.getOperand(1).getReg();
4289     Register Src1 = MI.getOperand(2).getReg();
4290     const DebugLoc &DL = MI.getDebugLoc();
4291     Register SrcCond = MI.getOperand(3).getReg();
4292 
4293     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4294     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4295     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4296     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4297 
4298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4299       .addReg(SrcCond);
4300     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4301       .addImm(0)
4302       .addReg(Src0, 0, AMDGPU::sub0)
4303       .addImm(0)
4304       .addReg(Src1, 0, AMDGPU::sub0)
4305       .addReg(SrcCondCopy);
4306     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4307       .addImm(0)
4308       .addReg(Src0, 0, AMDGPU::sub1)
4309       .addImm(0)
4310       .addReg(Src1, 0, AMDGPU::sub1)
4311       .addReg(SrcCondCopy);
4312 
4313     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4314       .addReg(DstLo)
4315       .addImm(AMDGPU::sub0)
4316       .addReg(DstHi)
4317       .addImm(AMDGPU::sub1);
4318     MI.eraseFromParent();
4319     return BB;
4320   }
4321   case AMDGPU::SI_BR_UNDEF: {
4322     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4323     const DebugLoc &DL = MI.getDebugLoc();
4324     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4325                            .add(MI.getOperand(0));
4326     Br->getOperand(1).setIsUndef(true); // read undef SCC
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::ADJCALLSTACKUP:
4331   case AMDGPU::ADJCALLSTACKDOWN: {
4332     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4333     MachineInstrBuilder MIB(*MF, &MI);
4334     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4335        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4336     return BB;
4337   }
4338   case AMDGPU::SI_CALL_ISEL: {
4339     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4340     const DebugLoc &DL = MI.getDebugLoc();
4341 
4342     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4343 
4344     MachineInstrBuilder MIB;
4345     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4346 
4347     for (const MachineOperand &MO : MI.operands())
4348       MIB.add(MO);
4349 
4350     MIB.cloneMemRefs(MI);
4351     MI.eraseFromParent();
4352     return BB;
4353   }
4354   case AMDGPU::V_ADD_CO_U32_e32:
4355   case AMDGPU::V_SUB_CO_U32_e32:
4356   case AMDGPU::V_SUBREV_CO_U32_e32: {
4357     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4358     const DebugLoc &DL = MI.getDebugLoc();
4359     unsigned Opc = MI.getOpcode();
4360 
4361     bool NeedClampOperand = false;
4362     if (TII->pseudoToMCOpcode(Opc) == -1) {
4363       Opc = AMDGPU::getVOPe64(Opc);
4364       NeedClampOperand = true;
4365     }
4366 
4367     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4368     if (TII->isVOP3(*I)) {
4369       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4370       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4371       I.addReg(TRI->getVCC(), RegState::Define);
4372     }
4373     I.add(MI.getOperand(1))
4374      .add(MI.getOperand(2));
4375     if (NeedClampOperand)
4376       I.addImm(0); // clamp bit for e64 encoding
4377 
4378     TII->legalizeOperands(*I);
4379 
4380     MI.eraseFromParent();
4381     return BB;
4382   }
4383   case AMDGPU::V_ADDC_U32_e32:
4384   case AMDGPU::V_SUBB_U32_e32:
4385   case AMDGPU::V_SUBBREV_U32_e32:
4386     // These instructions have an implicit use of vcc which counts towards the
4387     // constant bus limit.
4388     TII->legalizeOperands(MI);
4389     return BB;
4390   case AMDGPU::DS_GWS_INIT:
4391   case AMDGPU::DS_GWS_SEMA_BR:
4392   case AMDGPU::DS_GWS_BARRIER:
4393     if (Subtarget->needsAlignedVGPRs()) {
4394       // Add implicit aligned super-reg to force alignment on the data operand.
4395       const DebugLoc &DL = MI.getDebugLoc();
4396       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4397       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4398       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4399       Register DataReg = Op->getReg();
4400       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4401       Register Undef = MRI.createVirtualRegister(
4402           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4403       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4404       Register NewVR =
4405           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4406                                            : &AMDGPU::VReg_64_Align2RegClass);
4407       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4408           .addReg(DataReg, 0, Op->getSubReg())
4409           .addImm(AMDGPU::sub0)
4410           .addReg(Undef)
4411           .addImm(AMDGPU::sub1);
4412       Op->setReg(NewVR);
4413       Op->setSubReg(AMDGPU::sub0);
4414       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4415     }
4416     LLVM_FALLTHROUGH;
4417   case AMDGPU::DS_GWS_SEMA_V:
4418   case AMDGPU::DS_GWS_SEMA_P:
4419   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4420     // A s_waitcnt 0 is required to be the instruction immediately following.
4421     if (getSubtarget()->hasGWSAutoReplay()) {
4422       bundleInstWithWaitcnt(MI);
4423       return BB;
4424     }
4425 
4426     return emitGWSMemViolTestLoop(MI, BB);
4427   case AMDGPU::S_SETREG_B32: {
4428     // Try to optimize cases that only set the denormal mode or rounding mode.
4429     //
4430     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4431     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4432     // instead.
4433     //
4434     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4435     // allow you to have a no side effect instruction in the output of a
4436     // sideeffecting pattern.
4437     unsigned ID, Offset, Width;
4438     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4439     if (ID != AMDGPU::Hwreg::ID_MODE)
4440       return BB;
4441 
4442     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4443     const unsigned SetMask = WidthMask << Offset;
4444 
4445     if (getSubtarget()->hasDenormModeInst()) {
4446       unsigned SetDenormOp = 0;
4447       unsigned SetRoundOp = 0;
4448 
4449       // The dedicated instructions can only set the whole denorm or round mode
4450       // at once, not a subset of bits in either.
4451       if (SetMask ==
4452           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4453         // If this fully sets both the round and denorm mode, emit the two
4454         // dedicated instructions for these.
4455         SetRoundOp = AMDGPU::S_ROUND_MODE;
4456         SetDenormOp = AMDGPU::S_DENORM_MODE;
4457       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4458         SetRoundOp = AMDGPU::S_ROUND_MODE;
4459       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4460         SetDenormOp = AMDGPU::S_DENORM_MODE;
4461       }
4462 
4463       if (SetRoundOp || SetDenormOp) {
4464         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4465         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4466         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4467           unsigned ImmVal = Def->getOperand(1).getImm();
4468           if (SetRoundOp) {
4469             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4470                 .addImm(ImmVal & 0xf);
4471 
4472             // If we also have the denorm mode, get just the denorm mode bits.
4473             ImmVal >>= 4;
4474           }
4475 
4476           if (SetDenormOp) {
4477             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4478                 .addImm(ImmVal & 0xf);
4479           }
4480 
4481           MI.eraseFromParent();
4482           return BB;
4483         }
4484       }
4485     }
4486 
4487     // If only FP bits are touched, used the no side effects pseudo.
4488     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4489                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4490       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4491 
4492     return BB;
4493   }
4494   default:
4495     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4496   }
4497 }
4498 
4499 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4500   return isTypeLegal(VT.getScalarType());
4501 }
4502 
4503 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4504   // This currently forces unfolding various combinations of fsub into fma with
4505   // free fneg'd operands. As long as we have fast FMA (controlled by
4506   // isFMAFasterThanFMulAndFAdd), we should perform these.
4507 
4508   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4509   // most of these combines appear to be cycle neutral but save on instruction
4510   // count / code size.
4511   return true;
4512 }
4513 
4514 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4515 
4516 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4517                                          EVT VT) const {
4518   if (!VT.isVector()) {
4519     return MVT::i1;
4520   }
4521   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4522 }
4523 
4524 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4525   // TODO: Should i16 be used always if legal? For now it would force VALU
4526   // shifts.
4527   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4528 }
4529 
4530 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4531   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4532              ? Ty.changeElementSize(16)
4533              : Ty.changeElementSize(32);
4534 }
4535 
4536 // Answering this is somewhat tricky and depends on the specific device which
4537 // have different rates for fma or all f64 operations.
4538 //
4539 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4540 // regardless of which device (although the number of cycles differs between
4541 // devices), so it is always profitable for f64.
4542 //
4543 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4544 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4545 // which we can always do even without fused FP ops since it returns the same
4546 // result as the separate operations and since it is always full
4547 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4548 // however does not support denormals, so we do report fma as faster if we have
4549 // a fast fma device and require denormals.
4550 //
4551 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4552                                                   EVT VT) const {
4553   VT = VT.getScalarType();
4554 
4555   switch (VT.getSimpleVT().SimpleTy) {
4556   case MVT::f32: {
4557     // If mad is not available this depends only on if f32 fma is full rate.
4558     if (!Subtarget->hasMadMacF32Insts())
4559       return Subtarget->hasFastFMAF32();
4560 
4561     // Otherwise f32 mad is always full rate and returns the same result as
4562     // the separate operations so should be preferred over fma.
4563     // However does not support denomals.
4564     if (hasFP32Denormals(MF))
4565       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4566 
4567     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4568     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4569   }
4570   case MVT::f64:
4571     return true;
4572   case MVT::f16:
4573     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4574   default:
4575     break;
4576   }
4577 
4578   return false;
4579 }
4580 
4581 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4582                                                   LLT Ty) const {
4583   switch (Ty.getScalarSizeInBits()) {
4584   case 16:
4585     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4586   case 32:
4587     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4588   case 64:
4589     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4590   default:
4591     break;
4592   }
4593 
4594   return false;
4595 }
4596 
4597 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4598   if (!Ty.isScalar())
4599     return false;
4600 
4601   if (Ty.getScalarSizeInBits() == 16)
4602     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4603   if (Ty.getScalarSizeInBits() == 32)
4604     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4605 
4606   return false;
4607 }
4608 
4609 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4610                                    const SDNode *N) const {
4611   // TODO: Check future ftz flag
4612   // v_mad_f32/v_mac_f32 do not support denormals.
4613   EVT VT = N->getValueType(0);
4614   if (VT == MVT::f32)
4615     return Subtarget->hasMadMacF32Insts() &&
4616            !hasFP32Denormals(DAG.getMachineFunction());
4617   if (VT == MVT::f16) {
4618     return Subtarget->hasMadF16() &&
4619            !hasFP64FP16Denormals(DAG.getMachineFunction());
4620   }
4621 
4622   return false;
4623 }
4624 
4625 //===----------------------------------------------------------------------===//
4626 // Custom DAG Lowering Operations
4627 //===----------------------------------------------------------------------===//
4628 
4629 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4630 // wider vector type is legal.
4631 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4632                                              SelectionDAG &DAG) const {
4633   unsigned Opc = Op.getOpcode();
4634   EVT VT = Op.getValueType();
4635   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4636 
4637   SDValue Lo, Hi;
4638   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4639 
4640   SDLoc SL(Op);
4641   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4642                              Op->getFlags());
4643   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4644                              Op->getFlags());
4645 
4646   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4647 }
4648 
4649 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4650 // wider vector type is legal.
4651 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4652                                               SelectionDAG &DAG) const {
4653   unsigned Opc = Op.getOpcode();
4654   EVT VT = Op.getValueType();
4655   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4656          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4657          VT == MVT::v16f32 || VT == MVT::v32f32);
4658 
4659   SDValue Lo0, Hi0;
4660   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4661   SDValue Lo1, Hi1;
4662   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4663 
4664   SDLoc SL(Op);
4665 
4666   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4667                              Op->getFlags());
4668   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4669                              Op->getFlags());
4670 
4671   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4672 }
4673 
4674 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4675                                               SelectionDAG &DAG) const {
4676   unsigned Opc = Op.getOpcode();
4677   EVT VT = Op.getValueType();
4678   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4679          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4680          VT == MVT::v16f32 || VT == MVT::v32f32);
4681 
4682   SDValue Lo0, Hi0;
4683   SDValue Op0 = Op.getOperand(0);
4684   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4685                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4686                          : std::make_pair(Op0, Op0);
4687   SDValue Lo1, Hi1;
4688   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4689   SDValue Lo2, Hi2;
4690   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4691 
4692   SDLoc SL(Op);
4693   auto ResVT = DAG.GetSplitDestVTs(VT);
4694 
4695   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4696                              Op->getFlags());
4697   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4698                              Op->getFlags());
4699 
4700   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4701 }
4702 
4703 
4704 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4705   switch (Op.getOpcode()) {
4706   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4707   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4708   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4709   case ISD::LOAD: {
4710     SDValue Result = LowerLOAD(Op, DAG);
4711     assert((!Result.getNode() ||
4712             Result.getNode()->getNumValues() == 2) &&
4713            "Load should return a value and a chain");
4714     return Result;
4715   }
4716 
4717   case ISD::FSIN:
4718   case ISD::FCOS:
4719     return LowerTrig(Op, DAG);
4720   case ISD::SELECT: return LowerSELECT(Op, DAG);
4721   case ISD::FDIV: return LowerFDIV(Op, DAG);
4722   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4723   case ISD::STORE: return LowerSTORE(Op, DAG);
4724   case ISD::GlobalAddress: {
4725     MachineFunction &MF = DAG.getMachineFunction();
4726     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4727     return LowerGlobalAddress(MFI, Op, DAG);
4728   }
4729   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4730   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4731   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4732   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4733   case ISD::INSERT_SUBVECTOR:
4734     return lowerINSERT_SUBVECTOR(Op, DAG);
4735   case ISD::INSERT_VECTOR_ELT:
4736     return lowerINSERT_VECTOR_ELT(Op, DAG);
4737   case ISD::EXTRACT_VECTOR_ELT:
4738     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4739   case ISD::VECTOR_SHUFFLE:
4740     return lowerVECTOR_SHUFFLE(Op, DAG);
4741   case ISD::BUILD_VECTOR:
4742     return lowerBUILD_VECTOR(Op, DAG);
4743   case ISD::FP_ROUND:
4744     return lowerFP_ROUND(Op, DAG);
4745   case ISD::TRAP:
4746     return lowerTRAP(Op, DAG);
4747   case ISD::DEBUGTRAP:
4748     return lowerDEBUGTRAP(Op, DAG);
4749   case ISD::FABS:
4750   case ISD::FNEG:
4751   case ISD::FCANONICALIZE:
4752   case ISD::BSWAP:
4753     return splitUnaryVectorOp(Op, DAG);
4754   case ISD::FMINNUM:
4755   case ISD::FMAXNUM:
4756     return lowerFMINNUM_FMAXNUM(Op, DAG);
4757   case ISD::FMA:
4758     return splitTernaryVectorOp(Op, DAG);
4759   case ISD::FP_TO_SINT:
4760   case ISD::FP_TO_UINT:
4761     return LowerFP_TO_INT(Op, DAG);
4762   case ISD::SHL:
4763   case ISD::SRA:
4764   case ISD::SRL:
4765   case ISD::ADD:
4766   case ISD::SUB:
4767   case ISD::MUL:
4768   case ISD::SMIN:
4769   case ISD::SMAX:
4770   case ISD::UMIN:
4771   case ISD::UMAX:
4772   case ISD::FADD:
4773   case ISD::FMUL:
4774   case ISD::FMINNUM_IEEE:
4775   case ISD::FMAXNUM_IEEE:
4776   case ISD::UADDSAT:
4777   case ISD::USUBSAT:
4778   case ISD::SADDSAT:
4779   case ISD::SSUBSAT:
4780     return splitBinaryVectorOp(Op, DAG);
4781   case ISD::SMULO:
4782   case ISD::UMULO:
4783     return lowerXMULO(Op, DAG);
4784   case ISD::SMUL_LOHI:
4785   case ISD::UMUL_LOHI:
4786     return lowerXMUL_LOHI(Op, DAG);
4787   case ISD::DYNAMIC_STACKALLOC:
4788     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4789   }
4790   return SDValue();
4791 }
4792 
4793 // Used for D16: Casts the result of an instruction into the right vector,
4794 // packs values if loads return unpacked values.
4795 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4796                                        const SDLoc &DL,
4797                                        SelectionDAG &DAG, bool Unpacked) {
4798   if (!LoadVT.isVector())
4799     return Result;
4800 
4801   // Cast back to the original packed type or to a larger type that is a
4802   // multiple of 32 bit for D16. Widening the return type is a required for
4803   // legalization.
4804   EVT FittingLoadVT = LoadVT;
4805   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4806     FittingLoadVT =
4807         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4808                          LoadVT.getVectorNumElements() + 1);
4809   }
4810 
4811   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4812     // Truncate to v2i16/v4i16.
4813     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4814 
4815     // Workaround legalizer not scalarizing truncate after vector op
4816     // legalization but not creating intermediate vector trunc.
4817     SmallVector<SDValue, 4> Elts;
4818     DAG.ExtractVectorElements(Result, Elts);
4819     for (SDValue &Elt : Elts)
4820       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4821 
4822     // Pad illegal v1i16/v3fi6 to v4i16
4823     if ((LoadVT.getVectorNumElements() % 2) == 1)
4824       Elts.push_back(DAG.getUNDEF(MVT::i16));
4825 
4826     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4827 
4828     // Bitcast to original type (v2f16/v4f16).
4829     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4830   }
4831 
4832   // Cast back to the original packed type.
4833   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4834 }
4835 
4836 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4837                                               MemSDNode *M,
4838                                               SelectionDAG &DAG,
4839                                               ArrayRef<SDValue> Ops,
4840                                               bool IsIntrinsic) const {
4841   SDLoc DL(M);
4842 
4843   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4844   EVT LoadVT = M->getValueType(0);
4845 
4846   EVT EquivLoadVT = LoadVT;
4847   if (LoadVT.isVector()) {
4848     if (Unpacked) {
4849       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4850                                      LoadVT.getVectorNumElements());
4851     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4852       // Widen v3f16 to legal type
4853       EquivLoadVT =
4854           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4855                            LoadVT.getVectorNumElements() + 1);
4856     }
4857   }
4858 
4859   // Change from v4f16/v2f16 to EquivLoadVT.
4860   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4861 
4862   SDValue Load
4863     = DAG.getMemIntrinsicNode(
4864       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4865       VTList, Ops, M->getMemoryVT(),
4866       M->getMemOperand());
4867 
4868   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4869 
4870   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4871 }
4872 
4873 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4874                                              SelectionDAG &DAG,
4875                                              ArrayRef<SDValue> Ops) const {
4876   SDLoc DL(M);
4877   EVT LoadVT = M->getValueType(0);
4878   EVT EltType = LoadVT.getScalarType();
4879   EVT IntVT = LoadVT.changeTypeToInteger();
4880 
4881   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4882 
4883   unsigned Opc =
4884       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4885 
4886   if (IsD16) {
4887     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4888   }
4889 
4890   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4891   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4892     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4893 
4894   if (isTypeLegal(LoadVT)) {
4895     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4896                                M->getMemOperand(), DAG);
4897   }
4898 
4899   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4900   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4901   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4902                                         M->getMemOperand(), DAG);
4903   return DAG.getMergeValues(
4904       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4905       DL);
4906 }
4907 
4908 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4909                                   SDNode *N, SelectionDAG &DAG) {
4910   EVT VT = N->getValueType(0);
4911   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4912   unsigned CondCode = CD->getZExtValue();
4913   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4914     return DAG.getUNDEF(VT);
4915 
4916   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4917 
4918   SDValue LHS = N->getOperand(1);
4919   SDValue RHS = N->getOperand(2);
4920 
4921   SDLoc DL(N);
4922 
4923   EVT CmpVT = LHS.getValueType();
4924   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4925     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4926       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4927     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4928     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4929   }
4930 
4931   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4932 
4933   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4934   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4935 
4936   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4937                               DAG.getCondCode(CCOpcode));
4938   if (VT.bitsEq(CCVT))
4939     return SetCC;
4940   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4941 }
4942 
4943 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4944                                   SDNode *N, SelectionDAG &DAG) {
4945   EVT VT = N->getValueType(0);
4946   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4947 
4948   unsigned CondCode = CD->getZExtValue();
4949   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4950     return DAG.getUNDEF(VT);
4951 
4952   SDValue Src0 = N->getOperand(1);
4953   SDValue Src1 = N->getOperand(2);
4954   EVT CmpVT = Src0.getValueType();
4955   SDLoc SL(N);
4956 
4957   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4958     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4959     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4960   }
4961 
4962   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4963   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4964   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4965   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4966   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4967                               Src1, DAG.getCondCode(CCOpcode));
4968   if (VT.bitsEq(CCVT))
4969     return SetCC;
4970   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4971 }
4972 
4973 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4974                                     SelectionDAG &DAG) {
4975   EVT VT = N->getValueType(0);
4976   SDValue Src = N->getOperand(1);
4977   SDLoc SL(N);
4978 
4979   if (Src.getOpcode() == ISD::SETCC) {
4980     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4981     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4982                        Src.getOperand(1), Src.getOperand(2));
4983   }
4984   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4985     // (ballot 0) -> 0
4986     if (Arg->isZero())
4987       return DAG.getConstant(0, SL, VT);
4988 
4989     // (ballot 1) -> EXEC/EXEC_LO
4990     if (Arg->isOne()) {
4991       Register Exec;
4992       if (VT.getScalarSizeInBits() == 32)
4993         Exec = AMDGPU::EXEC_LO;
4994       else if (VT.getScalarSizeInBits() == 64)
4995         Exec = AMDGPU::EXEC;
4996       else
4997         return SDValue();
4998 
4999       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5000     }
5001   }
5002 
5003   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5004   // ISD::SETNE)
5005   return DAG.getNode(
5006       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5007       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5008 }
5009 
5010 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5011                                           SmallVectorImpl<SDValue> &Results,
5012                                           SelectionDAG &DAG) const {
5013   switch (N->getOpcode()) {
5014   case ISD::INSERT_VECTOR_ELT: {
5015     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5016       Results.push_back(Res);
5017     return;
5018   }
5019   case ISD::EXTRACT_VECTOR_ELT: {
5020     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5021       Results.push_back(Res);
5022     return;
5023   }
5024   case ISD::INTRINSIC_WO_CHAIN: {
5025     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5026     switch (IID) {
5027     case Intrinsic::amdgcn_cvt_pkrtz: {
5028       SDValue Src0 = N->getOperand(1);
5029       SDValue Src1 = N->getOperand(2);
5030       SDLoc SL(N);
5031       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5032                                 Src0, Src1);
5033       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5034       return;
5035     }
5036     case Intrinsic::amdgcn_cvt_pknorm_i16:
5037     case Intrinsic::amdgcn_cvt_pknorm_u16:
5038     case Intrinsic::amdgcn_cvt_pk_i16:
5039     case Intrinsic::amdgcn_cvt_pk_u16: {
5040       SDValue Src0 = N->getOperand(1);
5041       SDValue Src1 = N->getOperand(2);
5042       SDLoc SL(N);
5043       unsigned Opcode;
5044 
5045       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5046         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5047       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5048         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5049       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5050         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5051       else
5052         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5053 
5054       EVT VT = N->getValueType(0);
5055       if (isTypeLegal(VT))
5056         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5057       else {
5058         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5059         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5060       }
5061       return;
5062     }
5063     }
5064     break;
5065   }
5066   case ISD::INTRINSIC_W_CHAIN: {
5067     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5068       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5069         // FIXME: Hacky
5070         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5071           Results.push_back(Res.getOperand(I));
5072         }
5073       } else {
5074         Results.push_back(Res);
5075         Results.push_back(Res.getValue(1));
5076       }
5077       return;
5078     }
5079 
5080     break;
5081   }
5082   case ISD::SELECT: {
5083     SDLoc SL(N);
5084     EVT VT = N->getValueType(0);
5085     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5086     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5087     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5088 
5089     EVT SelectVT = NewVT;
5090     if (NewVT.bitsLT(MVT::i32)) {
5091       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5092       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5093       SelectVT = MVT::i32;
5094     }
5095 
5096     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5097                                     N->getOperand(0), LHS, RHS);
5098 
5099     if (NewVT != SelectVT)
5100       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5101     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5102     return;
5103   }
5104   case ISD::FNEG: {
5105     if (N->getValueType(0) != MVT::v2f16)
5106       break;
5107 
5108     SDLoc SL(N);
5109     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5110 
5111     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5112                              BC,
5113                              DAG.getConstant(0x80008000, SL, MVT::i32));
5114     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5115     return;
5116   }
5117   case ISD::FABS: {
5118     if (N->getValueType(0) != MVT::v2f16)
5119       break;
5120 
5121     SDLoc SL(N);
5122     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5123 
5124     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5125                              BC,
5126                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5127     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5128     return;
5129   }
5130   default:
5131     break;
5132   }
5133 }
5134 
5135 /// Helper function for LowerBRCOND
5136 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5137 
5138   SDNode *Parent = Value.getNode();
5139   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5140        I != E; ++I) {
5141 
5142     if (I.getUse().get() != Value)
5143       continue;
5144 
5145     if (I->getOpcode() == Opcode)
5146       return *I;
5147   }
5148   return nullptr;
5149 }
5150 
5151 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5152   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5153     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5154     case Intrinsic::amdgcn_if:
5155       return AMDGPUISD::IF;
5156     case Intrinsic::amdgcn_else:
5157       return AMDGPUISD::ELSE;
5158     case Intrinsic::amdgcn_loop:
5159       return AMDGPUISD::LOOP;
5160     case Intrinsic::amdgcn_end_cf:
5161       llvm_unreachable("should not occur");
5162     default:
5163       return 0;
5164     }
5165   }
5166 
5167   // break, if_break, else_break are all only used as inputs to loop, not
5168   // directly as branch conditions.
5169   return 0;
5170 }
5171 
5172 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5173   const Triple &TT = getTargetMachine().getTargetTriple();
5174   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5175           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5176          AMDGPU::shouldEmitConstantsToTextSection(TT);
5177 }
5178 
5179 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5180   // FIXME: Either avoid relying on address space here or change the default
5181   // address space for functions to avoid the explicit check.
5182   return (GV->getValueType()->isFunctionTy() ||
5183           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5184          !shouldEmitFixup(GV) &&
5185          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5186 }
5187 
5188 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5189   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5190 }
5191 
5192 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5193   if (!GV->hasExternalLinkage())
5194     return true;
5195 
5196   const auto OS = getTargetMachine().getTargetTriple().getOS();
5197   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5198 }
5199 
5200 /// This transforms the control flow intrinsics to get the branch destination as
5201 /// last parameter, also switches branch target with BR if the need arise
5202 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5203                                       SelectionDAG &DAG) const {
5204   SDLoc DL(BRCOND);
5205 
5206   SDNode *Intr = BRCOND.getOperand(1).getNode();
5207   SDValue Target = BRCOND.getOperand(2);
5208   SDNode *BR = nullptr;
5209   SDNode *SetCC = nullptr;
5210 
5211   if (Intr->getOpcode() == ISD::SETCC) {
5212     // As long as we negate the condition everything is fine
5213     SetCC = Intr;
5214     Intr = SetCC->getOperand(0).getNode();
5215 
5216   } else {
5217     // Get the target from BR if we don't negate the condition
5218     BR = findUser(BRCOND, ISD::BR);
5219     assert(BR && "brcond missing unconditional branch user");
5220     Target = BR->getOperand(1);
5221   }
5222 
5223   unsigned CFNode = isCFIntrinsic(Intr);
5224   if (CFNode == 0) {
5225     // This is a uniform branch so we don't need to legalize.
5226     return BRCOND;
5227   }
5228 
5229   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5230                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5231 
5232   assert(!SetCC ||
5233         (SetCC->getConstantOperandVal(1) == 1 &&
5234          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5235                                                              ISD::SETNE));
5236 
5237   // operands of the new intrinsic call
5238   SmallVector<SDValue, 4> Ops;
5239   if (HaveChain)
5240     Ops.push_back(BRCOND.getOperand(0));
5241 
5242   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5243   Ops.push_back(Target);
5244 
5245   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5246 
5247   // build the new intrinsic call
5248   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5249 
5250   if (!HaveChain) {
5251     SDValue Ops[] =  {
5252       SDValue(Result, 0),
5253       BRCOND.getOperand(0)
5254     };
5255 
5256     Result = DAG.getMergeValues(Ops, DL).getNode();
5257   }
5258 
5259   if (BR) {
5260     // Give the branch instruction our target
5261     SDValue Ops[] = {
5262       BR->getOperand(0),
5263       BRCOND.getOperand(2)
5264     };
5265     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5266     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5267   }
5268 
5269   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5270 
5271   // Copy the intrinsic results to registers
5272   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5273     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5274     if (!CopyToReg)
5275       continue;
5276 
5277     Chain = DAG.getCopyToReg(
5278       Chain, DL,
5279       CopyToReg->getOperand(1),
5280       SDValue(Result, i - 1),
5281       SDValue());
5282 
5283     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5284   }
5285 
5286   // Remove the old intrinsic from the chain
5287   DAG.ReplaceAllUsesOfValueWith(
5288     SDValue(Intr, Intr->getNumValues() - 1),
5289     Intr->getOperand(0));
5290 
5291   return Chain;
5292 }
5293 
5294 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5295                                           SelectionDAG &DAG) const {
5296   MVT VT = Op.getSimpleValueType();
5297   SDLoc DL(Op);
5298   // Checking the depth
5299   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5300     return DAG.getConstant(0, DL, VT);
5301 
5302   MachineFunction &MF = DAG.getMachineFunction();
5303   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5304   // Check for kernel and shader functions
5305   if (Info->isEntryFunction())
5306     return DAG.getConstant(0, DL, VT);
5307 
5308   MachineFrameInfo &MFI = MF.getFrameInfo();
5309   // There is a call to @llvm.returnaddress in this function
5310   MFI.setReturnAddressIsTaken(true);
5311 
5312   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5313   // Get the return address reg and mark it as an implicit live-in
5314   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5315 
5316   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5317 }
5318 
5319 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5320                                             SDValue Op,
5321                                             const SDLoc &DL,
5322                                             EVT VT) const {
5323   return Op.getValueType().bitsLE(VT) ?
5324       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5325     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5326                 DAG.getTargetConstant(0, DL, MVT::i32));
5327 }
5328 
5329 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5330   assert(Op.getValueType() == MVT::f16 &&
5331          "Do not know how to custom lower FP_ROUND for non-f16 type");
5332 
5333   SDValue Src = Op.getOperand(0);
5334   EVT SrcVT = Src.getValueType();
5335   if (SrcVT != MVT::f64)
5336     return Op;
5337 
5338   SDLoc DL(Op);
5339 
5340   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5341   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5342   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5343 }
5344 
5345 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5346                                                SelectionDAG &DAG) const {
5347   EVT VT = Op.getValueType();
5348   const MachineFunction &MF = DAG.getMachineFunction();
5349   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5350   bool IsIEEEMode = Info->getMode().IEEE;
5351 
5352   // FIXME: Assert during selection that this is only selected for
5353   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5354   // mode functions, but this happens to be OK since it's only done in cases
5355   // where there is known no sNaN.
5356   if (IsIEEEMode)
5357     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5358 
5359   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5360     return splitBinaryVectorOp(Op, DAG);
5361   return Op;
5362 }
5363 
5364 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5365   EVT VT = Op.getValueType();
5366   SDLoc SL(Op);
5367   SDValue LHS = Op.getOperand(0);
5368   SDValue RHS = Op.getOperand(1);
5369   bool isSigned = Op.getOpcode() == ISD::SMULO;
5370 
5371   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5372     const APInt &C = RHSC->getAPIntValue();
5373     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5374     if (C.isPowerOf2()) {
5375       // smulo(x, signed_min) is same as umulo(x, signed_min).
5376       bool UseArithShift = isSigned && !C.isMinSignedValue();
5377       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5378       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5379       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5380           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5381                       SL, VT, Result, ShiftAmt),
5382           LHS, ISD::SETNE);
5383       return DAG.getMergeValues({ Result, Overflow }, SL);
5384     }
5385   }
5386 
5387   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5388   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5389                             SL, VT, LHS, RHS);
5390 
5391   SDValue Sign = isSigned
5392     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5393                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5394     : DAG.getConstant(0, SL, VT);
5395   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5396 
5397   return DAG.getMergeValues({ Result, Overflow }, SL);
5398 }
5399 
5400 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5401   if (Op->isDivergent()) {
5402     // Select to V_MAD_[IU]64_[IU]32.
5403     return Op;
5404   }
5405   if (Subtarget->hasSMulHi()) {
5406     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5407     return SDValue();
5408   }
5409   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5410   // calculate the high part, so we might as well do the whole thing with
5411   // V_MAD_[IU]64_[IU]32.
5412   return Op;
5413 }
5414 
5415 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5416   if (!Subtarget->isTrapHandlerEnabled() ||
5417       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5418     return lowerTrapEndpgm(Op, DAG);
5419 
5420   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5421     switch (*HsaAbiVer) {
5422     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5423     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5424       return lowerTrapHsaQueuePtr(Op, DAG);
5425     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5426       return Subtarget->supportsGetDoorbellID() ?
5427           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5428     }
5429   }
5430 
5431   llvm_unreachable("Unknown trap handler");
5432 }
5433 
5434 SDValue SITargetLowering::lowerTrapEndpgm(
5435     SDValue Op, SelectionDAG &DAG) const {
5436   SDLoc SL(Op);
5437   SDValue Chain = Op.getOperand(0);
5438   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5439 }
5440 
5441 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5442     SDValue Op, SelectionDAG &DAG) const {
5443   SDLoc SL(Op);
5444   SDValue Chain = Op.getOperand(0);
5445 
5446   MachineFunction &MF = DAG.getMachineFunction();
5447   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5448   Register UserSGPR = Info->getQueuePtrUserSGPR();
5449 
5450   SDValue QueuePtr;
5451   if (UserSGPR == AMDGPU::NoRegister) {
5452     // We probably are in a function incorrectly marked with
5453     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5454     // so just use a null pointer.
5455     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5456   } else {
5457     QueuePtr = CreateLiveInRegister(
5458       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5459   }
5460 
5461   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5462   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5463                                    QueuePtr, SDValue());
5464 
5465   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5466   SDValue Ops[] = {
5467     ToReg,
5468     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5469     SGPR01,
5470     ToReg.getValue(1)
5471   };
5472   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5473 }
5474 
5475 SDValue SITargetLowering::lowerTrapHsa(
5476     SDValue Op, SelectionDAG &DAG) const {
5477   SDLoc SL(Op);
5478   SDValue Chain = Op.getOperand(0);
5479 
5480   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5481   SDValue Ops[] = {
5482     Chain,
5483     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5484   };
5485   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5486 }
5487 
5488 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5489   SDLoc SL(Op);
5490   SDValue Chain = Op.getOperand(0);
5491   MachineFunction &MF = DAG.getMachineFunction();
5492 
5493   if (!Subtarget->isTrapHandlerEnabled() ||
5494       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5495     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5496                                      "debugtrap handler not supported",
5497                                      Op.getDebugLoc(),
5498                                      DS_Warning);
5499     LLVMContext &Ctx = MF.getFunction().getContext();
5500     Ctx.diagnose(NoTrap);
5501     return Chain;
5502   }
5503 
5504   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5505   SDValue Ops[] = {
5506     Chain,
5507     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5508   };
5509   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5510 }
5511 
5512 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5513                                              SelectionDAG &DAG) const {
5514   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5515   if (Subtarget->hasApertureRegs()) {
5516     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5517         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5518         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5519     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5520         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5521         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5522     unsigned Encoding =
5523         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5524         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5525         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5526 
5527     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5528     SDValue ApertureReg = SDValue(
5529         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5530     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5531     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5532   }
5533 
5534   MachineFunction &MF = DAG.getMachineFunction();
5535   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5536   Register UserSGPR = Info->getQueuePtrUserSGPR();
5537   if (UserSGPR == AMDGPU::NoRegister) {
5538     // We probably are in a function incorrectly marked with
5539     // amdgpu-no-queue-ptr. This is undefined.
5540     return DAG.getUNDEF(MVT::i32);
5541   }
5542 
5543   SDValue QueuePtr = CreateLiveInRegister(
5544     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5545 
5546   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5547   // private_segment_aperture_base_hi.
5548   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5549 
5550   SDValue Ptr =
5551       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5552 
5553   // TODO: Use custom target PseudoSourceValue.
5554   // TODO: We should use the value from the IR intrinsic call, but it might not
5555   // be available and how do we get it?
5556   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5557   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5558                      commonAlignment(Align(64), StructOffset),
5559                      MachineMemOperand::MODereferenceable |
5560                          MachineMemOperand::MOInvariant);
5561 }
5562 
5563 /// Return true if the value is a known valid address, such that a null check is
5564 /// not necessary.
5565 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5566                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5567   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5568       isa<BasicBlockSDNode>(Val))
5569     return true;
5570 
5571   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5572     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5573 
5574   // TODO: Search through arithmetic, handle arguments and loads
5575   // marked nonnull.
5576   return false;
5577 }
5578 
5579 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5580                                              SelectionDAG &DAG) const {
5581   SDLoc SL(Op);
5582   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5583 
5584   SDValue Src = ASC->getOperand(0);
5585   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5586   unsigned SrcAS = ASC->getSrcAddressSpace();
5587 
5588   const AMDGPUTargetMachine &TM =
5589     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5590 
5591   // flat -> local/private
5592   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5593     unsigned DestAS = ASC->getDestAddressSpace();
5594 
5595     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5596         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5597       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5598 
5599       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5600         return Ptr;
5601 
5602       unsigned NullVal = TM.getNullPointerValue(DestAS);
5603       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5604       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5605 
5606       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5607                          SegmentNullPtr);
5608     }
5609   }
5610 
5611   // local/private -> flat
5612   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5613     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5614         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5615 
5616       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5617       SDValue CvtPtr =
5618           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5619       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5620 
5621       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5622         return CvtPtr;
5623 
5624       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5625       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5626 
5627       SDValue NonNull
5628         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5629 
5630       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5631                          FlatNullPtr);
5632     }
5633   }
5634 
5635   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5636       Src.getValueType() == MVT::i64)
5637     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5638 
5639   // global <-> flat are no-ops and never emitted.
5640 
5641   const MachineFunction &MF = DAG.getMachineFunction();
5642   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5643     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5644   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5645 
5646   return DAG.getUNDEF(ASC->getValueType(0));
5647 }
5648 
5649 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5650 // the small vector and inserting them into the big vector. That is better than
5651 // the default expansion of doing it via a stack slot. Even though the use of
5652 // the stack slot would be optimized away afterwards, the stack slot itself
5653 // remains.
5654 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5655                                                 SelectionDAG &DAG) const {
5656   SDValue Vec = Op.getOperand(0);
5657   SDValue Ins = Op.getOperand(1);
5658   SDValue Idx = Op.getOperand(2);
5659   EVT VecVT = Vec.getValueType();
5660   EVT InsVT = Ins.getValueType();
5661   EVT EltVT = VecVT.getVectorElementType();
5662   unsigned InsNumElts = InsVT.getVectorNumElements();
5663   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5664   SDLoc SL(Op);
5665 
5666   for (unsigned I = 0; I != InsNumElts; ++I) {
5667     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5668                               DAG.getConstant(I, SL, MVT::i32));
5669     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5670                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5671   }
5672   return Vec;
5673 }
5674 
5675 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5676                                                  SelectionDAG &DAG) const {
5677   SDValue Vec = Op.getOperand(0);
5678   SDValue InsVal = Op.getOperand(1);
5679   SDValue Idx = Op.getOperand(2);
5680   EVT VecVT = Vec.getValueType();
5681   EVT EltVT = VecVT.getVectorElementType();
5682   unsigned VecSize = VecVT.getSizeInBits();
5683   unsigned EltSize = EltVT.getSizeInBits();
5684 
5685 
5686   assert(VecSize <= 64);
5687 
5688   unsigned NumElts = VecVT.getVectorNumElements();
5689   SDLoc SL(Op);
5690   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5691 
5692   if (NumElts == 4 && EltSize == 16 && KIdx) {
5693     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5694 
5695     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5696                                  DAG.getConstant(0, SL, MVT::i32));
5697     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5698                                  DAG.getConstant(1, SL, MVT::i32));
5699 
5700     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5701     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5702 
5703     unsigned Idx = KIdx->getZExtValue();
5704     bool InsertLo = Idx < 2;
5705     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5706       InsertLo ? LoVec : HiVec,
5707       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5708       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5709 
5710     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5711 
5712     SDValue Concat = InsertLo ?
5713       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5714       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5715 
5716     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5717   }
5718 
5719   if (isa<ConstantSDNode>(Idx))
5720     return SDValue();
5721 
5722   MVT IntVT = MVT::getIntegerVT(VecSize);
5723 
5724   // Avoid stack access for dynamic indexing.
5725   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5726 
5727   // Create a congruent vector with the target value in each element so that
5728   // the required element can be masked and ORed into the target vector.
5729   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5730                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5731 
5732   assert(isPowerOf2_32(EltSize));
5733   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5734 
5735   // Convert vector index to bit-index.
5736   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5737 
5738   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5739   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5740                             DAG.getConstant(0xffff, SL, IntVT),
5741                             ScaledIdx);
5742 
5743   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5744   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5745                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5746 
5747   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5748   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5749 }
5750 
5751 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5752                                                   SelectionDAG &DAG) const {
5753   SDLoc SL(Op);
5754 
5755   EVT ResultVT = Op.getValueType();
5756   SDValue Vec = Op.getOperand(0);
5757   SDValue Idx = Op.getOperand(1);
5758   EVT VecVT = Vec.getValueType();
5759   unsigned VecSize = VecVT.getSizeInBits();
5760   EVT EltVT = VecVT.getVectorElementType();
5761 
5762   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5763 
5764   // Make sure we do any optimizations that will make it easier to fold
5765   // source modifiers before obscuring it with bit operations.
5766 
5767   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5768   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5769     return Combined;
5770 
5771   if (VecSize == 128) {
5772     SDValue Lo, Hi;
5773     EVT LoVT, HiVT;
5774     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5775     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5776     Lo =
5777         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5778                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5779     Hi =
5780         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5781                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5782     EVT IdxVT = Idx.getValueType();
5783     unsigned NElem = VecVT.getVectorNumElements();
5784     assert(isPowerOf2_32(NElem));
5785     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5786     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5787     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5788     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5789   }
5790 
5791   assert(VecSize <= 64);
5792 
5793   unsigned EltSize = EltVT.getSizeInBits();
5794   assert(isPowerOf2_32(EltSize));
5795 
5796   MVT IntVT = MVT::getIntegerVT(VecSize);
5797   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5798 
5799   // Convert vector index to bit-index (* EltSize)
5800   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5801 
5802   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5803   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5804 
5805   if (ResultVT == MVT::f16) {
5806     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5807     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5808   }
5809 
5810   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5811 }
5812 
5813 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5814   assert(Elt % 2 == 0);
5815   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5816 }
5817 
5818 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5819                                               SelectionDAG &DAG) const {
5820   SDLoc SL(Op);
5821   EVT ResultVT = Op.getValueType();
5822   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5823 
5824   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5825   EVT EltVT = PackVT.getVectorElementType();
5826   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5827 
5828   // vector_shuffle <0,1,6,7> lhs, rhs
5829   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5830   //
5831   // vector_shuffle <6,7,2,3> lhs, rhs
5832   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5833   //
5834   // vector_shuffle <6,7,0,1> lhs, rhs
5835   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5836 
5837   // Avoid scalarizing when both halves are reading from consecutive elements.
5838   SmallVector<SDValue, 4> Pieces;
5839   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5840     if (elementPairIsContiguous(SVN->getMask(), I)) {
5841       const int Idx = SVN->getMaskElt(I);
5842       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5843       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5844       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5845                                     PackVT, SVN->getOperand(VecIdx),
5846                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5847       Pieces.push_back(SubVec);
5848     } else {
5849       const int Idx0 = SVN->getMaskElt(I);
5850       const int Idx1 = SVN->getMaskElt(I + 1);
5851       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5852       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5853       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5854       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5855 
5856       SDValue Vec0 = SVN->getOperand(VecIdx0);
5857       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5858                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5859 
5860       SDValue Vec1 = SVN->getOperand(VecIdx1);
5861       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5862                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5863       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5864     }
5865   }
5866 
5867   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5868 }
5869 
5870 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5871                                             SelectionDAG &DAG) const {
5872   SDLoc SL(Op);
5873   EVT VT = Op.getValueType();
5874 
5875   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5876       VT == MVT::v8i16 || VT == MVT::v8f16) {
5877     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5878                                   VT.getVectorNumElements() / 2);
5879     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5880 
5881     // Turn into pair of packed build_vectors.
5882     // TODO: Special case for constants that can be materialized with s_mov_b64.
5883     SmallVector<SDValue, 4> LoOps, HiOps;
5884     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5885       LoOps.push_back(Op.getOperand(I));
5886       HiOps.push_back(Op.getOperand(I + E));
5887     }
5888     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5889     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5890 
5891     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5892     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5893 
5894     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5895                                        { CastLo, CastHi });
5896     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5897   }
5898 
5899   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5900   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5901 
5902   SDValue Lo = Op.getOperand(0);
5903   SDValue Hi = Op.getOperand(1);
5904 
5905   // Avoid adding defined bits with the zero_extend.
5906   if (Hi.isUndef()) {
5907     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5908     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5909     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5910   }
5911 
5912   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5913   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5914 
5915   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5916                               DAG.getConstant(16, SL, MVT::i32));
5917   if (Lo.isUndef())
5918     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5919 
5920   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5921   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5922 
5923   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5924   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5925 }
5926 
5927 bool
5928 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5929   // We can fold offsets for anything that doesn't require a GOT relocation.
5930   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5931           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5932           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5933          !shouldEmitGOTReloc(GA->getGlobal());
5934 }
5935 
5936 static SDValue
5937 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5938                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5939                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5940   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5941   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5942   // lowered to the following code sequence:
5943   //
5944   // For constant address space:
5945   //   s_getpc_b64 s[0:1]
5946   //   s_add_u32 s0, s0, $symbol
5947   //   s_addc_u32 s1, s1, 0
5948   //
5949   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5950   //   a fixup or relocation is emitted to replace $symbol with a literal
5951   //   constant, which is a pc-relative offset from the encoding of the $symbol
5952   //   operand to the global variable.
5953   //
5954   // For global address space:
5955   //   s_getpc_b64 s[0:1]
5956   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5957   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5958   //
5959   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5960   //   fixups or relocations are emitted to replace $symbol@*@lo and
5961   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5962   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5963   //   operand to the global variable.
5964   //
5965   // What we want here is an offset from the value returned by s_getpc
5966   // (which is the address of the s_add_u32 instruction) to the global
5967   // variable, but since the encoding of $symbol starts 4 bytes after the start
5968   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5969   // small. This requires us to add 4 to the global variable offset in order to
5970   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5971   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5972   // instruction.
5973   SDValue PtrLo =
5974       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5975   SDValue PtrHi;
5976   if (GAFlags == SIInstrInfo::MO_NONE) {
5977     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5978   } else {
5979     PtrHi =
5980         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5981   }
5982   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5983 }
5984 
5985 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5986                                              SDValue Op,
5987                                              SelectionDAG &DAG) const {
5988   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5989   SDLoc DL(GSD);
5990   EVT PtrVT = Op.getValueType();
5991 
5992   const GlobalValue *GV = GSD->getGlobal();
5993   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5994        shouldUseLDSConstAddress(GV)) ||
5995       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5996       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5997     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5998         GV->hasExternalLinkage()) {
5999       Type *Ty = GV->getValueType();
6000       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6001       // zero-sized type in other languages to declare the dynamic shared
6002       // memory which size is not known at the compile time. They will be
6003       // allocated by the runtime and placed directly after the static
6004       // allocated ones. They all share the same offset.
6005       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6006         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6007         // Adjust alignment for that dynamic shared memory array.
6008         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6009         return SDValue(
6010             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6011       }
6012     }
6013     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6014   }
6015 
6016   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6017     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6018                                             SIInstrInfo::MO_ABS32_LO);
6019     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6020   }
6021 
6022   if (shouldEmitFixup(GV))
6023     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6024   else if (shouldEmitPCReloc(GV))
6025     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6026                                    SIInstrInfo::MO_REL32);
6027 
6028   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6029                                             SIInstrInfo::MO_GOTPCREL32);
6030 
6031   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6032   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6033   const DataLayout &DataLayout = DAG.getDataLayout();
6034   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6035   MachinePointerInfo PtrInfo
6036     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6037 
6038   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6039                      MachineMemOperand::MODereferenceable |
6040                          MachineMemOperand::MOInvariant);
6041 }
6042 
6043 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6044                                    const SDLoc &DL, SDValue V) const {
6045   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6046   // the destination register.
6047   //
6048   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6049   // so we will end up with redundant moves to m0.
6050   //
6051   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6052 
6053   // A Null SDValue creates a glue result.
6054   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6055                                   V, Chain);
6056   return SDValue(M0, 0);
6057 }
6058 
6059 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6060                                                  SDValue Op,
6061                                                  MVT VT,
6062                                                  unsigned Offset) const {
6063   SDLoc SL(Op);
6064   SDValue Param = lowerKernargMemParameter(
6065       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6066   // The local size values will have the hi 16-bits as zero.
6067   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6068                      DAG.getValueType(VT));
6069 }
6070 
6071 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6072                                         EVT VT) {
6073   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6074                                       "non-hsa intrinsic with hsa target",
6075                                       DL.getDebugLoc());
6076   DAG.getContext()->diagnose(BadIntrin);
6077   return DAG.getUNDEF(VT);
6078 }
6079 
6080 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6081                                          EVT VT) {
6082   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6083                                       "intrinsic not supported on subtarget",
6084                                       DL.getDebugLoc());
6085   DAG.getContext()->diagnose(BadIntrin);
6086   return DAG.getUNDEF(VT);
6087 }
6088 
6089 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6090                                     ArrayRef<SDValue> Elts) {
6091   assert(!Elts.empty());
6092   MVT Type;
6093   unsigned NumElts = Elts.size();
6094 
6095   if (NumElts <= 8) {
6096     Type = MVT::getVectorVT(MVT::f32, NumElts);
6097   } else {
6098     assert(Elts.size() <= 16);
6099     Type = MVT::v16f32;
6100     NumElts = 16;
6101   }
6102 
6103   SmallVector<SDValue, 16> VecElts(NumElts);
6104   for (unsigned i = 0; i < Elts.size(); ++i) {
6105     SDValue Elt = Elts[i];
6106     if (Elt.getValueType() != MVT::f32)
6107       Elt = DAG.getBitcast(MVT::f32, Elt);
6108     VecElts[i] = Elt;
6109   }
6110   for (unsigned i = Elts.size(); i < NumElts; ++i)
6111     VecElts[i] = DAG.getUNDEF(MVT::f32);
6112 
6113   if (NumElts == 1)
6114     return VecElts[0];
6115   return DAG.getBuildVector(Type, DL, VecElts);
6116 }
6117 
6118 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6119                               SDValue Src, int ExtraElts) {
6120   EVT SrcVT = Src.getValueType();
6121 
6122   SmallVector<SDValue, 8> Elts;
6123 
6124   if (SrcVT.isVector())
6125     DAG.ExtractVectorElements(Src, Elts);
6126   else
6127     Elts.push_back(Src);
6128 
6129   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6130   while (ExtraElts--)
6131     Elts.push_back(Undef);
6132 
6133   return DAG.getBuildVector(CastVT, DL, Elts);
6134 }
6135 
6136 // Re-construct the required return value for a image load intrinsic.
6137 // This is more complicated due to the optional use TexFailCtrl which means the required
6138 // return type is an aggregate
6139 static SDValue constructRetValue(SelectionDAG &DAG,
6140                                  MachineSDNode *Result,
6141                                  ArrayRef<EVT> ResultTypes,
6142                                  bool IsTexFail, bool Unpacked, bool IsD16,
6143                                  int DMaskPop, int NumVDataDwords,
6144                                  const SDLoc &DL) {
6145   // Determine the required return type. This is the same regardless of IsTexFail flag
6146   EVT ReqRetVT = ResultTypes[0];
6147   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6148   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6149     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6150 
6151   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6152     DMaskPop : (DMaskPop + 1) / 2;
6153 
6154   MVT DataDwordVT = NumDataDwords == 1 ?
6155     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6156 
6157   MVT MaskPopVT = MaskPopDwords == 1 ?
6158     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6159 
6160   SDValue Data(Result, 0);
6161   SDValue TexFail;
6162 
6163   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6164     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6165     if (MaskPopVT.isVector()) {
6166       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6167                          SDValue(Result, 0), ZeroIdx);
6168     } else {
6169       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6170                          SDValue(Result, 0), ZeroIdx);
6171     }
6172   }
6173 
6174   if (DataDwordVT.isVector())
6175     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6176                           NumDataDwords - MaskPopDwords);
6177 
6178   if (IsD16)
6179     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6180 
6181   EVT LegalReqRetVT = ReqRetVT;
6182   if (!ReqRetVT.isVector()) {
6183     if (!Data.getValueType().isInteger())
6184       Data = DAG.getNode(ISD::BITCAST, DL,
6185                          Data.getValueType().changeTypeToInteger(), Data);
6186     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6187   } else {
6188     // We need to widen the return vector to a legal type
6189     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6190         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6191       LegalReqRetVT =
6192           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6193                            ReqRetVT.getVectorNumElements() + 1);
6194     }
6195   }
6196   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6197 
6198   if (IsTexFail) {
6199     TexFail =
6200         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6201                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6202 
6203     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6204   }
6205 
6206   if (Result->getNumValues() == 1)
6207     return Data;
6208 
6209   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6210 }
6211 
6212 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6213                          SDValue *LWE, bool &IsTexFail) {
6214   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6215 
6216   uint64_t Value = TexFailCtrlConst->getZExtValue();
6217   if (Value) {
6218     IsTexFail = true;
6219   }
6220 
6221   SDLoc DL(TexFailCtrlConst);
6222   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6223   Value &= ~(uint64_t)0x1;
6224   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6225   Value &= ~(uint64_t)0x2;
6226 
6227   return Value == 0;
6228 }
6229 
6230 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6231                                       MVT PackVectorVT,
6232                                       SmallVectorImpl<SDValue> &PackedAddrs,
6233                                       unsigned DimIdx, unsigned EndIdx,
6234                                       unsigned NumGradients) {
6235   SDLoc DL(Op);
6236   for (unsigned I = DimIdx; I < EndIdx; I++) {
6237     SDValue Addr = Op.getOperand(I);
6238 
6239     // Gradients are packed with undef for each coordinate.
6240     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6241     // 1D: undef,dx/dh; undef,dx/dv
6242     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6243     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6244     if (((I + 1) >= EndIdx) ||
6245         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6246                                          I == DimIdx + NumGradients - 1))) {
6247       if (Addr.getValueType() != MVT::i16)
6248         Addr = DAG.getBitcast(MVT::i16, Addr);
6249       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6250     } else {
6251       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6252       I++;
6253     }
6254     Addr = DAG.getBitcast(MVT::f32, Addr);
6255     PackedAddrs.push_back(Addr);
6256   }
6257 }
6258 
6259 SDValue SITargetLowering::lowerImage(SDValue Op,
6260                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6261                                      SelectionDAG &DAG, bool WithChain) const {
6262   SDLoc DL(Op);
6263   MachineFunction &MF = DAG.getMachineFunction();
6264   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6265   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6266       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6267   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6268   unsigned IntrOpcode = Intr->BaseOpcode;
6269   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6270 
6271   SmallVector<EVT, 3> ResultTypes(Op->values());
6272   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6273   bool IsD16 = false;
6274   bool IsG16 = false;
6275   bool IsA16 = false;
6276   SDValue VData;
6277   int NumVDataDwords;
6278   bool AdjustRetType = false;
6279 
6280   // Offset of intrinsic arguments
6281   const unsigned ArgOffset = WithChain ? 2 : 1;
6282 
6283   unsigned DMask;
6284   unsigned DMaskLanes = 0;
6285 
6286   if (BaseOpcode->Atomic) {
6287     VData = Op.getOperand(2);
6288 
6289     bool Is64Bit = VData.getValueType() == MVT::i64;
6290     if (BaseOpcode->AtomicX2) {
6291       SDValue VData2 = Op.getOperand(3);
6292       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6293                                  {VData, VData2});
6294       if (Is64Bit)
6295         VData = DAG.getBitcast(MVT::v4i32, VData);
6296 
6297       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6298       DMask = Is64Bit ? 0xf : 0x3;
6299       NumVDataDwords = Is64Bit ? 4 : 2;
6300     } else {
6301       DMask = Is64Bit ? 0x3 : 0x1;
6302       NumVDataDwords = Is64Bit ? 2 : 1;
6303     }
6304   } else {
6305     auto *DMaskConst =
6306         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6307     DMask = DMaskConst->getZExtValue();
6308     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6309 
6310     if (BaseOpcode->Store) {
6311       VData = Op.getOperand(2);
6312 
6313       MVT StoreVT = VData.getSimpleValueType();
6314       if (StoreVT.getScalarType() == MVT::f16) {
6315         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6316           return Op; // D16 is unsupported for this instruction
6317 
6318         IsD16 = true;
6319         VData = handleD16VData(VData, DAG, true);
6320       }
6321 
6322       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6323     } else {
6324       // Work out the num dwords based on the dmask popcount and underlying type
6325       // and whether packing is supported.
6326       MVT LoadVT = ResultTypes[0].getSimpleVT();
6327       if (LoadVT.getScalarType() == MVT::f16) {
6328         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6329           return Op; // D16 is unsupported for this instruction
6330 
6331         IsD16 = true;
6332       }
6333 
6334       // Confirm that the return type is large enough for the dmask specified
6335       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6336           (!LoadVT.isVector() && DMaskLanes > 1))
6337           return Op;
6338 
6339       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6340       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6341       // instructions.
6342       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6343           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6344         NumVDataDwords = (DMaskLanes + 1) / 2;
6345       else
6346         NumVDataDwords = DMaskLanes;
6347 
6348       AdjustRetType = true;
6349     }
6350   }
6351 
6352   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6353   SmallVector<SDValue, 4> VAddrs;
6354 
6355   // Check for 16 bit addresses or derivatives and pack if true.
6356   MVT VAddrVT =
6357       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6358   MVT VAddrScalarVT = VAddrVT.getScalarType();
6359   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6360   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6361 
6362   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6363   VAddrScalarVT = VAddrVT.getScalarType();
6364   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6365   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6366 
6367   // Push back extra arguments.
6368   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6369     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6370       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6371       // Special handling of bias when A16 is on. Bias is of type half but
6372       // occupies full 32-bit.
6373       SDValue Bias = DAG.getBuildVector(
6374           MVT::v2f16, DL,
6375           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6376       VAddrs.push_back(Bias);
6377     } else {
6378       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6379              "Bias needs to be converted to 16 bit in A16 mode");
6380       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6381     }
6382   }
6383 
6384   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6385     // 16 bit gradients are supported, but are tied to the A16 control
6386     // so both gradients and addresses must be 16 bit
6387     LLVM_DEBUG(
6388         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6389                   "require 16 bit args for both gradients and addresses");
6390     return Op;
6391   }
6392 
6393   if (IsA16) {
6394     if (!ST->hasA16()) {
6395       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6396                            "support 16 bit addresses\n");
6397       return Op;
6398     }
6399   }
6400 
6401   // We've dealt with incorrect input so we know that if IsA16, IsG16
6402   // are set then we have to compress/pack operands (either address,
6403   // gradient or both)
6404   // In the case where a16 and gradients are tied (no G16 support) then we
6405   // have already verified that both IsA16 and IsG16 are true
6406   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6407     // Activate g16
6408     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6409         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6410     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6411   }
6412 
6413   // Add gradients (packed or unpacked)
6414   if (IsG16) {
6415     // Pack the gradients
6416     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6417     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6418                               ArgOffset + Intr->GradientStart,
6419                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6420   } else {
6421     for (unsigned I = ArgOffset + Intr->GradientStart;
6422          I < ArgOffset + Intr->CoordStart; I++)
6423       VAddrs.push_back(Op.getOperand(I));
6424   }
6425 
6426   // Add addresses (packed or unpacked)
6427   if (IsA16) {
6428     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6429                               ArgOffset + Intr->CoordStart, VAddrEnd,
6430                               0 /* No gradients */);
6431   } else {
6432     // Add uncompressed address
6433     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6434       VAddrs.push_back(Op.getOperand(I));
6435   }
6436 
6437   // If the register allocator cannot place the address registers contiguously
6438   // without introducing moves, then using the non-sequential address encoding
6439   // is always preferable, since it saves VALU instructions and is usually a
6440   // wash in terms of code size or even better.
6441   //
6442   // However, we currently have no way of hinting to the register allocator that
6443   // MIMG addresses should be placed contiguously when it is possible to do so,
6444   // so force non-NSA for the common 2-address case as a heuristic.
6445   //
6446   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6447   // allocation when possible.
6448   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6449                 VAddrs.size() >= 3 &&
6450                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6451   SDValue VAddr;
6452   if (!UseNSA)
6453     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6454 
6455   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6456   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6457   SDValue Unorm;
6458   if (!BaseOpcode->Sampler) {
6459     Unorm = True;
6460   } else {
6461     auto UnormConst =
6462         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6463 
6464     Unorm = UnormConst->getZExtValue() ? True : False;
6465   }
6466 
6467   SDValue TFE;
6468   SDValue LWE;
6469   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6470   bool IsTexFail = false;
6471   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6472     return Op;
6473 
6474   if (IsTexFail) {
6475     if (!DMaskLanes) {
6476       // Expecting to get an error flag since TFC is on - and dmask is 0
6477       // Force dmask to be at least 1 otherwise the instruction will fail
6478       DMask = 0x1;
6479       DMaskLanes = 1;
6480       NumVDataDwords = 1;
6481     }
6482     NumVDataDwords += 1;
6483     AdjustRetType = true;
6484   }
6485 
6486   // Has something earlier tagged that the return type needs adjusting
6487   // This happens if the instruction is a load or has set TexFailCtrl flags
6488   if (AdjustRetType) {
6489     // NumVDataDwords reflects the true number of dwords required in the return type
6490     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6491       // This is a no-op load. This can be eliminated
6492       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6493       if (isa<MemSDNode>(Op))
6494         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6495       return Undef;
6496     }
6497 
6498     EVT NewVT = NumVDataDwords > 1 ?
6499                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6500                 : MVT::i32;
6501 
6502     ResultTypes[0] = NewVT;
6503     if (ResultTypes.size() == 3) {
6504       // Original result was aggregate type used for TexFailCtrl results
6505       // The actual instruction returns as a vector type which has now been
6506       // created. Remove the aggregate result.
6507       ResultTypes.erase(&ResultTypes[1]);
6508     }
6509   }
6510 
6511   unsigned CPol = cast<ConstantSDNode>(
6512       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6513   if (BaseOpcode->Atomic)
6514     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6515   if (CPol & ~AMDGPU::CPol::ALL)
6516     return Op;
6517 
6518   SmallVector<SDValue, 26> Ops;
6519   if (BaseOpcode->Store || BaseOpcode->Atomic)
6520     Ops.push_back(VData); // vdata
6521   if (UseNSA)
6522     append_range(Ops, VAddrs);
6523   else
6524     Ops.push_back(VAddr);
6525   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6526   if (BaseOpcode->Sampler)
6527     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6528   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6529   if (IsGFX10Plus)
6530     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6531   Ops.push_back(Unorm);
6532   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6533   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6534                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6535   if (IsGFX10Plus)
6536     Ops.push_back(IsA16 ? True : False);
6537   if (!Subtarget->hasGFX90AInsts()) {
6538     Ops.push_back(TFE); //tfe
6539   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6540     report_fatal_error("TFE is not supported on this GPU");
6541   }
6542   Ops.push_back(LWE); // lwe
6543   if (!IsGFX10Plus)
6544     Ops.push_back(DimInfo->DA ? True : False);
6545   if (BaseOpcode->HasD16)
6546     Ops.push_back(IsD16 ? True : False);
6547   if (isa<MemSDNode>(Op))
6548     Ops.push_back(Op.getOperand(0)); // chain
6549 
6550   int NumVAddrDwords =
6551       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6552   int Opcode = -1;
6553 
6554   if (IsGFX10Plus) {
6555     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6556                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6557                                           : AMDGPU::MIMGEncGfx10Default,
6558                                    NumVDataDwords, NumVAddrDwords);
6559   } else {
6560     if (Subtarget->hasGFX90AInsts()) {
6561       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6562                                      NumVDataDwords, NumVAddrDwords);
6563       if (Opcode == -1)
6564         report_fatal_error(
6565             "requested image instruction is not supported on this GPU");
6566     }
6567     if (Opcode == -1 &&
6568         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6569       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6570                                      NumVDataDwords, NumVAddrDwords);
6571     if (Opcode == -1)
6572       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6573                                      NumVDataDwords, NumVAddrDwords);
6574   }
6575   assert(Opcode != -1);
6576 
6577   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6578   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6579     MachineMemOperand *MemRef = MemOp->getMemOperand();
6580     DAG.setNodeMemRefs(NewNode, {MemRef});
6581   }
6582 
6583   if (BaseOpcode->AtomicX2) {
6584     SmallVector<SDValue, 1> Elt;
6585     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6586     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6587   }
6588   if (BaseOpcode->Store)
6589     return SDValue(NewNode, 0);
6590   return constructRetValue(DAG, NewNode,
6591                            OrigResultTypes, IsTexFail,
6592                            Subtarget->hasUnpackedD16VMem(), IsD16,
6593                            DMaskLanes, NumVDataDwords, DL);
6594 }
6595 
6596 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6597                                        SDValue Offset, SDValue CachePolicy,
6598                                        SelectionDAG &DAG) const {
6599   MachineFunction &MF = DAG.getMachineFunction();
6600 
6601   const DataLayout &DataLayout = DAG.getDataLayout();
6602   Align Alignment =
6603       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6604 
6605   MachineMemOperand *MMO = MF.getMachineMemOperand(
6606       MachinePointerInfo(),
6607       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6608           MachineMemOperand::MOInvariant,
6609       VT.getStoreSize(), Alignment);
6610 
6611   if (!Offset->isDivergent()) {
6612     SDValue Ops[] = {
6613         Rsrc,
6614         Offset, // Offset
6615         CachePolicy
6616     };
6617 
6618     // Widen vec3 load to vec4.
6619     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6620       EVT WidenedVT =
6621           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6622       auto WidenedOp = DAG.getMemIntrinsicNode(
6623           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6624           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6625       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6626                                    DAG.getVectorIdxConstant(0, DL));
6627       return Subvector;
6628     }
6629 
6630     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6631                                    DAG.getVTList(VT), Ops, VT, MMO);
6632   }
6633 
6634   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6635   // assume that the buffer is unswizzled.
6636   SmallVector<SDValue, 4> Loads;
6637   unsigned NumLoads = 1;
6638   MVT LoadVT = VT.getSimpleVT();
6639   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6640   assert((LoadVT.getScalarType() == MVT::i32 ||
6641           LoadVT.getScalarType() == MVT::f32));
6642 
6643   if (NumElts == 8 || NumElts == 16) {
6644     NumLoads = NumElts / 4;
6645     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6646   }
6647 
6648   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6649   SDValue Ops[] = {
6650       DAG.getEntryNode(),                               // Chain
6651       Rsrc,                                             // rsrc
6652       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6653       {},                                               // voffset
6654       {},                                               // soffset
6655       {},                                               // offset
6656       CachePolicy,                                      // cachepolicy
6657       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6658   };
6659 
6660   // Use the alignment to ensure that the required offsets will fit into the
6661   // immediate offsets.
6662   setBufferOffsets(Offset, DAG, &Ops[3],
6663                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6664 
6665   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6666   for (unsigned i = 0; i < NumLoads; ++i) {
6667     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6668     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6669                                         LoadVT, MMO, DAG));
6670   }
6671 
6672   if (NumElts == 8 || NumElts == 16)
6673     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6674 
6675   return Loads[0];
6676 }
6677 
6678 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6679                                                   SelectionDAG &DAG) const {
6680   MachineFunction &MF = DAG.getMachineFunction();
6681   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6682 
6683   EVT VT = Op.getValueType();
6684   SDLoc DL(Op);
6685   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6686 
6687   // TODO: Should this propagate fast-math-flags?
6688 
6689   switch (IntrinsicID) {
6690   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6691     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6692       return emitNonHSAIntrinsicError(DAG, DL, VT);
6693     return getPreloadedValue(DAG, *MFI, VT,
6694                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6695   }
6696   case Intrinsic::amdgcn_dispatch_ptr:
6697   case Intrinsic::amdgcn_queue_ptr: {
6698     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6699       DiagnosticInfoUnsupported BadIntrin(
6700           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6701           DL.getDebugLoc());
6702       DAG.getContext()->diagnose(BadIntrin);
6703       return DAG.getUNDEF(VT);
6704     }
6705 
6706     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6707       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6708     return getPreloadedValue(DAG, *MFI, VT, RegID);
6709   }
6710   case Intrinsic::amdgcn_implicitarg_ptr: {
6711     if (MFI->isEntryFunction())
6712       return getImplicitArgPtr(DAG, DL);
6713     return getPreloadedValue(DAG, *MFI, VT,
6714                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6715   }
6716   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6717     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6718       // This only makes sense to call in a kernel, so just lower to null.
6719       return DAG.getConstant(0, DL, VT);
6720     }
6721 
6722     return getPreloadedValue(DAG, *MFI, VT,
6723                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6724   }
6725   case Intrinsic::amdgcn_dispatch_id: {
6726     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6727   }
6728   case Intrinsic::amdgcn_rcp:
6729     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6730   case Intrinsic::amdgcn_rsq:
6731     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6732   case Intrinsic::amdgcn_rsq_legacy:
6733     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6734       return emitRemovedIntrinsicError(DAG, DL, VT);
6735     return SDValue();
6736   case Intrinsic::amdgcn_rcp_legacy:
6737     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6738       return emitRemovedIntrinsicError(DAG, DL, VT);
6739     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6740   case Intrinsic::amdgcn_rsq_clamp: {
6741     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6742       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6743 
6744     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6745     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6746     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6747 
6748     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6749     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6750                               DAG.getConstantFP(Max, DL, VT));
6751     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6752                        DAG.getConstantFP(Min, DL, VT));
6753   }
6754   case Intrinsic::r600_read_ngroups_x:
6755     if (Subtarget->isAmdHsaOS())
6756       return emitNonHSAIntrinsicError(DAG, DL, VT);
6757 
6758     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6759                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6760                                     false);
6761   case Intrinsic::r600_read_ngroups_y:
6762     if (Subtarget->isAmdHsaOS())
6763       return emitNonHSAIntrinsicError(DAG, DL, VT);
6764 
6765     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6766                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6767                                     false);
6768   case Intrinsic::r600_read_ngroups_z:
6769     if (Subtarget->isAmdHsaOS())
6770       return emitNonHSAIntrinsicError(DAG, DL, VT);
6771 
6772     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6773                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6774                                     false);
6775   case Intrinsic::r600_read_global_size_x:
6776     if (Subtarget->isAmdHsaOS())
6777       return emitNonHSAIntrinsicError(DAG, DL, VT);
6778 
6779     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6780                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6781                                     Align(4), false);
6782   case Intrinsic::r600_read_global_size_y:
6783     if (Subtarget->isAmdHsaOS())
6784       return emitNonHSAIntrinsicError(DAG, DL, VT);
6785 
6786     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6787                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6788                                     Align(4), false);
6789   case Intrinsic::r600_read_global_size_z:
6790     if (Subtarget->isAmdHsaOS())
6791       return emitNonHSAIntrinsicError(DAG, DL, VT);
6792 
6793     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6794                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6795                                     Align(4), false);
6796   case Intrinsic::r600_read_local_size_x:
6797     if (Subtarget->isAmdHsaOS())
6798       return emitNonHSAIntrinsicError(DAG, DL, VT);
6799 
6800     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6801                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6802   case Intrinsic::r600_read_local_size_y:
6803     if (Subtarget->isAmdHsaOS())
6804       return emitNonHSAIntrinsicError(DAG, DL, VT);
6805 
6806     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6807                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6808   case Intrinsic::r600_read_local_size_z:
6809     if (Subtarget->isAmdHsaOS())
6810       return emitNonHSAIntrinsicError(DAG, DL, VT);
6811 
6812     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6813                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6814   case Intrinsic::amdgcn_workgroup_id_x:
6815     return getPreloadedValue(DAG, *MFI, VT,
6816                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6817   case Intrinsic::amdgcn_workgroup_id_y:
6818     return getPreloadedValue(DAG, *MFI, VT,
6819                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6820   case Intrinsic::amdgcn_workgroup_id_z:
6821     return getPreloadedValue(DAG, *MFI, VT,
6822                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6823   case Intrinsic::amdgcn_workitem_id_x:
6824     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6825       return DAG.getConstant(0, DL, MVT::i32);
6826 
6827     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6828                           SDLoc(DAG.getEntryNode()),
6829                           MFI->getArgInfo().WorkItemIDX);
6830   case Intrinsic::amdgcn_workitem_id_y:
6831     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6832       return DAG.getConstant(0, DL, MVT::i32);
6833 
6834     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6835                           SDLoc(DAG.getEntryNode()),
6836                           MFI->getArgInfo().WorkItemIDY);
6837   case Intrinsic::amdgcn_workitem_id_z:
6838     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6839       return DAG.getConstant(0, DL, MVT::i32);
6840 
6841     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6842                           SDLoc(DAG.getEntryNode()),
6843                           MFI->getArgInfo().WorkItemIDZ);
6844   case Intrinsic::amdgcn_wavefrontsize:
6845     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6846                            SDLoc(Op), MVT::i32);
6847   case Intrinsic::amdgcn_s_buffer_load: {
6848     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6849     if (CPol & ~AMDGPU::CPol::ALL)
6850       return Op;
6851     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6852                         DAG);
6853   }
6854   case Intrinsic::amdgcn_fdiv_fast:
6855     return lowerFDIV_FAST(Op, DAG);
6856   case Intrinsic::amdgcn_sin:
6857     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6858 
6859   case Intrinsic::amdgcn_cos:
6860     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6861 
6862   case Intrinsic::amdgcn_mul_u24:
6863     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6864   case Intrinsic::amdgcn_mul_i24:
6865     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6866 
6867   case Intrinsic::amdgcn_log_clamp: {
6868     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6869       return SDValue();
6870 
6871     return emitRemovedIntrinsicError(DAG, DL, VT);
6872   }
6873   case Intrinsic::amdgcn_ldexp:
6874     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6875                        Op.getOperand(1), Op.getOperand(2));
6876 
6877   case Intrinsic::amdgcn_fract:
6878     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6879 
6880   case Intrinsic::amdgcn_class:
6881     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6882                        Op.getOperand(1), Op.getOperand(2));
6883   case Intrinsic::amdgcn_div_fmas:
6884     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6885                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6886                        Op.getOperand(4));
6887 
6888   case Intrinsic::amdgcn_div_fixup:
6889     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6890                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6891 
6892   case Intrinsic::amdgcn_div_scale: {
6893     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6894 
6895     // Translate to the operands expected by the machine instruction. The
6896     // first parameter must be the same as the first instruction.
6897     SDValue Numerator = Op.getOperand(1);
6898     SDValue Denominator = Op.getOperand(2);
6899 
6900     // Note this order is opposite of the machine instruction's operations,
6901     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6902     // intrinsic has the numerator as the first operand to match a normal
6903     // division operation.
6904 
6905     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6906 
6907     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6908                        Denominator, Numerator);
6909   }
6910   case Intrinsic::amdgcn_icmp: {
6911     // There is a Pat that handles this variant, so return it as-is.
6912     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6913         Op.getConstantOperandVal(2) == 0 &&
6914         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6915       return Op;
6916     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6917   }
6918   case Intrinsic::amdgcn_fcmp: {
6919     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6920   }
6921   case Intrinsic::amdgcn_ballot:
6922     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6923   case Intrinsic::amdgcn_fmed3:
6924     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6925                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6926   case Intrinsic::amdgcn_fdot2:
6927     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6928                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6929                        Op.getOperand(4));
6930   case Intrinsic::amdgcn_fmul_legacy:
6931     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6932                        Op.getOperand(1), Op.getOperand(2));
6933   case Intrinsic::amdgcn_sffbh:
6934     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6935   case Intrinsic::amdgcn_sbfe:
6936     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6937                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6938   case Intrinsic::amdgcn_ubfe:
6939     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6940                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6941   case Intrinsic::amdgcn_cvt_pkrtz:
6942   case Intrinsic::amdgcn_cvt_pknorm_i16:
6943   case Intrinsic::amdgcn_cvt_pknorm_u16:
6944   case Intrinsic::amdgcn_cvt_pk_i16:
6945   case Intrinsic::amdgcn_cvt_pk_u16: {
6946     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6947     EVT VT = Op.getValueType();
6948     unsigned Opcode;
6949 
6950     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6951       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6952     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6953       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6954     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6955       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6956     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6957       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6958     else
6959       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6960 
6961     if (isTypeLegal(VT))
6962       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6963 
6964     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6965                                Op.getOperand(1), Op.getOperand(2));
6966     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6967   }
6968   case Intrinsic::amdgcn_fmad_ftz:
6969     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6970                        Op.getOperand(2), Op.getOperand(3));
6971 
6972   case Intrinsic::amdgcn_if_break:
6973     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6974                                       Op->getOperand(1), Op->getOperand(2)), 0);
6975 
6976   case Intrinsic::amdgcn_groupstaticsize: {
6977     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6978     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6979       return Op;
6980 
6981     const Module *M = MF.getFunction().getParent();
6982     const GlobalValue *GV =
6983         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6984     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6985                                             SIInstrInfo::MO_ABS32_LO);
6986     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6987   }
6988   case Intrinsic::amdgcn_is_shared:
6989   case Intrinsic::amdgcn_is_private: {
6990     SDLoc SL(Op);
6991     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6992       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6993     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6994     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6995                                  Op.getOperand(1));
6996 
6997     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6998                                 DAG.getConstant(1, SL, MVT::i32));
6999     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7000   }
7001   case Intrinsic::amdgcn_perm:
7002     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7003                        Op.getOperand(2), Op.getOperand(3));
7004   case Intrinsic::amdgcn_reloc_constant: {
7005     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7006     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7007     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7008     auto RelocSymbol = cast<GlobalVariable>(
7009         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7010     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7011                                             SIInstrInfo::MO_ABS32_LO);
7012     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7013   }
7014   default:
7015     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7016             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7017       return lowerImage(Op, ImageDimIntr, DAG, false);
7018 
7019     return Op;
7020   }
7021 }
7022 
7023 /// Update \p MMO based on the offset inputs to an intrinsic.
7024 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7025                             SDValue SOffset, SDValue Offset,
7026                             SDValue VIndex = SDValue()) {
7027   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7028       !isa<ConstantSDNode>(Offset)) {
7029     // The combined offset is not known to be constant, so we cannot represent
7030     // it in the MMO. Give up.
7031     MMO->setValue((Value *)nullptr);
7032     return;
7033   }
7034 
7035   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7036                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7037     // The strided index component of the address is not known to be zero, so we
7038     // cannot represent it in the MMO. Give up.
7039     MMO->setValue((Value *)nullptr);
7040     return;
7041   }
7042 
7043   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7044                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7045                  cast<ConstantSDNode>(Offset)->getSExtValue());
7046 }
7047 
7048 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7049                                                      SelectionDAG &DAG,
7050                                                      unsigned NewOpcode) const {
7051   SDLoc DL(Op);
7052 
7053   SDValue VData = Op.getOperand(2);
7054   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7055   SDValue Ops[] = {
7056     Op.getOperand(0), // Chain
7057     VData,            // vdata
7058     Op.getOperand(3), // rsrc
7059     DAG.getConstant(0, DL, MVT::i32), // vindex
7060     Offsets.first,    // voffset
7061     Op.getOperand(5), // soffset
7062     Offsets.second,   // offset
7063     Op.getOperand(6), // cachepolicy
7064     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7065   };
7066 
7067   auto *M = cast<MemSDNode>(Op);
7068   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7069 
7070   EVT MemVT = VData.getValueType();
7071   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7072                                  M->getMemOperand());
7073 }
7074 
7075 // Return a value to use for the idxen operand by examining the vindex operand.
7076 static unsigned getIdxEn(SDValue VIndex) {
7077   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7078     // No need to set idxen if vindex is known to be zero.
7079     return VIndexC->getZExtValue() != 0;
7080   return 1;
7081 }
7082 
7083 SDValue
7084 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7085                                                 unsigned NewOpcode) const {
7086   SDLoc DL(Op);
7087 
7088   SDValue VData = Op.getOperand(2);
7089   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7090   SDValue Ops[] = {
7091     Op.getOperand(0), // Chain
7092     VData,            // vdata
7093     Op.getOperand(3), // rsrc
7094     Op.getOperand(4), // vindex
7095     Offsets.first,    // voffset
7096     Op.getOperand(6), // soffset
7097     Offsets.second,   // offset
7098     Op.getOperand(7), // cachepolicy
7099     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7100   };
7101 
7102   auto *M = cast<MemSDNode>(Op);
7103   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7104 
7105   EVT MemVT = VData.getValueType();
7106   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7107                                  M->getMemOperand());
7108 }
7109 
7110 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7111                                                  SelectionDAG &DAG) const {
7112   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7113   SDLoc DL(Op);
7114 
7115   switch (IntrID) {
7116   case Intrinsic::amdgcn_ds_ordered_add:
7117   case Intrinsic::amdgcn_ds_ordered_swap: {
7118     MemSDNode *M = cast<MemSDNode>(Op);
7119     SDValue Chain = M->getOperand(0);
7120     SDValue M0 = M->getOperand(2);
7121     SDValue Value = M->getOperand(3);
7122     unsigned IndexOperand = M->getConstantOperandVal(7);
7123     unsigned WaveRelease = M->getConstantOperandVal(8);
7124     unsigned WaveDone = M->getConstantOperandVal(9);
7125 
7126     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7127     IndexOperand &= ~0x3f;
7128     unsigned CountDw = 0;
7129 
7130     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7131       CountDw = (IndexOperand >> 24) & 0xf;
7132       IndexOperand &= ~(0xf << 24);
7133 
7134       if (CountDw < 1 || CountDw > 4) {
7135         report_fatal_error(
7136             "ds_ordered_count: dword count must be between 1 and 4");
7137       }
7138     }
7139 
7140     if (IndexOperand)
7141       report_fatal_error("ds_ordered_count: bad index operand");
7142 
7143     if (WaveDone && !WaveRelease)
7144       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7145 
7146     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7147     unsigned ShaderType =
7148         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7149     unsigned Offset0 = OrderedCountIndex << 2;
7150     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7151                        (Instruction << 4);
7152 
7153     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7154       Offset1 |= (CountDw - 1) << 6;
7155 
7156     unsigned Offset = Offset0 | (Offset1 << 8);
7157 
7158     SDValue Ops[] = {
7159       Chain,
7160       Value,
7161       DAG.getTargetConstant(Offset, DL, MVT::i16),
7162       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7163     };
7164     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7165                                    M->getVTList(), Ops, M->getMemoryVT(),
7166                                    M->getMemOperand());
7167   }
7168   case Intrinsic::amdgcn_ds_fadd: {
7169     MemSDNode *M = cast<MemSDNode>(Op);
7170     unsigned Opc;
7171     switch (IntrID) {
7172     case Intrinsic::amdgcn_ds_fadd:
7173       Opc = ISD::ATOMIC_LOAD_FADD;
7174       break;
7175     }
7176 
7177     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7178                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7179                          M->getMemOperand());
7180   }
7181   case Intrinsic::amdgcn_atomic_inc:
7182   case Intrinsic::amdgcn_atomic_dec:
7183   case Intrinsic::amdgcn_ds_fmin:
7184   case Intrinsic::amdgcn_ds_fmax: {
7185     MemSDNode *M = cast<MemSDNode>(Op);
7186     unsigned Opc;
7187     switch (IntrID) {
7188     case Intrinsic::amdgcn_atomic_inc:
7189       Opc = AMDGPUISD::ATOMIC_INC;
7190       break;
7191     case Intrinsic::amdgcn_atomic_dec:
7192       Opc = AMDGPUISD::ATOMIC_DEC;
7193       break;
7194     case Intrinsic::amdgcn_ds_fmin:
7195       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7196       break;
7197     case Intrinsic::amdgcn_ds_fmax:
7198       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7199       break;
7200     default:
7201       llvm_unreachable("Unknown intrinsic!");
7202     }
7203     SDValue Ops[] = {
7204       M->getOperand(0), // Chain
7205       M->getOperand(2), // Ptr
7206       M->getOperand(3)  // Value
7207     };
7208 
7209     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7210                                    M->getMemoryVT(), M->getMemOperand());
7211   }
7212   case Intrinsic::amdgcn_buffer_load:
7213   case Intrinsic::amdgcn_buffer_load_format: {
7214     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7215     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7216     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7217     SDValue Ops[] = {
7218       Op.getOperand(0), // Chain
7219       Op.getOperand(2), // rsrc
7220       Op.getOperand(3), // vindex
7221       SDValue(),        // voffset -- will be set by setBufferOffsets
7222       SDValue(),        // soffset -- will be set by setBufferOffsets
7223       SDValue(),        // offset -- will be set by setBufferOffsets
7224       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7225       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7226     };
7227     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7228 
7229     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7230         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7231 
7232     EVT VT = Op.getValueType();
7233     EVT IntVT = VT.changeTypeToInteger();
7234     auto *M = cast<MemSDNode>(Op);
7235     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7236     EVT LoadVT = Op.getValueType();
7237 
7238     if (LoadVT.getScalarType() == MVT::f16)
7239       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7240                                  M, DAG, Ops);
7241 
7242     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7243     if (LoadVT.getScalarType() == MVT::i8 ||
7244         LoadVT.getScalarType() == MVT::i16)
7245       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7246 
7247     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7248                                M->getMemOperand(), DAG);
7249   }
7250   case Intrinsic::amdgcn_raw_buffer_load:
7251   case Intrinsic::amdgcn_raw_buffer_load_format: {
7252     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7253 
7254     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7255     SDValue Ops[] = {
7256       Op.getOperand(0), // Chain
7257       Op.getOperand(2), // rsrc
7258       DAG.getConstant(0, DL, MVT::i32), // vindex
7259       Offsets.first,    // voffset
7260       Op.getOperand(4), // soffset
7261       Offsets.second,   // offset
7262       Op.getOperand(5), // cachepolicy, swizzled buffer
7263       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7264     };
7265 
7266     auto *M = cast<MemSDNode>(Op);
7267     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7268     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7269   }
7270   case Intrinsic::amdgcn_struct_buffer_load:
7271   case Intrinsic::amdgcn_struct_buffer_load_format: {
7272     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7273 
7274     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7275     SDValue Ops[] = {
7276       Op.getOperand(0), // Chain
7277       Op.getOperand(2), // rsrc
7278       Op.getOperand(3), // vindex
7279       Offsets.first,    // voffset
7280       Op.getOperand(5), // soffset
7281       Offsets.second,   // offset
7282       Op.getOperand(6), // cachepolicy, swizzled buffer
7283       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7284     };
7285 
7286     auto *M = cast<MemSDNode>(Op);
7287     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7288     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7289   }
7290   case Intrinsic::amdgcn_tbuffer_load: {
7291     MemSDNode *M = cast<MemSDNode>(Op);
7292     EVT LoadVT = Op.getValueType();
7293 
7294     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7295     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7296     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7297     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7298     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7299     SDValue Ops[] = {
7300       Op.getOperand(0),  // Chain
7301       Op.getOperand(2),  // rsrc
7302       Op.getOperand(3),  // vindex
7303       Op.getOperand(4),  // voffset
7304       Op.getOperand(5),  // soffset
7305       Op.getOperand(6),  // offset
7306       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7307       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7308       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7309     };
7310 
7311     if (LoadVT.getScalarType() == MVT::f16)
7312       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7313                                  M, DAG, Ops);
7314     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7315                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7316                                DAG);
7317   }
7318   case Intrinsic::amdgcn_raw_tbuffer_load: {
7319     MemSDNode *M = cast<MemSDNode>(Op);
7320     EVT LoadVT = Op.getValueType();
7321     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7322 
7323     SDValue Ops[] = {
7324       Op.getOperand(0),  // Chain
7325       Op.getOperand(2),  // rsrc
7326       DAG.getConstant(0, DL, MVT::i32), // vindex
7327       Offsets.first,     // voffset
7328       Op.getOperand(4),  // soffset
7329       Offsets.second,    // offset
7330       Op.getOperand(5),  // format
7331       Op.getOperand(6),  // cachepolicy, swizzled buffer
7332       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7333     };
7334 
7335     if (LoadVT.getScalarType() == MVT::f16)
7336       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7337                                  M, DAG, Ops);
7338     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7339                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7340                                DAG);
7341   }
7342   case Intrinsic::amdgcn_struct_tbuffer_load: {
7343     MemSDNode *M = cast<MemSDNode>(Op);
7344     EVT LoadVT = Op.getValueType();
7345     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7346 
7347     SDValue Ops[] = {
7348       Op.getOperand(0),  // Chain
7349       Op.getOperand(2),  // rsrc
7350       Op.getOperand(3),  // vindex
7351       Offsets.first,     // voffset
7352       Op.getOperand(5),  // soffset
7353       Offsets.second,    // offset
7354       Op.getOperand(6),  // format
7355       Op.getOperand(7),  // cachepolicy, swizzled buffer
7356       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7357     };
7358 
7359     if (LoadVT.getScalarType() == MVT::f16)
7360       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7361                                  M, DAG, Ops);
7362     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7363                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7364                                DAG);
7365   }
7366   case Intrinsic::amdgcn_buffer_atomic_swap:
7367   case Intrinsic::amdgcn_buffer_atomic_add:
7368   case Intrinsic::amdgcn_buffer_atomic_sub:
7369   case Intrinsic::amdgcn_buffer_atomic_csub:
7370   case Intrinsic::amdgcn_buffer_atomic_smin:
7371   case Intrinsic::amdgcn_buffer_atomic_umin:
7372   case Intrinsic::amdgcn_buffer_atomic_smax:
7373   case Intrinsic::amdgcn_buffer_atomic_umax:
7374   case Intrinsic::amdgcn_buffer_atomic_and:
7375   case Intrinsic::amdgcn_buffer_atomic_or:
7376   case Intrinsic::amdgcn_buffer_atomic_xor:
7377   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7378     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7379     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7380     SDValue Ops[] = {
7381       Op.getOperand(0), // Chain
7382       Op.getOperand(2), // vdata
7383       Op.getOperand(3), // rsrc
7384       Op.getOperand(4), // vindex
7385       SDValue(),        // voffset -- will be set by setBufferOffsets
7386       SDValue(),        // soffset -- will be set by setBufferOffsets
7387       SDValue(),        // offset -- will be set by setBufferOffsets
7388       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7389       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7390     };
7391     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7392 
7393     EVT VT = Op.getValueType();
7394 
7395     auto *M = cast<MemSDNode>(Op);
7396     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7397     unsigned Opcode = 0;
7398 
7399     switch (IntrID) {
7400     case Intrinsic::amdgcn_buffer_atomic_swap:
7401       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7402       break;
7403     case Intrinsic::amdgcn_buffer_atomic_add:
7404       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7405       break;
7406     case Intrinsic::amdgcn_buffer_atomic_sub:
7407       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7408       break;
7409     case Intrinsic::amdgcn_buffer_atomic_csub:
7410       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7411       break;
7412     case Intrinsic::amdgcn_buffer_atomic_smin:
7413       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7414       break;
7415     case Intrinsic::amdgcn_buffer_atomic_umin:
7416       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7417       break;
7418     case Intrinsic::amdgcn_buffer_atomic_smax:
7419       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7420       break;
7421     case Intrinsic::amdgcn_buffer_atomic_umax:
7422       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7423       break;
7424     case Intrinsic::amdgcn_buffer_atomic_and:
7425       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7426       break;
7427     case Intrinsic::amdgcn_buffer_atomic_or:
7428       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7429       break;
7430     case Intrinsic::amdgcn_buffer_atomic_xor:
7431       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7432       break;
7433     case Intrinsic::amdgcn_buffer_atomic_fadd:
7434       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7435         DiagnosticInfoUnsupported
7436           NoFpRet(DAG.getMachineFunction().getFunction(),
7437                   "return versions of fp atomics not supported",
7438                   DL.getDebugLoc(), DS_Error);
7439         DAG.getContext()->diagnose(NoFpRet);
7440         return SDValue();
7441       }
7442       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7443       break;
7444     default:
7445       llvm_unreachable("unhandled atomic opcode");
7446     }
7447 
7448     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7449                                    M->getMemOperand());
7450   }
7451   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7452     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7453   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7454     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7455   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7456     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7457   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7458     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7459   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7460     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7461   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7462     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7463   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7464     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7465   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7466     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7467   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7468     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7469   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7470     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7471   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7472     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7473   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7474     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7475   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7476     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7477   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7478     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7479   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7480     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7481   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7482     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7483   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7484     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7485   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7486     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7487   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7488     return lowerStructBufferAtomicIntrin(Op, DAG,
7489                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7490   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7491     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7492   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7493     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7494   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7495     return lowerStructBufferAtomicIntrin(Op, DAG,
7496                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7497   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7498     return lowerStructBufferAtomicIntrin(Op, DAG,
7499                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7500   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7501     return lowerStructBufferAtomicIntrin(Op, DAG,
7502                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7503   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7504     return lowerStructBufferAtomicIntrin(Op, DAG,
7505                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7506   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7507     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7508   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7509     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7510   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7511     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7512   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7513     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7514   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7515     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7516 
7517   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7518     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7519     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7520     SDValue Ops[] = {
7521       Op.getOperand(0), // Chain
7522       Op.getOperand(2), // src
7523       Op.getOperand(3), // cmp
7524       Op.getOperand(4), // rsrc
7525       Op.getOperand(5), // vindex
7526       SDValue(),        // voffset -- will be set by setBufferOffsets
7527       SDValue(),        // soffset -- will be set by setBufferOffsets
7528       SDValue(),        // offset -- will be set by setBufferOffsets
7529       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7530       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7531     };
7532     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7533 
7534     EVT VT = Op.getValueType();
7535     auto *M = cast<MemSDNode>(Op);
7536     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7537 
7538     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7539                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7540   }
7541   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7542     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7543     SDValue Ops[] = {
7544       Op.getOperand(0), // Chain
7545       Op.getOperand(2), // src
7546       Op.getOperand(3), // cmp
7547       Op.getOperand(4), // rsrc
7548       DAG.getConstant(0, DL, MVT::i32), // vindex
7549       Offsets.first,    // voffset
7550       Op.getOperand(6), // soffset
7551       Offsets.second,   // offset
7552       Op.getOperand(7), // cachepolicy
7553       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7554     };
7555     EVT VT = Op.getValueType();
7556     auto *M = cast<MemSDNode>(Op);
7557     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7558 
7559     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7560                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7561   }
7562   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7563     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7564     SDValue Ops[] = {
7565       Op.getOperand(0), // Chain
7566       Op.getOperand(2), // src
7567       Op.getOperand(3), // cmp
7568       Op.getOperand(4), // rsrc
7569       Op.getOperand(5), // vindex
7570       Offsets.first,    // voffset
7571       Op.getOperand(7), // soffset
7572       Offsets.second,   // offset
7573       Op.getOperand(8), // cachepolicy
7574       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7575     };
7576     EVT VT = Op.getValueType();
7577     auto *M = cast<MemSDNode>(Op);
7578     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7579 
7580     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7581                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7582   }
7583   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7584     MemSDNode *M = cast<MemSDNode>(Op);
7585     SDValue NodePtr = M->getOperand(2);
7586     SDValue RayExtent = M->getOperand(3);
7587     SDValue RayOrigin = M->getOperand(4);
7588     SDValue RayDir = M->getOperand(5);
7589     SDValue RayInvDir = M->getOperand(6);
7590     SDValue TDescr = M->getOperand(7);
7591 
7592     assert(NodePtr.getValueType() == MVT::i32 ||
7593            NodePtr.getValueType() == MVT::i64);
7594     assert(RayDir.getValueType() == MVT::v3f16 ||
7595            RayDir.getValueType() == MVT::v3f32);
7596 
7597     if (!Subtarget->hasGFX10_AEncoding()) {
7598       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7599       return SDValue();
7600     }
7601 
7602     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7603     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7604     const unsigned NumVDataDwords = 4;
7605     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7606     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7607                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7608     const unsigned BaseOpcodes[2][2] = {
7609         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7610         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7611          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7612     int Opcode;
7613     if (UseNSA) {
7614       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7615                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7616                                      NumVAddrDwords);
7617     } else {
7618       Opcode = AMDGPU::getMIMGOpcode(
7619           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7620           PowerOf2Ceil(NumVAddrDwords));
7621     }
7622     assert(Opcode != -1);
7623 
7624     SmallVector<SDValue, 16> Ops;
7625 
7626     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7627       SmallVector<SDValue, 3> Lanes;
7628       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7629       if (Lanes[0].getValueSizeInBits() == 32) {
7630         for (unsigned I = 0; I < 3; ++I)
7631           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7632       } else {
7633         if (IsAligned) {
7634           Ops.push_back(
7635             DAG.getBitcast(MVT::i32,
7636                            DAG.getBuildVector(MVT::v2f16, DL,
7637                                               { Lanes[0], Lanes[1] })));
7638           Ops.push_back(Lanes[2]);
7639         } else {
7640           SDValue Elt0 = Ops.pop_back_val();
7641           Ops.push_back(
7642             DAG.getBitcast(MVT::i32,
7643                            DAG.getBuildVector(MVT::v2f16, DL,
7644                                               { Elt0, Lanes[0] })));
7645           Ops.push_back(
7646             DAG.getBitcast(MVT::i32,
7647                            DAG.getBuildVector(MVT::v2f16, DL,
7648                                               { Lanes[1], Lanes[2] })));
7649         }
7650       }
7651     };
7652 
7653     if (Is64)
7654       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7655     else
7656       Ops.push_back(NodePtr);
7657 
7658     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7659     packLanes(RayOrigin, true);
7660     packLanes(RayDir, true);
7661     packLanes(RayInvDir, false);
7662 
7663     if (!UseNSA) {
7664       // Build a single vector containing all the operands so far prepared.
7665       if (NumVAddrDwords > 8) {
7666         SDValue Undef = DAG.getUNDEF(MVT::i32);
7667         Ops.append(16 - Ops.size(), Undef);
7668       }
7669       assert(Ops.size() == 8 || Ops.size() == 16);
7670       SDValue MergedOps = DAG.getBuildVector(
7671           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7672       Ops.clear();
7673       Ops.push_back(MergedOps);
7674     }
7675 
7676     Ops.push_back(TDescr);
7677     if (IsA16)
7678       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7679     Ops.push_back(M->getChain());
7680 
7681     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7682     MachineMemOperand *MemRef = M->getMemOperand();
7683     DAG.setNodeMemRefs(NewNode, {MemRef});
7684     return SDValue(NewNode, 0);
7685   }
7686   case Intrinsic::amdgcn_global_atomic_fadd:
7687     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7688       DiagnosticInfoUnsupported
7689         NoFpRet(DAG.getMachineFunction().getFunction(),
7690                 "return versions of fp atomics not supported",
7691                 DL.getDebugLoc(), DS_Error);
7692       DAG.getContext()->diagnose(NoFpRet);
7693       return SDValue();
7694     }
7695     LLVM_FALLTHROUGH;
7696   case Intrinsic::amdgcn_global_atomic_fmin:
7697   case Intrinsic::amdgcn_global_atomic_fmax:
7698   case Intrinsic::amdgcn_flat_atomic_fadd:
7699   case Intrinsic::amdgcn_flat_atomic_fmin:
7700   case Intrinsic::amdgcn_flat_atomic_fmax: {
7701     MemSDNode *M = cast<MemSDNode>(Op);
7702     SDValue Ops[] = {
7703       M->getOperand(0), // Chain
7704       M->getOperand(2), // Ptr
7705       M->getOperand(3)  // Value
7706     };
7707     unsigned Opcode = 0;
7708     switch (IntrID) {
7709     case Intrinsic::amdgcn_global_atomic_fadd:
7710     case Intrinsic::amdgcn_flat_atomic_fadd: {
7711       EVT VT = Op.getOperand(3).getValueType();
7712       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7713                            DAG.getVTList(VT, MVT::Other), Ops,
7714                            M->getMemOperand());
7715     }
7716     case Intrinsic::amdgcn_global_atomic_fmin:
7717     case Intrinsic::amdgcn_flat_atomic_fmin: {
7718       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7719       break;
7720     }
7721     case Intrinsic::amdgcn_global_atomic_fmax:
7722     case Intrinsic::amdgcn_flat_atomic_fmax: {
7723       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7724       break;
7725     }
7726     default:
7727       llvm_unreachable("unhandled atomic opcode");
7728     }
7729     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7730                                    M->getVTList(), Ops, M->getMemoryVT(),
7731                                    M->getMemOperand());
7732   }
7733   default:
7734 
7735     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7736             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7737       return lowerImage(Op, ImageDimIntr, DAG, true);
7738 
7739     return SDValue();
7740   }
7741 }
7742 
7743 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7744 // dwordx4 if on SI.
7745 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7746                                               SDVTList VTList,
7747                                               ArrayRef<SDValue> Ops, EVT MemVT,
7748                                               MachineMemOperand *MMO,
7749                                               SelectionDAG &DAG) const {
7750   EVT VT = VTList.VTs[0];
7751   EVT WidenedVT = VT;
7752   EVT WidenedMemVT = MemVT;
7753   if (!Subtarget->hasDwordx3LoadStores() &&
7754       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7755     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7756                                  WidenedVT.getVectorElementType(), 4);
7757     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7758                                     WidenedMemVT.getVectorElementType(), 4);
7759     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7760   }
7761 
7762   assert(VTList.NumVTs == 2);
7763   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7764 
7765   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7766                                        WidenedMemVT, MMO);
7767   if (WidenedVT != VT) {
7768     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7769                                DAG.getVectorIdxConstant(0, DL));
7770     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7771   }
7772   return NewOp;
7773 }
7774 
7775 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7776                                          bool ImageStore) const {
7777   EVT StoreVT = VData.getValueType();
7778 
7779   // No change for f16 and legal vector D16 types.
7780   if (!StoreVT.isVector())
7781     return VData;
7782 
7783   SDLoc DL(VData);
7784   unsigned NumElements = StoreVT.getVectorNumElements();
7785 
7786   if (Subtarget->hasUnpackedD16VMem()) {
7787     // We need to unpack the packed data to store.
7788     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7789     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7790 
7791     EVT EquivStoreVT =
7792         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7793     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7794     return DAG.UnrollVectorOp(ZExt.getNode());
7795   }
7796 
7797   // The sq block of gfx8.1 does not estimate register use correctly for d16
7798   // image store instructions. The data operand is computed as if it were not a
7799   // d16 image instruction.
7800   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7801     // Bitcast to i16
7802     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7803     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7804 
7805     // Decompose into scalars
7806     SmallVector<SDValue, 4> Elts;
7807     DAG.ExtractVectorElements(IntVData, Elts);
7808 
7809     // Group pairs of i16 into v2i16 and bitcast to i32
7810     SmallVector<SDValue, 4> PackedElts;
7811     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7812       SDValue Pair =
7813           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7814       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7815       PackedElts.push_back(IntPair);
7816     }
7817     if ((NumElements % 2) == 1) {
7818       // Handle v3i16
7819       unsigned I = Elts.size() / 2;
7820       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7821                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7822       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7823       PackedElts.push_back(IntPair);
7824     }
7825 
7826     // Pad using UNDEF
7827     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7828 
7829     // Build final vector
7830     EVT VecVT =
7831         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7832     return DAG.getBuildVector(VecVT, DL, PackedElts);
7833   }
7834 
7835   if (NumElements == 3) {
7836     EVT IntStoreVT =
7837         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7838     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7839 
7840     EVT WidenedStoreVT = EVT::getVectorVT(
7841         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7842     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7843                                          WidenedStoreVT.getStoreSizeInBits());
7844     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7845     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7846   }
7847 
7848   assert(isTypeLegal(StoreVT));
7849   return VData;
7850 }
7851 
7852 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7853                                               SelectionDAG &DAG) const {
7854   SDLoc DL(Op);
7855   SDValue Chain = Op.getOperand(0);
7856   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7857   MachineFunction &MF = DAG.getMachineFunction();
7858 
7859   switch (IntrinsicID) {
7860   case Intrinsic::amdgcn_exp_compr: {
7861     SDValue Src0 = Op.getOperand(4);
7862     SDValue Src1 = Op.getOperand(5);
7863     // Hack around illegal type on SI by directly selecting it.
7864     if (isTypeLegal(Src0.getValueType()))
7865       return SDValue();
7866 
7867     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7868     SDValue Undef = DAG.getUNDEF(MVT::f32);
7869     const SDValue Ops[] = {
7870       Op.getOperand(2), // tgt
7871       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7872       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7873       Undef, // src2
7874       Undef, // src3
7875       Op.getOperand(7), // vm
7876       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7877       Op.getOperand(3), // en
7878       Op.getOperand(0) // Chain
7879     };
7880 
7881     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7882     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7883   }
7884   case Intrinsic::amdgcn_s_barrier: {
7885     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7886       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7887       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7888       if (WGSize <= ST.getWavefrontSize())
7889         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7890                                           Op.getOperand(0)), 0);
7891     }
7892     return SDValue();
7893   };
7894   case Intrinsic::amdgcn_tbuffer_store: {
7895     SDValue VData = Op.getOperand(2);
7896     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7897     if (IsD16)
7898       VData = handleD16VData(VData, DAG);
7899     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7900     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7901     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7902     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7903     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7904     SDValue Ops[] = {
7905       Chain,
7906       VData,             // vdata
7907       Op.getOperand(3),  // rsrc
7908       Op.getOperand(4),  // vindex
7909       Op.getOperand(5),  // voffset
7910       Op.getOperand(6),  // soffset
7911       Op.getOperand(7),  // offset
7912       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7913       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7914       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7915     };
7916     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7917                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7918     MemSDNode *M = cast<MemSDNode>(Op);
7919     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7920                                    M->getMemoryVT(), M->getMemOperand());
7921   }
7922 
7923   case Intrinsic::amdgcn_struct_tbuffer_store: {
7924     SDValue VData = Op.getOperand(2);
7925     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7926     if (IsD16)
7927       VData = handleD16VData(VData, DAG);
7928     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7929     SDValue Ops[] = {
7930       Chain,
7931       VData,             // vdata
7932       Op.getOperand(3),  // rsrc
7933       Op.getOperand(4),  // vindex
7934       Offsets.first,     // voffset
7935       Op.getOperand(6),  // soffset
7936       Offsets.second,    // offset
7937       Op.getOperand(7),  // format
7938       Op.getOperand(8),  // cachepolicy, swizzled buffer
7939       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7940     };
7941     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7942                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7943     MemSDNode *M = cast<MemSDNode>(Op);
7944     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7945                                    M->getMemoryVT(), M->getMemOperand());
7946   }
7947 
7948   case Intrinsic::amdgcn_raw_tbuffer_store: {
7949     SDValue VData = Op.getOperand(2);
7950     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7951     if (IsD16)
7952       VData = handleD16VData(VData, DAG);
7953     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7954     SDValue Ops[] = {
7955       Chain,
7956       VData,             // vdata
7957       Op.getOperand(3),  // rsrc
7958       DAG.getConstant(0, DL, MVT::i32), // vindex
7959       Offsets.first,     // voffset
7960       Op.getOperand(5),  // soffset
7961       Offsets.second,    // offset
7962       Op.getOperand(6),  // format
7963       Op.getOperand(7),  // cachepolicy, swizzled buffer
7964       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7965     };
7966     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7967                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7968     MemSDNode *M = cast<MemSDNode>(Op);
7969     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7970                                    M->getMemoryVT(), M->getMemOperand());
7971   }
7972 
7973   case Intrinsic::amdgcn_buffer_store:
7974   case Intrinsic::amdgcn_buffer_store_format: {
7975     SDValue VData = Op.getOperand(2);
7976     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7977     if (IsD16)
7978       VData = handleD16VData(VData, DAG);
7979     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7980     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7981     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7982     SDValue Ops[] = {
7983       Chain,
7984       VData,
7985       Op.getOperand(3), // rsrc
7986       Op.getOperand(4), // vindex
7987       SDValue(), // voffset -- will be set by setBufferOffsets
7988       SDValue(), // soffset -- will be set by setBufferOffsets
7989       SDValue(), // offset -- will be set by setBufferOffsets
7990       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7991       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7992     };
7993     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7994 
7995     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7996                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7997     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7998     MemSDNode *M = cast<MemSDNode>(Op);
7999     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8000 
8001     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8002     EVT VDataType = VData.getValueType().getScalarType();
8003     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8004       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8005 
8006     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8007                                    M->getMemoryVT(), M->getMemOperand());
8008   }
8009 
8010   case Intrinsic::amdgcn_raw_buffer_store:
8011   case Intrinsic::amdgcn_raw_buffer_store_format: {
8012     const bool IsFormat =
8013         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8014 
8015     SDValue VData = Op.getOperand(2);
8016     EVT VDataVT = VData.getValueType();
8017     EVT EltType = VDataVT.getScalarType();
8018     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8019     if (IsD16) {
8020       VData = handleD16VData(VData, DAG);
8021       VDataVT = VData.getValueType();
8022     }
8023 
8024     if (!isTypeLegal(VDataVT)) {
8025       VData =
8026           DAG.getNode(ISD::BITCAST, DL,
8027                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8028     }
8029 
8030     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8031     SDValue Ops[] = {
8032       Chain,
8033       VData,
8034       Op.getOperand(3), // rsrc
8035       DAG.getConstant(0, DL, MVT::i32), // vindex
8036       Offsets.first,    // voffset
8037       Op.getOperand(5), // soffset
8038       Offsets.second,   // offset
8039       Op.getOperand(6), // cachepolicy, swizzled buffer
8040       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8041     };
8042     unsigned Opc =
8043         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8044     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8045     MemSDNode *M = cast<MemSDNode>(Op);
8046     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8047 
8048     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8049     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8050       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8051 
8052     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8053                                    M->getMemoryVT(), M->getMemOperand());
8054   }
8055 
8056   case Intrinsic::amdgcn_struct_buffer_store:
8057   case Intrinsic::amdgcn_struct_buffer_store_format: {
8058     const bool IsFormat =
8059         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8060 
8061     SDValue VData = Op.getOperand(2);
8062     EVT VDataVT = VData.getValueType();
8063     EVT EltType = VDataVT.getScalarType();
8064     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8065 
8066     if (IsD16) {
8067       VData = handleD16VData(VData, DAG);
8068       VDataVT = VData.getValueType();
8069     }
8070 
8071     if (!isTypeLegal(VDataVT)) {
8072       VData =
8073           DAG.getNode(ISD::BITCAST, DL,
8074                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8075     }
8076 
8077     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8078     SDValue Ops[] = {
8079       Chain,
8080       VData,
8081       Op.getOperand(3), // rsrc
8082       Op.getOperand(4), // vindex
8083       Offsets.first,    // voffset
8084       Op.getOperand(6), // soffset
8085       Offsets.second,   // offset
8086       Op.getOperand(7), // cachepolicy, swizzled buffer
8087       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8088     };
8089     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8090                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8091     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8092     MemSDNode *M = cast<MemSDNode>(Op);
8093     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8094 
8095     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8096     EVT VDataType = VData.getValueType().getScalarType();
8097     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8098       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8099 
8100     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8101                                    M->getMemoryVT(), M->getMemOperand());
8102   }
8103   case Intrinsic::amdgcn_end_cf:
8104     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8105                                       Op->getOperand(2), Chain), 0);
8106 
8107   default: {
8108     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8109             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8110       return lowerImage(Op, ImageDimIntr, DAG, true);
8111 
8112     return Op;
8113   }
8114   }
8115 }
8116 
8117 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8118 // offset (the offset that is included in bounds checking and swizzling, to be
8119 // split between the instruction's voffset and immoffset fields) and soffset
8120 // (the offset that is excluded from bounds checking and swizzling, to go in
8121 // the instruction's soffset field).  This function takes the first kind of
8122 // offset and figures out how to split it between voffset and immoffset.
8123 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8124     SDValue Offset, SelectionDAG &DAG) const {
8125   SDLoc DL(Offset);
8126   const unsigned MaxImm = 4095;
8127   SDValue N0 = Offset;
8128   ConstantSDNode *C1 = nullptr;
8129 
8130   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8131     N0 = SDValue();
8132   else if (DAG.isBaseWithConstantOffset(N0)) {
8133     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8134     N0 = N0.getOperand(0);
8135   }
8136 
8137   if (C1) {
8138     unsigned ImmOffset = C1->getZExtValue();
8139     // If the immediate value is too big for the immoffset field, put the value
8140     // and -4096 into the immoffset field so that the value that is copied/added
8141     // for the voffset field is a multiple of 4096, and it stands more chance
8142     // of being CSEd with the copy/add for another similar load/store.
8143     // However, do not do that rounding down to a multiple of 4096 if that is a
8144     // negative number, as it appears to be illegal to have a negative offset
8145     // in the vgpr, even if adding the immediate offset makes it positive.
8146     unsigned Overflow = ImmOffset & ~MaxImm;
8147     ImmOffset -= Overflow;
8148     if ((int32_t)Overflow < 0) {
8149       Overflow += ImmOffset;
8150       ImmOffset = 0;
8151     }
8152     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8153     if (Overflow) {
8154       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8155       if (!N0)
8156         N0 = OverflowVal;
8157       else {
8158         SDValue Ops[] = { N0, OverflowVal };
8159         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8160       }
8161     }
8162   }
8163   if (!N0)
8164     N0 = DAG.getConstant(0, DL, MVT::i32);
8165   if (!C1)
8166     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8167   return {N0, SDValue(C1, 0)};
8168 }
8169 
8170 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8171 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8172 // pointed to by Offsets.
8173 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8174                                         SelectionDAG &DAG, SDValue *Offsets,
8175                                         Align Alignment) const {
8176   SDLoc DL(CombinedOffset);
8177   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8178     uint32_t Imm = C->getZExtValue();
8179     uint32_t SOffset, ImmOffset;
8180     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8181                                  Alignment)) {
8182       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8183       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8184       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8185       return;
8186     }
8187   }
8188   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8189     SDValue N0 = CombinedOffset.getOperand(0);
8190     SDValue N1 = CombinedOffset.getOperand(1);
8191     uint32_t SOffset, ImmOffset;
8192     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8193     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8194                                                 Subtarget, Alignment)) {
8195       Offsets[0] = N0;
8196       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8197       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8198       return;
8199     }
8200   }
8201   Offsets[0] = CombinedOffset;
8202   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8203   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8204 }
8205 
8206 // Handle 8 bit and 16 bit buffer loads
8207 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8208                                                      EVT LoadVT, SDLoc DL,
8209                                                      ArrayRef<SDValue> Ops,
8210                                                      MemSDNode *M) const {
8211   EVT IntVT = LoadVT.changeTypeToInteger();
8212   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8213          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8214 
8215   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8216   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8217                                                Ops, IntVT,
8218                                                M->getMemOperand());
8219   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8220   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8221 
8222   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8223 }
8224 
8225 // Handle 8 bit and 16 bit buffer stores
8226 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8227                                                       EVT VDataType, SDLoc DL,
8228                                                       SDValue Ops[],
8229                                                       MemSDNode *M) const {
8230   if (VDataType == MVT::f16)
8231     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8232 
8233   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8234   Ops[1] = BufferStoreExt;
8235   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8236                                  AMDGPUISD::BUFFER_STORE_SHORT;
8237   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8238   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8239                                      M->getMemOperand());
8240 }
8241 
8242 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8243                                  ISD::LoadExtType ExtType, SDValue Op,
8244                                  const SDLoc &SL, EVT VT) {
8245   if (VT.bitsLT(Op.getValueType()))
8246     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8247 
8248   switch (ExtType) {
8249   case ISD::SEXTLOAD:
8250     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8251   case ISD::ZEXTLOAD:
8252     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8253   case ISD::EXTLOAD:
8254     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8255   case ISD::NON_EXTLOAD:
8256     return Op;
8257   }
8258 
8259   llvm_unreachable("invalid ext type");
8260 }
8261 
8262 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8263   SelectionDAG &DAG = DCI.DAG;
8264   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8265     return SDValue();
8266 
8267   // FIXME: Constant loads should all be marked invariant.
8268   unsigned AS = Ld->getAddressSpace();
8269   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8270       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8271       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8272     return SDValue();
8273 
8274   // Don't do this early, since it may interfere with adjacent load merging for
8275   // illegal types. We can avoid losing alignment information for exotic types
8276   // pre-legalize.
8277   EVT MemVT = Ld->getMemoryVT();
8278   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8279       MemVT.getSizeInBits() >= 32)
8280     return SDValue();
8281 
8282   SDLoc SL(Ld);
8283 
8284   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8285          "unexpected vector extload");
8286 
8287   // TODO: Drop only high part of range.
8288   SDValue Ptr = Ld->getBasePtr();
8289   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8290                                 MVT::i32, SL, Ld->getChain(), Ptr,
8291                                 Ld->getOffset(),
8292                                 Ld->getPointerInfo(), MVT::i32,
8293                                 Ld->getAlignment(),
8294                                 Ld->getMemOperand()->getFlags(),
8295                                 Ld->getAAInfo(),
8296                                 nullptr); // Drop ranges
8297 
8298   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8299   if (MemVT.isFloatingPoint()) {
8300     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8301            "unexpected fp extload");
8302     TruncVT = MemVT.changeTypeToInteger();
8303   }
8304 
8305   SDValue Cvt = NewLoad;
8306   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8307     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8308                       DAG.getValueType(TruncVT));
8309   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8310              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8311     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8312   } else {
8313     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8314   }
8315 
8316   EVT VT = Ld->getValueType(0);
8317   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8318 
8319   DCI.AddToWorklist(Cvt.getNode());
8320 
8321   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8322   // the appropriate extension from the 32-bit load.
8323   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8324   DCI.AddToWorklist(Cvt.getNode());
8325 
8326   // Handle conversion back to floating point if necessary.
8327   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8328 
8329   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8330 }
8331 
8332 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8333   SDLoc DL(Op);
8334   LoadSDNode *Load = cast<LoadSDNode>(Op);
8335   ISD::LoadExtType ExtType = Load->getExtensionType();
8336   EVT MemVT = Load->getMemoryVT();
8337 
8338   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8339     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8340       return SDValue();
8341 
8342     // FIXME: Copied from PPC
8343     // First, load into 32 bits, then truncate to 1 bit.
8344 
8345     SDValue Chain = Load->getChain();
8346     SDValue BasePtr = Load->getBasePtr();
8347     MachineMemOperand *MMO = Load->getMemOperand();
8348 
8349     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8350 
8351     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8352                                    BasePtr, RealMemVT, MMO);
8353 
8354     if (!MemVT.isVector()) {
8355       SDValue Ops[] = {
8356         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8357         NewLD.getValue(1)
8358       };
8359 
8360       return DAG.getMergeValues(Ops, DL);
8361     }
8362 
8363     SmallVector<SDValue, 3> Elts;
8364     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8365       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8366                                 DAG.getConstant(I, DL, MVT::i32));
8367 
8368       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8369     }
8370 
8371     SDValue Ops[] = {
8372       DAG.getBuildVector(MemVT, DL, Elts),
8373       NewLD.getValue(1)
8374     };
8375 
8376     return DAG.getMergeValues(Ops, DL);
8377   }
8378 
8379   if (!MemVT.isVector())
8380     return SDValue();
8381 
8382   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8383          "Custom lowering for non-i32 vectors hasn't been implemented.");
8384 
8385   unsigned Alignment = Load->getAlignment();
8386   unsigned AS = Load->getAddressSpace();
8387   if (Subtarget->hasLDSMisalignedBug() &&
8388       AS == AMDGPUAS::FLAT_ADDRESS &&
8389       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8390     return SplitVectorLoad(Op, DAG);
8391   }
8392 
8393   MachineFunction &MF = DAG.getMachineFunction();
8394   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8395   // If there is a possibilty that flat instruction access scratch memory
8396   // then we need to use the same legalization rules we use for private.
8397   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8398       !Subtarget->hasMultiDwordFlatScratchAddressing())
8399     AS = MFI->hasFlatScratchInit() ?
8400          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8401 
8402   unsigned NumElements = MemVT.getVectorNumElements();
8403 
8404   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8405       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8406     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8407       if (MemVT.isPow2VectorType())
8408         return SDValue();
8409       return WidenOrSplitVectorLoad(Op, DAG);
8410     }
8411     // Non-uniform loads will be selected to MUBUF instructions, so they
8412     // have the same legalization requirements as global and private
8413     // loads.
8414     //
8415   }
8416 
8417   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8418       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8419       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8420     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8421         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8422         Alignment >= 4 && NumElements < 32) {
8423       if (MemVT.isPow2VectorType())
8424         return SDValue();
8425       return WidenOrSplitVectorLoad(Op, DAG);
8426     }
8427     // Non-uniform loads will be selected to MUBUF instructions, so they
8428     // have the same legalization requirements as global and private
8429     // loads.
8430     //
8431   }
8432   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8433       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8434       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8435       AS == AMDGPUAS::FLAT_ADDRESS) {
8436     if (NumElements > 4)
8437       return SplitVectorLoad(Op, DAG);
8438     // v3 loads not supported on SI.
8439     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8440       return WidenOrSplitVectorLoad(Op, DAG);
8441 
8442     // v3 and v4 loads are supported for private and global memory.
8443     return SDValue();
8444   }
8445   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8446     // Depending on the setting of the private_element_size field in the
8447     // resource descriptor, we can only make private accesses up to a certain
8448     // size.
8449     switch (Subtarget->getMaxPrivateElementSize()) {
8450     case 4: {
8451       SDValue Ops[2];
8452       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8453       return DAG.getMergeValues(Ops, DL);
8454     }
8455     case 8:
8456       if (NumElements > 2)
8457         return SplitVectorLoad(Op, DAG);
8458       return SDValue();
8459     case 16:
8460       // Same as global/flat
8461       if (NumElements > 4)
8462         return SplitVectorLoad(Op, DAG);
8463       // v3 loads not supported on SI.
8464       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8465         return WidenOrSplitVectorLoad(Op, DAG);
8466 
8467       return SDValue();
8468     default:
8469       llvm_unreachable("unsupported private_element_size");
8470     }
8471   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8472     // Use ds_read_b128 or ds_read_b96 when possible.
8473     if (Subtarget->hasDS96AndDS128() &&
8474         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8475          MemVT.getStoreSize() == 12) &&
8476         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8477                                            Load->getAlign()))
8478       return SDValue();
8479 
8480     if (NumElements > 2)
8481       return SplitVectorLoad(Op, DAG);
8482 
8483     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8484     // address is negative, then the instruction is incorrectly treated as
8485     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8486     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8487     // load later in the SILoadStoreOptimizer.
8488     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8489         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8490         Load->getAlignment() < 8) {
8491       return SplitVectorLoad(Op, DAG);
8492     }
8493   }
8494 
8495   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8496                                       MemVT, *Load->getMemOperand())) {
8497     SDValue Ops[2];
8498     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8499     return DAG.getMergeValues(Ops, DL);
8500   }
8501 
8502   return SDValue();
8503 }
8504 
8505 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8506   EVT VT = Op.getValueType();
8507   if (VT.getSizeInBits() == 128)
8508     return splitTernaryVectorOp(Op, DAG);
8509 
8510   assert(VT.getSizeInBits() == 64);
8511 
8512   SDLoc DL(Op);
8513   SDValue Cond = Op.getOperand(0);
8514 
8515   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8516   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8517 
8518   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8519   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8520 
8521   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8522   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8523 
8524   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8525 
8526   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8527   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8528 
8529   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8530 
8531   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8532   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8533 }
8534 
8535 // Catch division cases where we can use shortcuts with rcp and rsq
8536 // instructions.
8537 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8538                                               SelectionDAG &DAG) const {
8539   SDLoc SL(Op);
8540   SDValue LHS = Op.getOperand(0);
8541   SDValue RHS = Op.getOperand(1);
8542   EVT VT = Op.getValueType();
8543   const SDNodeFlags Flags = Op->getFlags();
8544 
8545   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8546 
8547   // Without !fpmath accuracy information, we can't do more because we don't
8548   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8549   if (!AllowInaccurateRcp)
8550     return SDValue();
8551 
8552   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8553     if (CLHS->isExactlyValue(1.0)) {
8554       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8555       // the CI documentation has a worst case error of 1 ulp.
8556       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8557       // use it as long as we aren't trying to use denormals.
8558       //
8559       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8560 
8561       // 1.0 / sqrt(x) -> rsq(x)
8562 
8563       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8564       // error seems really high at 2^29 ULP.
8565       if (RHS.getOpcode() == ISD::FSQRT)
8566         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8567 
8568       // 1.0 / x -> rcp(x)
8569       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8570     }
8571 
8572     // Same as for 1.0, but expand the sign out of the constant.
8573     if (CLHS->isExactlyValue(-1.0)) {
8574       // -1.0 / x -> rcp (fneg x)
8575       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8576       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8577     }
8578   }
8579 
8580   // Turn into multiply by the reciprocal.
8581   // x / y -> x * (1.0 / y)
8582   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8583   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8584 }
8585 
8586 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8587                                                 SelectionDAG &DAG) const {
8588   SDLoc SL(Op);
8589   SDValue X = Op.getOperand(0);
8590   SDValue Y = Op.getOperand(1);
8591   EVT VT = Op.getValueType();
8592   const SDNodeFlags Flags = Op->getFlags();
8593 
8594   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8595                             DAG.getTarget().Options.UnsafeFPMath;
8596   if (!AllowInaccurateDiv)
8597     return SDValue();
8598 
8599   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8600   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8601 
8602   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8603   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8604 
8605   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8606   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8607   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8608   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8609   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8610   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8611 }
8612 
8613 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8614                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8615                           SDNodeFlags Flags) {
8616   if (GlueChain->getNumValues() <= 1) {
8617     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8618   }
8619 
8620   assert(GlueChain->getNumValues() == 3);
8621 
8622   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8623   switch (Opcode) {
8624   default: llvm_unreachable("no chain equivalent for opcode");
8625   case ISD::FMUL:
8626     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8627     break;
8628   }
8629 
8630   return DAG.getNode(Opcode, SL, VTList,
8631                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8632                      Flags);
8633 }
8634 
8635 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8636                            EVT VT, SDValue A, SDValue B, SDValue C,
8637                            SDValue GlueChain, SDNodeFlags Flags) {
8638   if (GlueChain->getNumValues() <= 1) {
8639     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8640   }
8641 
8642   assert(GlueChain->getNumValues() == 3);
8643 
8644   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8645   switch (Opcode) {
8646   default: llvm_unreachable("no chain equivalent for opcode");
8647   case ISD::FMA:
8648     Opcode = AMDGPUISD::FMA_W_CHAIN;
8649     break;
8650   }
8651 
8652   return DAG.getNode(Opcode, SL, VTList,
8653                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8654                      Flags);
8655 }
8656 
8657 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8658   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8659     return FastLowered;
8660 
8661   SDLoc SL(Op);
8662   SDValue Src0 = Op.getOperand(0);
8663   SDValue Src1 = Op.getOperand(1);
8664 
8665   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8666   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8667 
8668   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8669   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8670 
8671   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8672   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8673 
8674   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8675 }
8676 
8677 // Faster 2.5 ULP division that does not support denormals.
8678 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8679   SDLoc SL(Op);
8680   SDValue LHS = Op.getOperand(1);
8681   SDValue RHS = Op.getOperand(2);
8682 
8683   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8684 
8685   const APFloat K0Val(BitsToFloat(0x6f800000));
8686   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8687 
8688   const APFloat K1Val(BitsToFloat(0x2f800000));
8689   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8690 
8691   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8692 
8693   EVT SetCCVT =
8694     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8695 
8696   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8697 
8698   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8699 
8700   // TODO: Should this propagate fast-math-flags?
8701   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8702 
8703   // rcp does not support denormals.
8704   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8705 
8706   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8707 
8708   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8709 }
8710 
8711 // Returns immediate value for setting the F32 denorm mode when using the
8712 // S_DENORM_MODE instruction.
8713 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8714                                     const SDLoc &SL, const GCNSubtarget *ST) {
8715   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8716   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8717                                 ? FP_DENORM_FLUSH_NONE
8718                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8719 
8720   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8721   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8722 }
8723 
8724 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8725   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8726     return FastLowered;
8727 
8728   // The selection matcher assumes anything with a chain selecting to a
8729   // mayRaiseFPException machine instruction. Since we're introducing a chain
8730   // here, we need to explicitly report nofpexcept for the regular fdiv
8731   // lowering.
8732   SDNodeFlags Flags = Op->getFlags();
8733   Flags.setNoFPExcept(true);
8734 
8735   SDLoc SL(Op);
8736   SDValue LHS = Op.getOperand(0);
8737   SDValue RHS = Op.getOperand(1);
8738 
8739   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8740 
8741   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8742 
8743   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8744                                           {RHS, RHS, LHS}, Flags);
8745   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8746                                         {LHS, RHS, LHS}, Flags);
8747 
8748   // Denominator is scaled to not be denormal, so using rcp is ok.
8749   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8750                                   DenominatorScaled, Flags);
8751   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8752                                      DenominatorScaled, Flags);
8753 
8754   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8755                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8756                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8757   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8758 
8759   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8760 
8761   if (!HasFP32Denormals) {
8762     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8763     // lowering. The chain dependence is insufficient, and we need glue. We do
8764     // not need the glue variants in a strictfp function.
8765 
8766     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8767 
8768     SDNode *EnableDenorm;
8769     if (Subtarget->hasDenormModeInst()) {
8770       const SDValue EnableDenormValue =
8771           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8772 
8773       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8774                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8775     } else {
8776       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8777                                                         SL, MVT::i32);
8778       EnableDenorm =
8779           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8780                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8781     }
8782 
8783     SDValue Ops[3] = {
8784       NegDivScale0,
8785       SDValue(EnableDenorm, 0),
8786       SDValue(EnableDenorm, 1)
8787     };
8788 
8789     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8790   }
8791 
8792   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8793                              ApproxRcp, One, NegDivScale0, Flags);
8794 
8795   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8796                              ApproxRcp, Fma0, Flags);
8797 
8798   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8799                            Fma1, Fma1, Flags);
8800 
8801   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8802                              NumeratorScaled, Mul, Flags);
8803 
8804   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8805                              Fma2, Fma1, Mul, Fma2, Flags);
8806 
8807   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8808                              NumeratorScaled, Fma3, Flags);
8809 
8810   if (!HasFP32Denormals) {
8811     SDNode *DisableDenorm;
8812     if (Subtarget->hasDenormModeInst()) {
8813       const SDValue DisableDenormValue =
8814           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8815 
8816       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8817                                   Fma4.getValue(1), DisableDenormValue,
8818                                   Fma4.getValue(2)).getNode();
8819     } else {
8820       const SDValue DisableDenormValue =
8821           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8822 
8823       DisableDenorm = DAG.getMachineNode(
8824           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8825           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8826     }
8827 
8828     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8829                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8830     DAG.setRoot(OutputChain);
8831   }
8832 
8833   SDValue Scale = NumeratorScaled.getValue(1);
8834   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8835                              {Fma4, Fma1, Fma3, Scale}, Flags);
8836 
8837   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8838 }
8839 
8840 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8841   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8842     return FastLowered;
8843 
8844   SDLoc SL(Op);
8845   SDValue X = Op.getOperand(0);
8846   SDValue Y = Op.getOperand(1);
8847 
8848   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8849 
8850   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8851 
8852   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8853 
8854   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8855 
8856   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8857 
8858   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8859 
8860   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8861 
8862   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8863 
8864   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8865 
8866   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8867   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8868 
8869   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8870                              NegDivScale0, Mul, DivScale1);
8871 
8872   SDValue Scale;
8873 
8874   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8875     // Workaround a hardware bug on SI where the condition output from div_scale
8876     // is not usable.
8877 
8878     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8879 
8880     // Figure out if the scale to use for div_fmas.
8881     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8882     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8883     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8884     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8885 
8886     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8887     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8888 
8889     SDValue Scale0Hi
8890       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8891     SDValue Scale1Hi
8892       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8893 
8894     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8895     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8896     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8897   } else {
8898     Scale = DivScale1.getValue(1);
8899   }
8900 
8901   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8902                              Fma4, Fma3, Mul, Scale);
8903 
8904   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8905 }
8906 
8907 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8908   EVT VT = Op.getValueType();
8909 
8910   if (VT == MVT::f32)
8911     return LowerFDIV32(Op, DAG);
8912 
8913   if (VT == MVT::f64)
8914     return LowerFDIV64(Op, DAG);
8915 
8916   if (VT == MVT::f16)
8917     return LowerFDIV16(Op, DAG);
8918 
8919   llvm_unreachable("Unexpected type for fdiv");
8920 }
8921 
8922 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8923   SDLoc DL(Op);
8924   StoreSDNode *Store = cast<StoreSDNode>(Op);
8925   EVT VT = Store->getMemoryVT();
8926 
8927   if (VT == MVT::i1) {
8928     return DAG.getTruncStore(Store->getChain(), DL,
8929        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8930        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8931   }
8932 
8933   assert(VT.isVector() &&
8934          Store->getValue().getValueType().getScalarType() == MVT::i32);
8935 
8936   unsigned AS = Store->getAddressSpace();
8937   if (Subtarget->hasLDSMisalignedBug() &&
8938       AS == AMDGPUAS::FLAT_ADDRESS &&
8939       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8940     return SplitVectorStore(Op, DAG);
8941   }
8942 
8943   MachineFunction &MF = DAG.getMachineFunction();
8944   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8945   // If there is a possibilty that flat instruction access scratch memory
8946   // then we need to use the same legalization rules we use for private.
8947   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8948       !Subtarget->hasMultiDwordFlatScratchAddressing())
8949     AS = MFI->hasFlatScratchInit() ?
8950          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8951 
8952   unsigned NumElements = VT.getVectorNumElements();
8953   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8954       AS == AMDGPUAS::FLAT_ADDRESS) {
8955     if (NumElements > 4)
8956       return SplitVectorStore(Op, DAG);
8957     // v3 stores not supported on SI.
8958     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8959       return SplitVectorStore(Op, DAG);
8960 
8961     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8962                                         VT, *Store->getMemOperand()))
8963       return expandUnalignedStore(Store, DAG);
8964 
8965     return SDValue();
8966   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8967     switch (Subtarget->getMaxPrivateElementSize()) {
8968     case 4:
8969       return scalarizeVectorStore(Store, DAG);
8970     case 8:
8971       if (NumElements > 2)
8972         return SplitVectorStore(Op, DAG);
8973       return SDValue();
8974     case 16:
8975       if (NumElements > 4 ||
8976           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8977         return SplitVectorStore(Op, DAG);
8978       return SDValue();
8979     default:
8980       llvm_unreachable("unsupported private_element_size");
8981     }
8982   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8983     // Use ds_write_b128 or ds_write_b96 when possible.
8984     if (Subtarget->hasDS96AndDS128() &&
8985         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8986          (VT.getStoreSize() == 12)) &&
8987         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8988                                            Store->getAlign()))
8989       return SDValue();
8990 
8991     if (NumElements > 2)
8992       return SplitVectorStore(Op, DAG);
8993 
8994     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8995     // address is negative, then the instruction is incorrectly treated as
8996     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8997     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8998     // store later in the SILoadStoreOptimizer.
8999     if (!Subtarget->hasUsableDSOffset() &&
9000         NumElements == 2 && VT.getStoreSize() == 8 &&
9001         Store->getAlignment() < 8) {
9002       return SplitVectorStore(Op, DAG);
9003     }
9004 
9005     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9006                                         VT, *Store->getMemOperand())) {
9007       if (VT.isVector())
9008         return SplitVectorStore(Op, DAG);
9009       return expandUnalignedStore(Store, DAG);
9010     }
9011 
9012     return SDValue();
9013   } else {
9014     llvm_unreachable("unhandled address space");
9015   }
9016 }
9017 
9018 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9019   SDLoc DL(Op);
9020   EVT VT = Op.getValueType();
9021   SDValue Arg = Op.getOperand(0);
9022   SDValue TrigVal;
9023 
9024   // Propagate fast-math flags so that the multiply we introduce can be folded
9025   // if Arg is already the result of a multiply by constant.
9026   auto Flags = Op->getFlags();
9027 
9028   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9029 
9030   if (Subtarget->hasTrigReducedRange()) {
9031     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9032     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9033   } else {
9034     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9035   }
9036 
9037   switch (Op.getOpcode()) {
9038   case ISD::FCOS:
9039     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9040   case ISD::FSIN:
9041     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9042   default:
9043     llvm_unreachable("Wrong trig opcode");
9044   }
9045 }
9046 
9047 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9048   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9049   assert(AtomicNode->isCompareAndSwap());
9050   unsigned AS = AtomicNode->getAddressSpace();
9051 
9052   // No custom lowering required for local address space
9053   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9054     return Op;
9055 
9056   // Non-local address space requires custom lowering for atomic compare
9057   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9058   SDLoc DL(Op);
9059   SDValue ChainIn = Op.getOperand(0);
9060   SDValue Addr = Op.getOperand(1);
9061   SDValue Old = Op.getOperand(2);
9062   SDValue New = Op.getOperand(3);
9063   EVT VT = Op.getValueType();
9064   MVT SimpleVT = VT.getSimpleVT();
9065   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9066 
9067   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9068   SDValue Ops[] = { ChainIn, Addr, NewOld };
9069 
9070   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9071                                  Ops, VT, AtomicNode->getMemOperand());
9072 }
9073 
9074 //===----------------------------------------------------------------------===//
9075 // Custom DAG optimizations
9076 //===----------------------------------------------------------------------===//
9077 
9078 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9079                                                      DAGCombinerInfo &DCI) const {
9080   EVT VT = N->getValueType(0);
9081   EVT ScalarVT = VT.getScalarType();
9082   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9083     return SDValue();
9084 
9085   SelectionDAG &DAG = DCI.DAG;
9086   SDLoc DL(N);
9087 
9088   SDValue Src = N->getOperand(0);
9089   EVT SrcVT = Src.getValueType();
9090 
9091   // TODO: We could try to match extracting the higher bytes, which would be
9092   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9093   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9094   // about in practice.
9095   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9096     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9097       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9098       DCI.AddToWorklist(Cvt.getNode());
9099 
9100       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9101       if (ScalarVT != MVT::f32) {
9102         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9103                           DAG.getTargetConstant(0, DL, MVT::i32));
9104       }
9105       return Cvt;
9106     }
9107   }
9108 
9109   return SDValue();
9110 }
9111 
9112 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9113 
9114 // This is a variant of
9115 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9116 //
9117 // The normal DAG combiner will do this, but only if the add has one use since
9118 // that would increase the number of instructions.
9119 //
9120 // This prevents us from seeing a constant offset that can be folded into a
9121 // memory instruction's addressing mode. If we know the resulting add offset of
9122 // a pointer can be folded into an addressing offset, we can replace the pointer
9123 // operand with the add of new constant offset. This eliminates one of the uses,
9124 // and may allow the remaining use to also be simplified.
9125 //
9126 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9127                                                unsigned AddrSpace,
9128                                                EVT MemVT,
9129                                                DAGCombinerInfo &DCI) const {
9130   SDValue N0 = N->getOperand(0);
9131   SDValue N1 = N->getOperand(1);
9132 
9133   // We only do this to handle cases where it's profitable when there are
9134   // multiple uses of the add, so defer to the standard combine.
9135   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9136       N0->hasOneUse())
9137     return SDValue();
9138 
9139   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9140   if (!CN1)
9141     return SDValue();
9142 
9143   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9144   if (!CAdd)
9145     return SDValue();
9146 
9147   // If the resulting offset is too large, we can't fold it into the addressing
9148   // mode offset.
9149   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9150   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9151 
9152   AddrMode AM;
9153   AM.HasBaseReg = true;
9154   AM.BaseOffs = Offset.getSExtValue();
9155   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9156     return SDValue();
9157 
9158   SelectionDAG &DAG = DCI.DAG;
9159   SDLoc SL(N);
9160   EVT VT = N->getValueType(0);
9161 
9162   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9163   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9164 
9165   SDNodeFlags Flags;
9166   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9167                           (N0.getOpcode() == ISD::OR ||
9168                            N0->getFlags().hasNoUnsignedWrap()));
9169 
9170   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9171 }
9172 
9173 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9174 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9175 /// specific intrinsic, but they all place the pointer operand first.
9176 static unsigned getBasePtrIndex(const MemSDNode *N) {
9177   switch (N->getOpcode()) {
9178   case ISD::STORE:
9179   case ISD::INTRINSIC_W_CHAIN:
9180   case ISD::INTRINSIC_VOID:
9181     return 2;
9182   default:
9183     return 1;
9184   }
9185 }
9186 
9187 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9188                                                   DAGCombinerInfo &DCI) const {
9189   SelectionDAG &DAG = DCI.DAG;
9190   SDLoc SL(N);
9191 
9192   unsigned PtrIdx = getBasePtrIndex(N);
9193   SDValue Ptr = N->getOperand(PtrIdx);
9194 
9195   // TODO: We could also do this for multiplies.
9196   if (Ptr.getOpcode() == ISD::SHL) {
9197     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9198                                           N->getMemoryVT(), DCI);
9199     if (NewPtr) {
9200       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9201 
9202       NewOps[PtrIdx] = NewPtr;
9203       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9204     }
9205   }
9206 
9207   return SDValue();
9208 }
9209 
9210 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9211   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9212          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9213          (Opc == ISD::XOR && Val == 0);
9214 }
9215 
9216 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9217 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9218 // integer combine opportunities since most 64-bit operations are decomposed
9219 // this way.  TODO: We won't want this for SALU especially if it is an inline
9220 // immediate.
9221 SDValue SITargetLowering::splitBinaryBitConstantOp(
9222   DAGCombinerInfo &DCI,
9223   const SDLoc &SL,
9224   unsigned Opc, SDValue LHS,
9225   const ConstantSDNode *CRHS) const {
9226   uint64_t Val = CRHS->getZExtValue();
9227   uint32_t ValLo = Lo_32(Val);
9228   uint32_t ValHi = Hi_32(Val);
9229   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9230 
9231     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9232          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9233         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9234     // If we need to materialize a 64-bit immediate, it will be split up later
9235     // anyway. Avoid creating the harder to understand 64-bit immediate
9236     // materialization.
9237     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9238   }
9239 
9240   return SDValue();
9241 }
9242 
9243 // Returns true if argument is a boolean value which is not serialized into
9244 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9245 static bool isBoolSGPR(SDValue V) {
9246   if (V.getValueType() != MVT::i1)
9247     return false;
9248   switch (V.getOpcode()) {
9249   default:
9250     break;
9251   case ISD::SETCC:
9252   case AMDGPUISD::FP_CLASS:
9253     return true;
9254   case ISD::AND:
9255   case ISD::OR:
9256   case ISD::XOR:
9257     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9258   }
9259   return false;
9260 }
9261 
9262 // If a constant has all zeroes or all ones within each byte return it.
9263 // Otherwise return 0.
9264 static uint32_t getConstantPermuteMask(uint32_t C) {
9265   // 0xff for any zero byte in the mask
9266   uint32_t ZeroByteMask = 0;
9267   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9268   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9269   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9270   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9271   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9272   if ((NonZeroByteMask & C) != NonZeroByteMask)
9273     return 0; // Partial bytes selected.
9274   return C;
9275 }
9276 
9277 // Check if a node selects whole bytes from its operand 0 starting at a byte
9278 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9279 // or -1 if not succeeded.
9280 // Note byte select encoding:
9281 // value 0-3 selects corresponding source byte;
9282 // value 0xc selects zero;
9283 // value 0xff selects 0xff.
9284 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9285   assert(V.getValueSizeInBits() == 32);
9286 
9287   if (V.getNumOperands() != 2)
9288     return ~0;
9289 
9290   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9291   if (!N1)
9292     return ~0;
9293 
9294   uint32_t C = N1->getZExtValue();
9295 
9296   switch (V.getOpcode()) {
9297   default:
9298     break;
9299   case ISD::AND:
9300     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9301       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9302     }
9303     break;
9304 
9305   case ISD::OR:
9306     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9307       return (0x03020100 & ~ConstMask) | ConstMask;
9308     }
9309     break;
9310 
9311   case ISD::SHL:
9312     if (C % 8)
9313       return ~0;
9314 
9315     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9316 
9317   case ISD::SRL:
9318     if (C % 8)
9319       return ~0;
9320 
9321     return uint32_t(0x0c0c0c0c03020100ull >> C);
9322   }
9323 
9324   return ~0;
9325 }
9326 
9327 SDValue SITargetLowering::performAndCombine(SDNode *N,
9328                                             DAGCombinerInfo &DCI) const {
9329   if (DCI.isBeforeLegalize())
9330     return SDValue();
9331 
9332   SelectionDAG &DAG = DCI.DAG;
9333   EVT VT = N->getValueType(0);
9334   SDValue LHS = N->getOperand(0);
9335   SDValue RHS = N->getOperand(1);
9336 
9337 
9338   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9339   if (VT == MVT::i64 && CRHS) {
9340     if (SDValue Split
9341         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9342       return Split;
9343   }
9344 
9345   if (CRHS && VT == MVT::i32) {
9346     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9347     // nb = number of trailing zeroes in mask
9348     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9349     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9350     uint64_t Mask = CRHS->getZExtValue();
9351     unsigned Bits = countPopulation(Mask);
9352     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9353         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9354       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9355         unsigned Shift = CShift->getZExtValue();
9356         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9357         unsigned Offset = NB + Shift;
9358         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9359           SDLoc SL(N);
9360           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9361                                     LHS->getOperand(0),
9362                                     DAG.getConstant(Offset, SL, MVT::i32),
9363                                     DAG.getConstant(Bits, SL, MVT::i32));
9364           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9365           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9366                                     DAG.getValueType(NarrowVT));
9367           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9368                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9369           return Shl;
9370         }
9371       }
9372     }
9373 
9374     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9375     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9376         isa<ConstantSDNode>(LHS.getOperand(2))) {
9377       uint32_t Sel = getConstantPermuteMask(Mask);
9378       if (!Sel)
9379         return SDValue();
9380 
9381       // Select 0xc for all zero bytes
9382       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9383       SDLoc DL(N);
9384       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9385                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9386     }
9387   }
9388 
9389   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9390   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9391   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9392     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9393     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9394 
9395     SDValue X = LHS.getOperand(0);
9396     SDValue Y = RHS.getOperand(0);
9397     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9398       return SDValue();
9399 
9400     if (LCC == ISD::SETO) {
9401       if (X != LHS.getOperand(1))
9402         return SDValue();
9403 
9404       if (RCC == ISD::SETUNE) {
9405         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9406         if (!C1 || !C1->isInfinity() || C1->isNegative())
9407           return SDValue();
9408 
9409         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9410                               SIInstrFlags::N_SUBNORMAL |
9411                               SIInstrFlags::N_ZERO |
9412                               SIInstrFlags::P_ZERO |
9413                               SIInstrFlags::P_SUBNORMAL |
9414                               SIInstrFlags::P_NORMAL;
9415 
9416         static_assert(((~(SIInstrFlags::S_NAN |
9417                           SIInstrFlags::Q_NAN |
9418                           SIInstrFlags::N_INFINITY |
9419                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9420                       "mask not equal");
9421 
9422         SDLoc DL(N);
9423         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9424                            X, DAG.getConstant(Mask, DL, MVT::i32));
9425       }
9426     }
9427   }
9428 
9429   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9430     std::swap(LHS, RHS);
9431 
9432   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9433       RHS.hasOneUse()) {
9434     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9435     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9436     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9437     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9438     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9439         (RHS.getOperand(0) == LHS.getOperand(0) &&
9440          LHS.getOperand(0) == LHS.getOperand(1))) {
9441       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9442       unsigned NewMask = LCC == ISD::SETO ?
9443         Mask->getZExtValue() & ~OrdMask :
9444         Mask->getZExtValue() & OrdMask;
9445 
9446       SDLoc DL(N);
9447       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9448                          DAG.getConstant(NewMask, DL, MVT::i32));
9449     }
9450   }
9451 
9452   if (VT == MVT::i32 &&
9453       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9454     // and x, (sext cc from i1) => select cc, x, 0
9455     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9456       std::swap(LHS, RHS);
9457     if (isBoolSGPR(RHS.getOperand(0)))
9458       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9459                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9460   }
9461 
9462   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9463   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9464   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9465       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9466     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9467     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9468     if (LHSMask != ~0u && RHSMask != ~0u) {
9469       // Canonicalize the expression in an attempt to have fewer unique masks
9470       // and therefore fewer registers used to hold the masks.
9471       if (LHSMask > RHSMask) {
9472         std::swap(LHSMask, RHSMask);
9473         std::swap(LHS, RHS);
9474       }
9475 
9476       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9477       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9478       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9479       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9480 
9481       // Check of we need to combine values from two sources within a byte.
9482       if (!(LHSUsedLanes & RHSUsedLanes) &&
9483           // If we select high and lower word keep it for SDWA.
9484           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9485           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9486         // Each byte in each mask is either selector mask 0-3, or has higher
9487         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9488         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9489         // mask which is not 0xff wins. By anding both masks we have a correct
9490         // result except that 0x0c shall be corrected to give 0x0c only.
9491         uint32_t Mask = LHSMask & RHSMask;
9492         for (unsigned I = 0; I < 32; I += 8) {
9493           uint32_t ByteSel = 0xff << I;
9494           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9495             Mask &= (0x0c << I) & 0xffffffff;
9496         }
9497 
9498         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9499         // or 0x0c.
9500         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9501         SDLoc DL(N);
9502 
9503         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9504                            LHS.getOperand(0), RHS.getOperand(0),
9505                            DAG.getConstant(Sel, DL, MVT::i32));
9506       }
9507     }
9508   }
9509 
9510   return SDValue();
9511 }
9512 
9513 SDValue SITargetLowering::performOrCombine(SDNode *N,
9514                                            DAGCombinerInfo &DCI) const {
9515   SelectionDAG &DAG = DCI.DAG;
9516   SDValue LHS = N->getOperand(0);
9517   SDValue RHS = N->getOperand(1);
9518 
9519   EVT VT = N->getValueType(0);
9520   if (VT == MVT::i1) {
9521     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9522     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9523         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9524       SDValue Src = LHS.getOperand(0);
9525       if (Src != RHS.getOperand(0))
9526         return SDValue();
9527 
9528       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9529       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9530       if (!CLHS || !CRHS)
9531         return SDValue();
9532 
9533       // Only 10 bits are used.
9534       static const uint32_t MaxMask = 0x3ff;
9535 
9536       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9537       SDLoc DL(N);
9538       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9539                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9540     }
9541 
9542     return SDValue();
9543   }
9544 
9545   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9546   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9547       LHS.getOpcode() == AMDGPUISD::PERM &&
9548       isa<ConstantSDNode>(LHS.getOperand(2))) {
9549     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9550     if (!Sel)
9551       return SDValue();
9552 
9553     Sel |= LHS.getConstantOperandVal(2);
9554     SDLoc DL(N);
9555     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9556                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9557   }
9558 
9559   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9560   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9561   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9562       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9563     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9564     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9565     if (LHSMask != ~0u && RHSMask != ~0u) {
9566       // Canonicalize the expression in an attempt to have fewer unique masks
9567       // and therefore fewer registers used to hold the masks.
9568       if (LHSMask > RHSMask) {
9569         std::swap(LHSMask, RHSMask);
9570         std::swap(LHS, RHS);
9571       }
9572 
9573       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9574       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9575       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9576       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9577 
9578       // Check of we need to combine values from two sources within a byte.
9579       if (!(LHSUsedLanes & RHSUsedLanes) &&
9580           // If we select high and lower word keep it for SDWA.
9581           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9582           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9583         // Kill zero bytes selected by other mask. Zero value is 0xc.
9584         LHSMask &= ~RHSUsedLanes;
9585         RHSMask &= ~LHSUsedLanes;
9586         // Add 4 to each active LHS lane
9587         LHSMask |= LHSUsedLanes & 0x04040404;
9588         // Combine masks
9589         uint32_t Sel = LHSMask | RHSMask;
9590         SDLoc DL(N);
9591 
9592         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9593                            LHS.getOperand(0), RHS.getOperand(0),
9594                            DAG.getConstant(Sel, DL, MVT::i32));
9595       }
9596     }
9597   }
9598 
9599   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9600     return SDValue();
9601 
9602   // TODO: This could be a generic combine with a predicate for extracting the
9603   // high half of an integer being free.
9604 
9605   // (or i64:x, (zero_extend i32:y)) ->
9606   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9607   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9608       RHS.getOpcode() != ISD::ZERO_EXTEND)
9609     std::swap(LHS, RHS);
9610 
9611   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9612     SDValue ExtSrc = RHS.getOperand(0);
9613     EVT SrcVT = ExtSrc.getValueType();
9614     if (SrcVT == MVT::i32) {
9615       SDLoc SL(N);
9616       SDValue LowLHS, HiBits;
9617       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9618       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9619 
9620       DCI.AddToWorklist(LowOr.getNode());
9621       DCI.AddToWorklist(HiBits.getNode());
9622 
9623       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9624                                 LowOr, HiBits);
9625       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9626     }
9627   }
9628 
9629   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9630   if (CRHS) {
9631     if (SDValue Split
9632           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9633                                      N->getOperand(0), CRHS))
9634       return Split;
9635   }
9636 
9637   return SDValue();
9638 }
9639 
9640 SDValue SITargetLowering::performXorCombine(SDNode *N,
9641                                             DAGCombinerInfo &DCI) const {
9642   EVT VT = N->getValueType(0);
9643   if (VT != MVT::i64)
9644     return SDValue();
9645 
9646   SDValue LHS = N->getOperand(0);
9647   SDValue RHS = N->getOperand(1);
9648 
9649   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9650   if (CRHS) {
9651     if (SDValue Split
9652           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9653       return Split;
9654   }
9655 
9656   return SDValue();
9657 }
9658 
9659 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9660                                                    DAGCombinerInfo &DCI) const {
9661   if (!Subtarget->has16BitInsts() ||
9662       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9663     return SDValue();
9664 
9665   EVT VT = N->getValueType(0);
9666   if (VT != MVT::i32)
9667     return SDValue();
9668 
9669   SDValue Src = N->getOperand(0);
9670   if (Src.getValueType() != MVT::i16)
9671     return SDValue();
9672 
9673   return SDValue();
9674 }
9675 
9676 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9677                                                         DAGCombinerInfo &DCI)
9678                                                         const {
9679   SDValue Src = N->getOperand(0);
9680   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9681 
9682   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9683       VTSign->getVT() == MVT::i8) ||
9684       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9685       VTSign->getVT() == MVT::i16)) &&
9686       Src.hasOneUse()) {
9687     auto *M = cast<MemSDNode>(Src);
9688     SDValue Ops[] = {
9689       Src.getOperand(0), // Chain
9690       Src.getOperand(1), // rsrc
9691       Src.getOperand(2), // vindex
9692       Src.getOperand(3), // voffset
9693       Src.getOperand(4), // soffset
9694       Src.getOperand(5), // offset
9695       Src.getOperand(6),
9696       Src.getOperand(7)
9697     };
9698     // replace with BUFFER_LOAD_BYTE/SHORT
9699     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9700                                          Src.getOperand(0).getValueType());
9701     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9702                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9703     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9704                                                           ResList,
9705                                                           Ops, M->getMemoryVT(),
9706                                                           M->getMemOperand());
9707     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9708                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9709   }
9710   return SDValue();
9711 }
9712 
9713 SDValue SITargetLowering::performClassCombine(SDNode *N,
9714                                               DAGCombinerInfo &DCI) const {
9715   SelectionDAG &DAG = DCI.DAG;
9716   SDValue Mask = N->getOperand(1);
9717 
9718   // fp_class x, 0 -> false
9719   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9720     if (CMask->isZero())
9721       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9722   }
9723 
9724   if (N->getOperand(0).isUndef())
9725     return DAG.getUNDEF(MVT::i1);
9726 
9727   return SDValue();
9728 }
9729 
9730 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9731                                             DAGCombinerInfo &DCI) const {
9732   EVT VT = N->getValueType(0);
9733   SDValue N0 = N->getOperand(0);
9734 
9735   if (N0.isUndef())
9736     return N0;
9737 
9738   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9739                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9740     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9741                            N->getFlags());
9742   }
9743 
9744   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9745     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9746                            N0.getOperand(0), N->getFlags());
9747   }
9748 
9749   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9750 }
9751 
9752 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9753                                        unsigned MaxDepth) const {
9754   unsigned Opcode = Op.getOpcode();
9755   if (Opcode == ISD::FCANONICALIZE)
9756     return true;
9757 
9758   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9759     auto F = CFP->getValueAPF();
9760     if (F.isNaN() && F.isSignaling())
9761       return false;
9762     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9763   }
9764 
9765   // If source is a result of another standard FP operation it is already in
9766   // canonical form.
9767   if (MaxDepth == 0)
9768     return false;
9769 
9770   switch (Opcode) {
9771   // These will flush denorms if required.
9772   case ISD::FADD:
9773   case ISD::FSUB:
9774   case ISD::FMUL:
9775   case ISD::FCEIL:
9776   case ISD::FFLOOR:
9777   case ISD::FMA:
9778   case ISD::FMAD:
9779   case ISD::FSQRT:
9780   case ISD::FDIV:
9781   case ISD::FREM:
9782   case ISD::FP_ROUND:
9783   case ISD::FP_EXTEND:
9784   case AMDGPUISD::FMUL_LEGACY:
9785   case AMDGPUISD::FMAD_FTZ:
9786   case AMDGPUISD::RCP:
9787   case AMDGPUISD::RSQ:
9788   case AMDGPUISD::RSQ_CLAMP:
9789   case AMDGPUISD::RCP_LEGACY:
9790   case AMDGPUISD::RCP_IFLAG:
9791   case AMDGPUISD::DIV_SCALE:
9792   case AMDGPUISD::DIV_FMAS:
9793   case AMDGPUISD::DIV_FIXUP:
9794   case AMDGPUISD::FRACT:
9795   case AMDGPUISD::LDEXP:
9796   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9797   case AMDGPUISD::CVT_F32_UBYTE0:
9798   case AMDGPUISD::CVT_F32_UBYTE1:
9799   case AMDGPUISD::CVT_F32_UBYTE2:
9800   case AMDGPUISD::CVT_F32_UBYTE3:
9801     return true;
9802 
9803   // It can/will be lowered or combined as a bit operation.
9804   // Need to check their input recursively to handle.
9805   case ISD::FNEG:
9806   case ISD::FABS:
9807   case ISD::FCOPYSIGN:
9808     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9809 
9810   case ISD::FSIN:
9811   case ISD::FCOS:
9812   case ISD::FSINCOS:
9813     return Op.getValueType().getScalarType() != MVT::f16;
9814 
9815   case ISD::FMINNUM:
9816   case ISD::FMAXNUM:
9817   case ISD::FMINNUM_IEEE:
9818   case ISD::FMAXNUM_IEEE:
9819   case AMDGPUISD::CLAMP:
9820   case AMDGPUISD::FMED3:
9821   case AMDGPUISD::FMAX3:
9822   case AMDGPUISD::FMIN3: {
9823     // FIXME: Shouldn't treat the generic operations different based these.
9824     // However, we aren't really required to flush the result from
9825     // minnum/maxnum..
9826 
9827     // snans will be quieted, so we only need to worry about denormals.
9828     if (Subtarget->supportsMinMaxDenormModes() ||
9829         denormalsEnabledForType(DAG, Op.getValueType()))
9830       return true;
9831 
9832     // Flushing may be required.
9833     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9834     // targets need to check their input recursively.
9835 
9836     // FIXME: Does this apply with clamp? It's implemented with max.
9837     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9838       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9839         return false;
9840     }
9841 
9842     return true;
9843   }
9844   case ISD::SELECT: {
9845     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9846            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9847   }
9848   case ISD::BUILD_VECTOR: {
9849     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9850       SDValue SrcOp = Op.getOperand(i);
9851       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9852         return false;
9853     }
9854 
9855     return true;
9856   }
9857   case ISD::EXTRACT_VECTOR_ELT:
9858   case ISD::EXTRACT_SUBVECTOR: {
9859     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9860   }
9861   case ISD::INSERT_VECTOR_ELT: {
9862     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9863            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9864   }
9865   case ISD::UNDEF:
9866     // Could be anything.
9867     return false;
9868 
9869   case ISD::BITCAST:
9870     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9871   case ISD::TRUNCATE: {
9872     // Hack round the mess we make when legalizing extract_vector_elt
9873     if (Op.getValueType() == MVT::i16) {
9874       SDValue TruncSrc = Op.getOperand(0);
9875       if (TruncSrc.getValueType() == MVT::i32 &&
9876           TruncSrc.getOpcode() == ISD::BITCAST &&
9877           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9878         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9879       }
9880     }
9881     return false;
9882   }
9883   case ISD::INTRINSIC_WO_CHAIN: {
9884     unsigned IntrinsicID
9885       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9886     // TODO: Handle more intrinsics
9887     switch (IntrinsicID) {
9888     case Intrinsic::amdgcn_cvt_pkrtz:
9889     case Intrinsic::amdgcn_cubeid:
9890     case Intrinsic::amdgcn_frexp_mant:
9891     case Intrinsic::amdgcn_fdot2:
9892     case Intrinsic::amdgcn_rcp:
9893     case Intrinsic::amdgcn_rsq:
9894     case Intrinsic::amdgcn_rsq_clamp:
9895     case Intrinsic::amdgcn_rcp_legacy:
9896     case Intrinsic::amdgcn_rsq_legacy:
9897     case Intrinsic::amdgcn_trig_preop:
9898       return true;
9899     default:
9900       break;
9901     }
9902 
9903     LLVM_FALLTHROUGH;
9904   }
9905   default:
9906     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9907            DAG.isKnownNeverSNaN(Op);
9908   }
9909 
9910   llvm_unreachable("invalid operation");
9911 }
9912 
9913 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9914                                        unsigned MaxDepth) const {
9915   MachineRegisterInfo &MRI = MF.getRegInfo();
9916   MachineInstr *MI = MRI.getVRegDef(Reg);
9917   unsigned Opcode = MI->getOpcode();
9918 
9919   if (Opcode == AMDGPU::G_FCANONICALIZE)
9920     return true;
9921 
9922   Optional<FPValueAndVReg> FCR;
9923   // Constant splat (can be padded with undef) or scalar constant.
9924   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9925     if (FCR->Value.isSignaling())
9926       return false;
9927     return !FCR->Value.isDenormal() ||
9928            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9929   }
9930 
9931   if (MaxDepth == 0)
9932     return false;
9933 
9934   switch (Opcode) {
9935   case AMDGPU::G_FMINNUM_IEEE:
9936   case AMDGPU::G_FMAXNUM_IEEE: {
9937     if (Subtarget->supportsMinMaxDenormModes() ||
9938         denormalsEnabledForType(MRI.getType(Reg), MF))
9939       return true;
9940     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9941       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9942         return false;
9943     return true;
9944   }
9945   default:
9946     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9947            isKnownNeverSNaN(Reg, MRI);
9948   }
9949 
9950   llvm_unreachable("invalid operation");
9951 }
9952 
9953 // Constant fold canonicalize.
9954 SDValue SITargetLowering::getCanonicalConstantFP(
9955   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9956   // Flush denormals to 0 if not enabled.
9957   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9958     return DAG.getConstantFP(0.0, SL, VT);
9959 
9960   if (C.isNaN()) {
9961     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9962     if (C.isSignaling()) {
9963       // Quiet a signaling NaN.
9964       // FIXME: Is this supposed to preserve payload bits?
9965       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9966     }
9967 
9968     // Make sure it is the canonical NaN bitpattern.
9969     //
9970     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9971     // immediate?
9972     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9973       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9974   }
9975 
9976   // Already canonical.
9977   return DAG.getConstantFP(C, SL, VT);
9978 }
9979 
9980 static bool vectorEltWillFoldAway(SDValue Op) {
9981   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9982 }
9983 
9984 SDValue SITargetLowering::performFCanonicalizeCombine(
9985   SDNode *N,
9986   DAGCombinerInfo &DCI) const {
9987   SelectionDAG &DAG = DCI.DAG;
9988   SDValue N0 = N->getOperand(0);
9989   EVT VT = N->getValueType(0);
9990 
9991   // fcanonicalize undef -> qnan
9992   if (N0.isUndef()) {
9993     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9994     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9995   }
9996 
9997   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9998     EVT VT = N->getValueType(0);
9999     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10000   }
10001 
10002   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10003   //                                                   (fcanonicalize k)
10004   //
10005   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10006 
10007   // TODO: This could be better with wider vectors that will be split to v2f16,
10008   // and to consider uses since there aren't that many packed operations.
10009   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10010       isTypeLegal(MVT::v2f16)) {
10011     SDLoc SL(N);
10012     SDValue NewElts[2];
10013     SDValue Lo = N0.getOperand(0);
10014     SDValue Hi = N0.getOperand(1);
10015     EVT EltVT = Lo.getValueType();
10016 
10017     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10018       for (unsigned I = 0; I != 2; ++I) {
10019         SDValue Op = N0.getOperand(I);
10020         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10021           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10022                                               CFP->getValueAPF());
10023         } else if (Op.isUndef()) {
10024           // Handled below based on what the other operand is.
10025           NewElts[I] = Op;
10026         } else {
10027           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10028         }
10029       }
10030 
10031       // If one half is undef, and one is constant, perfer a splat vector rather
10032       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10033       // cheaper to use and may be free with a packed operation.
10034       if (NewElts[0].isUndef()) {
10035         if (isa<ConstantFPSDNode>(NewElts[1]))
10036           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10037             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10038       }
10039 
10040       if (NewElts[1].isUndef()) {
10041         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10042           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10043       }
10044 
10045       return DAG.getBuildVector(VT, SL, NewElts);
10046     }
10047   }
10048 
10049   unsigned SrcOpc = N0.getOpcode();
10050 
10051   // If it's free to do so, push canonicalizes further up the source, which may
10052   // find a canonical source.
10053   //
10054   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10055   // sNaNs.
10056   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10057     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10058     if (CRHS && N0.hasOneUse()) {
10059       SDLoc SL(N);
10060       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10061                                    N0.getOperand(0));
10062       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10063       DCI.AddToWorklist(Canon0.getNode());
10064 
10065       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10066     }
10067   }
10068 
10069   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10070 }
10071 
10072 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10073   switch (Opc) {
10074   case ISD::FMAXNUM:
10075   case ISD::FMAXNUM_IEEE:
10076     return AMDGPUISD::FMAX3;
10077   case ISD::SMAX:
10078     return AMDGPUISD::SMAX3;
10079   case ISD::UMAX:
10080     return AMDGPUISD::UMAX3;
10081   case ISD::FMINNUM:
10082   case ISD::FMINNUM_IEEE:
10083     return AMDGPUISD::FMIN3;
10084   case ISD::SMIN:
10085     return AMDGPUISD::SMIN3;
10086   case ISD::UMIN:
10087     return AMDGPUISD::UMIN3;
10088   default:
10089     llvm_unreachable("Not a min/max opcode");
10090   }
10091 }
10092 
10093 SDValue SITargetLowering::performIntMed3ImmCombine(
10094   SelectionDAG &DAG, const SDLoc &SL,
10095   SDValue Op0, SDValue Op1, bool Signed) const {
10096   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10097   if (!K1)
10098     return SDValue();
10099 
10100   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10101   if (!K0)
10102     return SDValue();
10103 
10104   if (Signed) {
10105     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10106       return SDValue();
10107   } else {
10108     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10109       return SDValue();
10110   }
10111 
10112   EVT VT = K0->getValueType(0);
10113   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10114   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10115     return DAG.getNode(Med3Opc, SL, VT,
10116                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10117   }
10118 
10119   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10120   if (VT == MVT::i16) {
10121     MVT NVT = MVT::i32;
10122     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10123 
10124     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10125     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10126     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10127 
10128     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10129     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10130   }
10131 
10132   return SDValue();
10133 }
10134 
10135 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10136   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10137     return C;
10138 
10139   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10140     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10141       return C;
10142   }
10143 
10144   return nullptr;
10145 }
10146 
10147 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10148                                                   const SDLoc &SL,
10149                                                   SDValue Op0,
10150                                                   SDValue Op1) const {
10151   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10152   if (!K1)
10153     return SDValue();
10154 
10155   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10156   if (!K0)
10157     return SDValue();
10158 
10159   // Ordered >= (although NaN inputs should have folded away by now).
10160   if (K0->getValueAPF() > K1->getValueAPF())
10161     return SDValue();
10162 
10163   const MachineFunction &MF = DAG.getMachineFunction();
10164   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10165 
10166   // TODO: Check IEEE bit enabled?
10167   EVT VT = Op0.getValueType();
10168   if (Info->getMode().DX10Clamp) {
10169     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10170     // hardware fmed3 behavior converting to a min.
10171     // FIXME: Should this be allowing -0.0?
10172     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10173       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10174   }
10175 
10176   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10177   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10178     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10179     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10180     // then give the other result, which is different from med3 with a NaN
10181     // input.
10182     SDValue Var = Op0.getOperand(0);
10183     if (!DAG.isKnownNeverSNaN(Var))
10184       return SDValue();
10185 
10186     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10187 
10188     if ((!K0->hasOneUse() ||
10189          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10190         (!K1->hasOneUse() ||
10191          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10192       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10193                          Var, SDValue(K0, 0), SDValue(K1, 0));
10194     }
10195   }
10196 
10197   return SDValue();
10198 }
10199 
10200 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10201                                                DAGCombinerInfo &DCI) const {
10202   SelectionDAG &DAG = DCI.DAG;
10203 
10204   EVT VT = N->getValueType(0);
10205   unsigned Opc = N->getOpcode();
10206   SDValue Op0 = N->getOperand(0);
10207   SDValue Op1 = N->getOperand(1);
10208 
10209   // Only do this if the inner op has one use since this will just increases
10210   // register pressure for no benefit.
10211 
10212   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10213       !VT.isVector() &&
10214       (VT == MVT::i32 || VT == MVT::f32 ||
10215        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10216     // max(max(a, b), c) -> max3(a, b, c)
10217     // min(min(a, b), c) -> min3(a, b, c)
10218     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10219       SDLoc DL(N);
10220       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10221                          DL,
10222                          N->getValueType(0),
10223                          Op0.getOperand(0),
10224                          Op0.getOperand(1),
10225                          Op1);
10226     }
10227 
10228     // Try commuted.
10229     // max(a, max(b, c)) -> max3(a, b, c)
10230     // min(a, min(b, c)) -> min3(a, b, c)
10231     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10232       SDLoc DL(N);
10233       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10234                          DL,
10235                          N->getValueType(0),
10236                          Op0,
10237                          Op1.getOperand(0),
10238                          Op1.getOperand(1));
10239     }
10240   }
10241 
10242   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10243   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10244     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10245       return Med3;
10246   }
10247 
10248   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10249     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10250       return Med3;
10251   }
10252 
10253   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10254   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10255        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10256        (Opc == AMDGPUISD::FMIN_LEGACY &&
10257         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10258       (VT == MVT::f32 || VT == MVT::f64 ||
10259        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10260        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10261       Op0.hasOneUse()) {
10262     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10263       return Res;
10264   }
10265 
10266   return SDValue();
10267 }
10268 
10269 static bool isClampZeroToOne(SDValue A, SDValue B) {
10270   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10271     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10272       // FIXME: Should this be allowing -0.0?
10273       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10274              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10275     }
10276   }
10277 
10278   return false;
10279 }
10280 
10281 // FIXME: Should only worry about snans for version with chain.
10282 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10283                                               DAGCombinerInfo &DCI) const {
10284   EVT VT = N->getValueType(0);
10285   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10286   // NaNs. With a NaN input, the order of the operands may change the result.
10287 
10288   SelectionDAG &DAG = DCI.DAG;
10289   SDLoc SL(N);
10290 
10291   SDValue Src0 = N->getOperand(0);
10292   SDValue Src1 = N->getOperand(1);
10293   SDValue Src2 = N->getOperand(2);
10294 
10295   if (isClampZeroToOne(Src0, Src1)) {
10296     // const_a, const_b, x -> clamp is safe in all cases including signaling
10297     // nans.
10298     // FIXME: Should this be allowing -0.0?
10299     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10300   }
10301 
10302   const MachineFunction &MF = DAG.getMachineFunction();
10303   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10304 
10305   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10306   // handling no dx10-clamp?
10307   if (Info->getMode().DX10Clamp) {
10308     // If NaNs is clamped to 0, we are free to reorder the inputs.
10309 
10310     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10311       std::swap(Src0, Src1);
10312 
10313     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10314       std::swap(Src1, Src2);
10315 
10316     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10317       std::swap(Src0, Src1);
10318 
10319     if (isClampZeroToOne(Src1, Src2))
10320       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10321   }
10322 
10323   return SDValue();
10324 }
10325 
10326 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10327                                                  DAGCombinerInfo &DCI) const {
10328   SDValue Src0 = N->getOperand(0);
10329   SDValue Src1 = N->getOperand(1);
10330   if (Src0.isUndef() && Src1.isUndef())
10331     return DCI.DAG.getUNDEF(N->getValueType(0));
10332   return SDValue();
10333 }
10334 
10335 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10336 // expanded into a set of cmp/select instructions.
10337 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10338                                                 unsigned NumElem,
10339                                                 bool IsDivergentIdx) {
10340   if (UseDivergentRegisterIndexing)
10341     return false;
10342 
10343   unsigned VecSize = EltSize * NumElem;
10344 
10345   // Sub-dword vectors of size 2 dword or less have better implementation.
10346   if (VecSize <= 64 && EltSize < 32)
10347     return false;
10348 
10349   // Always expand the rest of sub-dword instructions, otherwise it will be
10350   // lowered via memory.
10351   if (EltSize < 32)
10352     return true;
10353 
10354   // Always do this if var-idx is divergent, otherwise it will become a loop.
10355   if (IsDivergentIdx)
10356     return true;
10357 
10358   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10359   unsigned NumInsts = NumElem /* Number of compares */ +
10360                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10361   return NumInsts <= 16;
10362 }
10363 
10364 static bool shouldExpandVectorDynExt(SDNode *N) {
10365   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10366   if (isa<ConstantSDNode>(Idx))
10367     return false;
10368 
10369   SDValue Vec = N->getOperand(0);
10370   EVT VecVT = Vec.getValueType();
10371   EVT EltVT = VecVT.getVectorElementType();
10372   unsigned EltSize = EltVT.getSizeInBits();
10373   unsigned NumElem = VecVT.getVectorNumElements();
10374 
10375   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10376                                                     Idx->isDivergent());
10377 }
10378 
10379 SDValue SITargetLowering::performExtractVectorEltCombine(
10380   SDNode *N, DAGCombinerInfo &DCI) const {
10381   SDValue Vec = N->getOperand(0);
10382   SelectionDAG &DAG = DCI.DAG;
10383 
10384   EVT VecVT = Vec.getValueType();
10385   EVT EltVT = VecVT.getVectorElementType();
10386 
10387   if ((Vec.getOpcode() == ISD::FNEG ||
10388        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10389     SDLoc SL(N);
10390     EVT EltVT = N->getValueType(0);
10391     SDValue Idx = N->getOperand(1);
10392     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10393                               Vec.getOperand(0), Idx);
10394     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10395   }
10396 
10397   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10398   //    =>
10399   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10400   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10401   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10402   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10403     SDLoc SL(N);
10404     EVT EltVT = N->getValueType(0);
10405     SDValue Idx = N->getOperand(1);
10406     unsigned Opc = Vec.getOpcode();
10407 
10408     switch(Opc) {
10409     default:
10410       break;
10411       // TODO: Support other binary operations.
10412     case ISD::FADD:
10413     case ISD::FSUB:
10414     case ISD::FMUL:
10415     case ISD::ADD:
10416     case ISD::UMIN:
10417     case ISD::UMAX:
10418     case ISD::SMIN:
10419     case ISD::SMAX:
10420     case ISD::FMAXNUM:
10421     case ISD::FMINNUM:
10422     case ISD::FMAXNUM_IEEE:
10423     case ISD::FMINNUM_IEEE: {
10424       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10425                                  Vec.getOperand(0), Idx);
10426       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10427                                  Vec.getOperand(1), Idx);
10428 
10429       DCI.AddToWorklist(Elt0.getNode());
10430       DCI.AddToWorklist(Elt1.getNode());
10431       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10432     }
10433     }
10434   }
10435 
10436   unsigned VecSize = VecVT.getSizeInBits();
10437   unsigned EltSize = EltVT.getSizeInBits();
10438 
10439   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10440   if (::shouldExpandVectorDynExt(N)) {
10441     SDLoc SL(N);
10442     SDValue Idx = N->getOperand(1);
10443     SDValue V;
10444     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10445       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10446       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10447       if (I == 0)
10448         V = Elt;
10449       else
10450         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10451     }
10452     return V;
10453   }
10454 
10455   if (!DCI.isBeforeLegalize())
10456     return SDValue();
10457 
10458   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10459   // elements. This exposes more load reduction opportunities by replacing
10460   // multiple small extract_vector_elements with a single 32-bit extract.
10461   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10462   if (isa<MemSDNode>(Vec) &&
10463       EltSize <= 16 &&
10464       EltVT.isByteSized() &&
10465       VecSize > 32 &&
10466       VecSize % 32 == 0 &&
10467       Idx) {
10468     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10469 
10470     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10471     unsigned EltIdx = BitIndex / 32;
10472     unsigned LeftoverBitIdx = BitIndex % 32;
10473     SDLoc SL(N);
10474 
10475     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10476     DCI.AddToWorklist(Cast.getNode());
10477 
10478     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10479                               DAG.getConstant(EltIdx, SL, MVT::i32));
10480     DCI.AddToWorklist(Elt.getNode());
10481     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10482                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10483     DCI.AddToWorklist(Srl.getNode());
10484 
10485     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10486     DCI.AddToWorklist(Trunc.getNode());
10487     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10488   }
10489 
10490   return SDValue();
10491 }
10492 
10493 SDValue
10494 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10495                                                 DAGCombinerInfo &DCI) const {
10496   SDValue Vec = N->getOperand(0);
10497   SDValue Idx = N->getOperand(2);
10498   EVT VecVT = Vec.getValueType();
10499   EVT EltVT = VecVT.getVectorElementType();
10500 
10501   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10502   // => BUILD_VECTOR n x select (e, const-idx)
10503   if (!::shouldExpandVectorDynExt(N))
10504     return SDValue();
10505 
10506   SelectionDAG &DAG = DCI.DAG;
10507   SDLoc SL(N);
10508   SDValue Ins = N->getOperand(1);
10509   EVT IdxVT = Idx.getValueType();
10510 
10511   SmallVector<SDValue, 16> Ops;
10512   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10513     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10514     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10515     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10516     Ops.push_back(V);
10517   }
10518 
10519   return DAG.getBuildVector(VecVT, SL, Ops);
10520 }
10521 
10522 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10523                                           const SDNode *N0,
10524                                           const SDNode *N1) const {
10525   EVT VT = N0->getValueType(0);
10526 
10527   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10528   // support denormals ever.
10529   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10530        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10531         getSubtarget()->hasMadF16())) &&
10532        isOperationLegal(ISD::FMAD, VT))
10533     return ISD::FMAD;
10534 
10535   const TargetOptions &Options = DAG.getTarget().Options;
10536   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10537        (N0->getFlags().hasAllowContract() &&
10538         N1->getFlags().hasAllowContract())) &&
10539       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10540     return ISD::FMA;
10541   }
10542 
10543   return 0;
10544 }
10545 
10546 // For a reassociatable opcode perform:
10547 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10548 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10549                                                SelectionDAG &DAG) const {
10550   EVT VT = N->getValueType(0);
10551   if (VT != MVT::i32 && VT != MVT::i64)
10552     return SDValue();
10553 
10554   unsigned Opc = N->getOpcode();
10555   SDValue Op0 = N->getOperand(0);
10556   SDValue Op1 = N->getOperand(1);
10557 
10558   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10559     return SDValue();
10560 
10561   if (Op0->isDivergent())
10562     std::swap(Op0, Op1);
10563 
10564   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10565     return SDValue();
10566 
10567   SDValue Op2 = Op1.getOperand(1);
10568   Op1 = Op1.getOperand(0);
10569   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10570     return SDValue();
10571 
10572   if (Op1->isDivergent())
10573     std::swap(Op1, Op2);
10574 
10575   // If either operand is constant this will conflict with
10576   // DAGCombiner::ReassociateOps().
10577   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10578       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10579     return SDValue();
10580 
10581   SDLoc SL(N);
10582   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10583   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10584 }
10585 
10586 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10587                            EVT VT,
10588                            SDValue N0, SDValue N1, SDValue N2,
10589                            bool Signed) {
10590   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10591   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10592   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10593   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10594 }
10595 
10596 SDValue SITargetLowering::performAddCombine(SDNode *N,
10597                                             DAGCombinerInfo &DCI) const {
10598   SelectionDAG &DAG = DCI.DAG;
10599   EVT VT = N->getValueType(0);
10600   SDLoc SL(N);
10601   SDValue LHS = N->getOperand(0);
10602   SDValue RHS = N->getOperand(1);
10603 
10604   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10605       && Subtarget->hasMad64_32() &&
10606       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10607       VT.getScalarSizeInBits() <= 64) {
10608     if (LHS.getOpcode() != ISD::MUL)
10609       std::swap(LHS, RHS);
10610 
10611     SDValue MulLHS = LHS.getOperand(0);
10612     SDValue MulRHS = LHS.getOperand(1);
10613     SDValue AddRHS = RHS;
10614 
10615     // TODO: Maybe restrict if SGPR inputs.
10616     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10617         numBitsUnsigned(MulRHS, DAG) <= 32) {
10618       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10619       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10620       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10621       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10622     }
10623 
10624     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10625       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10626       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10627       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10628       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10629     }
10630 
10631     return SDValue();
10632   }
10633 
10634   if (SDValue V = reassociateScalarOps(N, DAG)) {
10635     return V;
10636   }
10637 
10638   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10639     return SDValue();
10640 
10641   // add x, zext (setcc) => addcarry x, 0, setcc
10642   // add x, sext (setcc) => subcarry x, 0, setcc
10643   unsigned Opc = LHS.getOpcode();
10644   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10645       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10646     std::swap(RHS, LHS);
10647 
10648   Opc = RHS.getOpcode();
10649   switch (Opc) {
10650   default: break;
10651   case ISD::ZERO_EXTEND:
10652   case ISD::SIGN_EXTEND:
10653   case ISD::ANY_EXTEND: {
10654     auto Cond = RHS.getOperand(0);
10655     // If this won't be a real VOPC output, we would still need to insert an
10656     // extra instruction anyway.
10657     if (!isBoolSGPR(Cond))
10658       break;
10659     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10660     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10661     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10662     return DAG.getNode(Opc, SL, VTList, Args);
10663   }
10664   case ISD::ADDCARRY: {
10665     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10666     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10667     if (!C || C->getZExtValue() != 0) break;
10668     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10669     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10670   }
10671   }
10672   return SDValue();
10673 }
10674 
10675 SDValue SITargetLowering::performSubCombine(SDNode *N,
10676                                             DAGCombinerInfo &DCI) const {
10677   SelectionDAG &DAG = DCI.DAG;
10678   EVT VT = N->getValueType(0);
10679 
10680   if (VT != MVT::i32)
10681     return SDValue();
10682 
10683   SDLoc SL(N);
10684   SDValue LHS = N->getOperand(0);
10685   SDValue RHS = N->getOperand(1);
10686 
10687   // sub x, zext (setcc) => subcarry x, 0, setcc
10688   // sub x, sext (setcc) => addcarry x, 0, setcc
10689   unsigned Opc = RHS.getOpcode();
10690   switch (Opc) {
10691   default: break;
10692   case ISD::ZERO_EXTEND:
10693   case ISD::SIGN_EXTEND:
10694   case ISD::ANY_EXTEND: {
10695     auto Cond = RHS.getOperand(0);
10696     // If this won't be a real VOPC output, we would still need to insert an
10697     // extra instruction anyway.
10698     if (!isBoolSGPR(Cond))
10699       break;
10700     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10701     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10702     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10703     return DAG.getNode(Opc, SL, VTList, Args);
10704   }
10705   }
10706 
10707   if (LHS.getOpcode() == ISD::SUBCARRY) {
10708     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10709     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10710     if (!C || !C->isZero())
10711       return SDValue();
10712     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10713     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10714   }
10715   return SDValue();
10716 }
10717 
10718 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10719   DAGCombinerInfo &DCI) const {
10720 
10721   if (N->getValueType(0) != MVT::i32)
10722     return SDValue();
10723 
10724   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10725   if (!C || C->getZExtValue() != 0)
10726     return SDValue();
10727 
10728   SelectionDAG &DAG = DCI.DAG;
10729   SDValue LHS = N->getOperand(0);
10730 
10731   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10732   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10733   unsigned LHSOpc = LHS.getOpcode();
10734   unsigned Opc = N->getOpcode();
10735   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10736       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10737     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10738     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10739   }
10740   return SDValue();
10741 }
10742 
10743 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10744                                              DAGCombinerInfo &DCI) const {
10745   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10746     return SDValue();
10747 
10748   SelectionDAG &DAG = DCI.DAG;
10749   EVT VT = N->getValueType(0);
10750 
10751   SDLoc SL(N);
10752   SDValue LHS = N->getOperand(0);
10753   SDValue RHS = N->getOperand(1);
10754 
10755   // These should really be instruction patterns, but writing patterns with
10756   // source modiifiers is a pain.
10757 
10758   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10759   if (LHS.getOpcode() == ISD::FADD) {
10760     SDValue A = LHS.getOperand(0);
10761     if (A == LHS.getOperand(1)) {
10762       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10763       if (FusedOp != 0) {
10764         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10765         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10766       }
10767     }
10768   }
10769 
10770   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10771   if (RHS.getOpcode() == ISD::FADD) {
10772     SDValue A = RHS.getOperand(0);
10773     if (A == RHS.getOperand(1)) {
10774       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10775       if (FusedOp != 0) {
10776         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10777         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10778       }
10779     }
10780   }
10781 
10782   return SDValue();
10783 }
10784 
10785 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10786                                              DAGCombinerInfo &DCI) const {
10787   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10788     return SDValue();
10789 
10790   SelectionDAG &DAG = DCI.DAG;
10791   SDLoc SL(N);
10792   EVT VT = N->getValueType(0);
10793   assert(!VT.isVector());
10794 
10795   // Try to get the fneg to fold into the source modifier. This undoes generic
10796   // DAG combines and folds them into the mad.
10797   //
10798   // Only do this if we are not trying to support denormals. v_mad_f32 does
10799   // not support denormals ever.
10800   SDValue LHS = N->getOperand(0);
10801   SDValue RHS = N->getOperand(1);
10802   if (LHS.getOpcode() == ISD::FADD) {
10803     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10804     SDValue A = LHS.getOperand(0);
10805     if (A == LHS.getOperand(1)) {
10806       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10807       if (FusedOp != 0){
10808         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10809         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10810 
10811         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10812       }
10813     }
10814   }
10815 
10816   if (RHS.getOpcode() == ISD::FADD) {
10817     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10818 
10819     SDValue A = RHS.getOperand(0);
10820     if (A == RHS.getOperand(1)) {
10821       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10822       if (FusedOp != 0){
10823         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10824         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10825       }
10826     }
10827   }
10828 
10829   return SDValue();
10830 }
10831 
10832 SDValue SITargetLowering::performFMACombine(SDNode *N,
10833                                             DAGCombinerInfo &DCI) const {
10834   SelectionDAG &DAG = DCI.DAG;
10835   EVT VT = N->getValueType(0);
10836   SDLoc SL(N);
10837 
10838   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10839     return SDValue();
10840 
10841   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10842   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10843   SDValue Op1 = N->getOperand(0);
10844   SDValue Op2 = N->getOperand(1);
10845   SDValue FMA = N->getOperand(2);
10846 
10847   if (FMA.getOpcode() != ISD::FMA ||
10848       Op1.getOpcode() != ISD::FP_EXTEND ||
10849       Op2.getOpcode() != ISD::FP_EXTEND)
10850     return SDValue();
10851 
10852   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10853   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10854   // is sufficient to allow generaing fdot2.
10855   const TargetOptions &Options = DAG.getTarget().Options;
10856   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10857       (N->getFlags().hasAllowContract() &&
10858        FMA->getFlags().hasAllowContract())) {
10859     Op1 = Op1.getOperand(0);
10860     Op2 = Op2.getOperand(0);
10861     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10862         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10863       return SDValue();
10864 
10865     SDValue Vec1 = Op1.getOperand(0);
10866     SDValue Idx1 = Op1.getOperand(1);
10867     SDValue Vec2 = Op2.getOperand(0);
10868 
10869     SDValue FMAOp1 = FMA.getOperand(0);
10870     SDValue FMAOp2 = FMA.getOperand(1);
10871     SDValue FMAAcc = FMA.getOperand(2);
10872 
10873     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10874         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10875       return SDValue();
10876 
10877     FMAOp1 = FMAOp1.getOperand(0);
10878     FMAOp2 = FMAOp2.getOperand(0);
10879     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10880         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10881       return SDValue();
10882 
10883     SDValue Vec3 = FMAOp1.getOperand(0);
10884     SDValue Vec4 = FMAOp2.getOperand(0);
10885     SDValue Idx2 = FMAOp1.getOperand(1);
10886 
10887     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10888         // Idx1 and Idx2 cannot be the same.
10889         Idx1 == Idx2)
10890       return SDValue();
10891 
10892     if (Vec1 == Vec2 || Vec3 == Vec4)
10893       return SDValue();
10894 
10895     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10896       return SDValue();
10897 
10898     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10899         (Vec1 == Vec4 && Vec2 == Vec3)) {
10900       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10901                          DAG.getTargetConstant(0, SL, MVT::i1));
10902     }
10903   }
10904   return SDValue();
10905 }
10906 
10907 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10908                                               DAGCombinerInfo &DCI) const {
10909   SelectionDAG &DAG = DCI.DAG;
10910   SDLoc SL(N);
10911 
10912   SDValue LHS = N->getOperand(0);
10913   SDValue RHS = N->getOperand(1);
10914   EVT VT = LHS.getValueType();
10915   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10916 
10917   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10918   if (!CRHS) {
10919     CRHS = dyn_cast<ConstantSDNode>(LHS);
10920     if (CRHS) {
10921       std::swap(LHS, RHS);
10922       CC = getSetCCSwappedOperands(CC);
10923     }
10924   }
10925 
10926   if (CRHS) {
10927     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10928         isBoolSGPR(LHS.getOperand(0))) {
10929       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10930       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10931       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10932       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10933       if ((CRHS->isAllOnes() &&
10934            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10935           (CRHS->isZero() &&
10936            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10937         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10938                            DAG.getConstant(-1, SL, MVT::i1));
10939       if ((CRHS->isAllOnes() &&
10940            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10941           (CRHS->isZero() &&
10942            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10943         return LHS.getOperand(0);
10944     }
10945 
10946     const APInt &CRHSVal = CRHS->getAPIntValue();
10947     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10948         LHS.getOpcode() == ISD::SELECT &&
10949         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10950         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10951         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10952         isBoolSGPR(LHS.getOperand(0))) {
10953       // Given CT != FT:
10954       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10955       // setcc (select cc, CT, CF), CF, ne => cc
10956       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10957       // setcc (select cc, CT, CF), CT, eq => cc
10958       const APInt &CT = LHS.getConstantOperandAPInt(1);
10959       const APInt &CF = LHS.getConstantOperandAPInt(2);
10960 
10961       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10962           (CT == CRHSVal && CC == ISD::SETNE))
10963         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10964                            DAG.getConstant(-1, SL, MVT::i1));
10965       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10966           (CT == CRHSVal && CC == ISD::SETEQ))
10967         return LHS.getOperand(0);
10968     }
10969   }
10970 
10971   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10972                                            VT != MVT::f16))
10973     return SDValue();
10974 
10975   // Match isinf/isfinite pattern
10976   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10977   // (fcmp one (fabs x), inf) -> (fp_class x,
10978   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10979   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10980     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10981     if (!CRHS)
10982       return SDValue();
10983 
10984     const APFloat &APF = CRHS->getValueAPF();
10985     if (APF.isInfinity() && !APF.isNegative()) {
10986       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10987                                  SIInstrFlags::N_INFINITY;
10988       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10989                                     SIInstrFlags::P_ZERO |
10990                                     SIInstrFlags::N_NORMAL |
10991                                     SIInstrFlags::P_NORMAL |
10992                                     SIInstrFlags::N_SUBNORMAL |
10993                                     SIInstrFlags::P_SUBNORMAL;
10994       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10995       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10996                          DAG.getConstant(Mask, SL, MVT::i32));
10997     }
10998   }
10999 
11000   return SDValue();
11001 }
11002 
11003 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11004                                                      DAGCombinerInfo &DCI) const {
11005   SelectionDAG &DAG = DCI.DAG;
11006   SDLoc SL(N);
11007   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11008 
11009   SDValue Src = N->getOperand(0);
11010   SDValue Shift = N->getOperand(0);
11011 
11012   // TODO: Extend type shouldn't matter (assuming legal types).
11013   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11014     Shift = Shift.getOperand(0);
11015 
11016   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11017     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11018     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11019     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11020     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11021     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11022     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11023       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11024                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11025 
11026       unsigned ShiftOffset = 8 * Offset;
11027       if (Shift.getOpcode() == ISD::SHL)
11028         ShiftOffset -= C->getZExtValue();
11029       else
11030         ShiftOffset += C->getZExtValue();
11031 
11032       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11033         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11034                            MVT::f32, Shifted);
11035       }
11036     }
11037   }
11038 
11039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11040   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11041   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11042     // We simplified Src. If this node is not dead, visit it again so it is
11043     // folded properly.
11044     if (N->getOpcode() != ISD::DELETED_NODE)
11045       DCI.AddToWorklist(N);
11046     return SDValue(N, 0);
11047   }
11048 
11049   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11050   if (SDValue DemandedSrc =
11051           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11052     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11053 
11054   return SDValue();
11055 }
11056 
11057 SDValue SITargetLowering::performClampCombine(SDNode *N,
11058                                               DAGCombinerInfo &DCI) const {
11059   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11060   if (!CSrc)
11061     return SDValue();
11062 
11063   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11064   const APFloat &F = CSrc->getValueAPF();
11065   APFloat Zero = APFloat::getZero(F.getSemantics());
11066   if (F < Zero ||
11067       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11068     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11069   }
11070 
11071   APFloat One(F.getSemantics(), "1.0");
11072   if (F > One)
11073     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11074 
11075   return SDValue(CSrc, 0);
11076 }
11077 
11078 
11079 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11080                                             DAGCombinerInfo &DCI) const {
11081   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11082     return SDValue();
11083   switch (N->getOpcode()) {
11084   case ISD::ADD:
11085     return performAddCombine(N, DCI);
11086   case ISD::SUB:
11087     return performSubCombine(N, DCI);
11088   case ISD::ADDCARRY:
11089   case ISD::SUBCARRY:
11090     return performAddCarrySubCarryCombine(N, DCI);
11091   case ISD::FADD:
11092     return performFAddCombine(N, DCI);
11093   case ISD::FSUB:
11094     return performFSubCombine(N, DCI);
11095   case ISD::SETCC:
11096     return performSetCCCombine(N, DCI);
11097   case ISD::FMAXNUM:
11098   case ISD::FMINNUM:
11099   case ISD::FMAXNUM_IEEE:
11100   case ISD::FMINNUM_IEEE:
11101   case ISD::SMAX:
11102   case ISD::SMIN:
11103   case ISD::UMAX:
11104   case ISD::UMIN:
11105   case AMDGPUISD::FMIN_LEGACY:
11106   case AMDGPUISD::FMAX_LEGACY:
11107     return performMinMaxCombine(N, DCI);
11108   case ISD::FMA:
11109     return performFMACombine(N, DCI);
11110   case ISD::AND:
11111     return performAndCombine(N, DCI);
11112   case ISD::OR:
11113     return performOrCombine(N, DCI);
11114   case ISD::XOR:
11115     return performXorCombine(N, DCI);
11116   case ISD::ZERO_EXTEND:
11117     return performZeroExtendCombine(N, DCI);
11118   case ISD::SIGN_EXTEND_INREG:
11119     return performSignExtendInRegCombine(N , DCI);
11120   case AMDGPUISD::FP_CLASS:
11121     return performClassCombine(N, DCI);
11122   case ISD::FCANONICALIZE:
11123     return performFCanonicalizeCombine(N, DCI);
11124   case AMDGPUISD::RCP:
11125     return performRcpCombine(N, DCI);
11126   case AMDGPUISD::FRACT:
11127   case AMDGPUISD::RSQ:
11128   case AMDGPUISD::RCP_LEGACY:
11129   case AMDGPUISD::RCP_IFLAG:
11130   case AMDGPUISD::RSQ_CLAMP:
11131   case AMDGPUISD::LDEXP: {
11132     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11133     SDValue Src = N->getOperand(0);
11134     if (Src.isUndef())
11135       return Src;
11136     break;
11137   }
11138   case ISD::SINT_TO_FP:
11139   case ISD::UINT_TO_FP:
11140     return performUCharToFloatCombine(N, DCI);
11141   case AMDGPUISD::CVT_F32_UBYTE0:
11142   case AMDGPUISD::CVT_F32_UBYTE1:
11143   case AMDGPUISD::CVT_F32_UBYTE2:
11144   case AMDGPUISD::CVT_F32_UBYTE3:
11145     return performCvtF32UByteNCombine(N, DCI);
11146   case AMDGPUISD::FMED3:
11147     return performFMed3Combine(N, DCI);
11148   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11149     return performCvtPkRTZCombine(N, DCI);
11150   case AMDGPUISD::CLAMP:
11151     return performClampCombine(N, DCI);
11152   case ISD::SCALAR_TO_VECTOR: {
11153     SelectionDAG &DAG = DCI.DAG;
11154     EVT VT = N->getValueType(0);
11155 
11156     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11157     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11158       SDLoc SL(N);
11159       SDValue Src = N->getOperand(0);
11160       EVT EltVT = Src.getValueType();
11161       if (EltVT == MVT::f16)
11162         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11163 
11164       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11165       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11166     }
11167 
11168     break;
11169   }
11170   case ISD::EXTRACT_VECTOR_ELT:
11171     return performExtractVectorEltCombine(N, DCI);
11172   case ISD::INSERT_VECTOR_ELT:
11173     return performInsertVectorEltCombine(N, DCI);
11174   case ISD::LOAD: {
11175     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11176       return Widended;
11177     LLVM_FALLTHROUGH;
11178   }
11179   default: {
11180     if (!DCI.isBeforeLegalize()) {
11181       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11182         return performMemSDNodeCombine(MemNode, DCI);
11183     }
11184 
11185     break;
11186   }
11187   }
11188 
11189   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11190 }
11191 
11192 /// Helper function for adjustWritemask
11193 static unsigned SubIdx2Lane(unsigned Idx) {
11194   switch (Idx) {
11195   default: return ~0u;
11196   case AMDGPU::sub0: return 0;
11197   case AMDGPU::sub1: return 1;
11198   case AMDGPU::sub2: return 2;
11199   case AMDGPU::sub3: return 3;
11200   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11201   }
11202 }
11203 
11204 /// Adjust the writemask of MIMG instructions
11205 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11206                                           SelectionDAG &DAG) const {
11207   unsigned Opcode = Node->getMachineOpcode();
11208 
11209   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11210   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11211   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11212     return Node; // not implemented for D16
11213 
11214   SDNode *Users[5] = { nullptr };
11215   unsigned Lane = 0;
11216   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11217   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11218   unsigned NewDmask = 0;
11219   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11220   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11221   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11222                   Node->getConstantOperandVal(LWEIdx))
11223                      ? true
11224                      : false;
11225   unsigned TFCLane = 0;
11226   bool HasChain = Node->getNumValues() > 1;
11227 
11228   if (OldDmask == 0) {
11229     // These are folded out, but on the chance it happens don't assert.
11230     return Node;
11231   }
11232 
11233   unsigned OldBitsSet = countPopulation(OldDmask);
11234   // Work out which is the TFE/LWE lane if that is enabled.
11235   if (UsesTFC) {
11236     TFCLane = OldBitsSet;
11237   }
11238 
11239   // Try to figure out the used register components
11240   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11241        I != E; ++I) {
11242 
11243     // Don't look at users of the chain.
11244     if (I.getUse().getResNo() != 0)
11245       continue;
11246 
11247     // Abort if we can't understand the usage
11248     if (!I->isMachineOpcode() ||
11249         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11250       return Node;
11251 
11252     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11253     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11254     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11255     // set, etc.
11256     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11257     if (Lane == ~0u)
11258       return Node;
11259 
11260     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11261     if (UsesTFC && Lane == TFCLane) {
11262       Users[Lane] = *I;
11263     } else {
11264       // Set which texture component corresponds to the lane.
11265       unsigned Comp;
11266       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11267         Comp = countTrailingZeros(Dmask);
11268         Dmask &= ~(1 << Comp);
11269       }
11270 
11271       // Abort if we have more than one user per component.
11272       if (Users[Lane])
11273         return Node;
11274 
11275       Users[Lane] = *I;
11276       NewDmask |= 1 << Comp;
11277     }
11278   }
11279 
11280   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11281   bool NoChannels = !NewDmask;
11282   if (NoChannels) {
11283     if (!UsesTFC) {
11284       // No uses of the result and not using TFC. Then do nothing.
11285       return Node;
11286     }
11287     // If the original dmask has one channel - then nothing to do
11288     if (OldBitsSet == 1)
11289       return Node;
11290     // Use an arbitrary dmask - required for the instruction to work
11291     NewDmask = 1;
11292   }
11293   // Abort if there's no change
11294   if (NewDmask == OldDmask)
11295     return Node;
11296 
11297   unsigned BitsSet = countPopulation(NewDmask);
11298 
11299   // Check for TFE or LWE - increase the number of channels by one to account
11300   // for the extra return value
11301   // This will need adjustment for D16 if this is also included in
11302   // adjustWriteMask (this function) but at present D16 are excluded.
11303   unsigned NewChannels = BitsSet + UsesTFC;
11304 
11305   int NewOpcode =
11306       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11307   assert(NewOpcode != -1 &&
11308          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11309          "failed to find equivalent MIMG op");
11310 
11311   // Adjust the writemask in the node
11312   SmallVector<SDValue, 12> Ops;
11313   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11314   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11315   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11316 
11317   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11318 
11319   MVT ResultVT = NewChannels == 1 ?
11320     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11321                            NewChannels == 5 ? 8 : NewChannels);
11322   SDVTList NewVTList = HasChain ?
11323     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11324 
11325 
11326   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11327                                               NewVTList, Ops);
11328 
11329   if (HasChain) {
11330     // Update chain.
11331     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11332     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11333   }
11334 
11335   if (NewChannels == 1) {
11336     assert(Node->hasNUsesOfValue(1, 0));
11337     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11338                                       SDLoc(Node), Users[Lane]->getValueType(0),
11339                                       SDValue(NewNode, 0));
11340     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11341     return nullptr;
11342   }
11343 
11344   // Update the users of the node with the new indices
11345   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11346     SDNode *User = Users[i];
11347     if (!User) {
11348       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11349       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11350       if (i || !NoChannels)
11351         continue;
11352     } else {
11353       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11354       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11355     }
11356 
11357     switch (Idx) {
11358     default: break;
11359     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11360     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11361     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11362     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11363     }
11364   }
11365 
11366   DAG.RemoveDeadNode(Node);
11367   return nullptr;
11368 }
11369 
11370 static bool isFrameIndexOp(SDValue Op) {
11371   if (Op.getOpcode() == ISD::AssertZext)
11372     Op = Op.getOperand(0);
11373 
11374   return isa<FrameIndexSDNode>(Op);
11375 }
11376 
11377 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11378 /// with frame index operands.
11379 /// LLVM assumes that inputs are to these instructions are registers.
11380 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11381                                                         SelectionDAG &DAG) const {
11382   if (Node->getOpcode() == ISD::CopyToReg) {
11383     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11384     SDValue SrcVal = Node->getOperand(2);
11385 
11386     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11387     // to try understanding copies to physical registers.
11388     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11389       SDLoc SL(Node);
11390       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11391       SDValue VReg = DAG.getRegister(
11392         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11393 
11394       SDNode *Glued = Node->getGluedNode();
11395       SDValue ToVReg
11396         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11397                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11398       SDValue ToResultReg
11399         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11400                            VReg, ToVReg.getValue(1));
11401       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11402       DAG.RemoveDeadNode(Node);
11403       return ToResultReg.getNode();
11404     }
11405   }
11406 
11407   SmallVector<SDValue, 8> Ops;
11408   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11409     if (!isFrameIndexOp(Node->getOperand(i))) {
11410       Ops.push_back(Node->getOperand(i));
11411       continue;
11412     }
11413 
11414     SDLoc DL(Node);
11415     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11416                                      Node->getOperand(i).getValueType(),
11417                                      Node->getOperand(i)), 0));
11418   }
11419 
11420   return DAG.UpdateNodeOperands(Node, Ops);
11421 }
11422 
11423 /// Fold the instructions after selecting them.
11424 /// Returns null if users were already updated.
11425 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11426                                           SelectionDAG &DAG) const {
11427   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11428   unsigned Opcode = Node->getMachineOpcode();
11429 
11430   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11431       !TII->isGather4(Opcode) &&
11432       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11433     return adjustWritemask(Node, DAG);
11434   }
11435 
11436   if (Opcode == AMDGPU::INSERT_SUBREG ||
11437       Opcode == AMDGPU::REG_SEQUENCE) {
11438     legalizeTargetIndependentNode(Node, DAG);
11439     return Node;
11440   }
11441 
11442   switch (Opcode) {
11443   case AMDGPU::V_DIV_SCALE_F32_e64:
11444   case AMDGPU::V_DIV_SCALE_F64_e64: {
11445     // Satisfy the operand register constraint when one of the inputs is
11446     // undefined. Ordinarily each undef value will have its own implicit_def of
11447     // a vreg, so force these to use a single register.
11448     SDValue Src0 = Node->getOperand(1);
11449     SDValue Src1 = Node->getOperand(3);
11450     SDValue Src2 = Node->getOperand(5);
11451 
11452     if ((Src0.isMachineOpcode() &&
11453          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11454         (Src0 == Src1 || Src0 == Src2))
11455       break;
11456 
11457     MVT VT = Src0.getValueType().getSimpleVT();
11458     const TargetRegisterClass *RC =
11459         getRegClassFor(VT, Src0.getNode()->isDivergent());
11460 
11461     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11462     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11463 
11464     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11465                                       UndefReg, Src0, SDValue());
11466 
11467     // src0 must be the same register as src1 or src2, even if the value is
11468     // undefined, so make sure we don't violate this constraint.
11469     if (Src0.isMachineOpcode() &&
11470         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11471       if (Src1.isMachineOpcode() &&
11472           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11473         Src0 = Src1;
11474       else if (Src2.isMachineOpcode() &&
11475                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11476         Src0 = Src2;
11477       else {
11478         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11479         Src0 = UndefReg;
11480         Src1 = UndefReg;
11481       }
11482     } else
11483       break;
11484 
11485     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11486     Ops[1] = Src0;
11487     Ops[3] = Src1;
11488     Ops[5] = Src2;
11489     Ops.push_back(ImpDef.getValue(1));
11490     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11491   }
11492   default:
11493     break;
11494   }
11495 
11496   return Node;
11497 }
11498 
11499 // Any MIMG instructions that use tfe or lwe require an initialization of the
11500 // result register that will be written in the case of a memory access failure.
11501 // The required code is also added to tie this init code to the result of the
11502 // img instruction.
11503 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11504   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11505   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11506   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11507   MachineBasicBlock &MBB = *MI.getParent();
11508 
11509   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11510   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11511   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11512 
11513   if (!TFE && !LWE) // intersect_ray
11514     return;
11515 
11516   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11517   unsigned LWEVal = LWE->getImm();
11518   unsigned D16Val = D16 ? D16->getImm() : 0;
11519 
11520   if (!TFEVal && !LWEVal)
11521     return;
11522 
11523   // At least one of TFE or LWE are non-zero
11524   // We have to insert a suitable initialization of the result value and
11525   // tie this to the dest of the image instruction.
11526 
11527   const DebugLoc &DL = MI.getDebugLoc();
11528 
11529   int DstIdx =
11530       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11531 
11532   // Calculate which dword we have to initialize to 0.
11533   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11534 
11535   // check that dmask operand is found.
11536   assert(MO_Dmask && "Expected dmask operand in instruction");
11537 
11538   unsigned dmask = MO_Dmask->getImm();
11539   // Determine the number of active lanes taking into account the
11540   // Gather4 special case
11541   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11542 
11543   bool Packed = !Subtarget->hasUnpackedD16VMem();
11544 
11545   unsigned InitIdx =
11546       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11547 
11548   // Abandon attempt if the dst size isn't large enough
11549   // - this is in fact an error but this is picked up elsewhere and
11550   // reported correctly.
11551   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11552   if (DstSize < InitIdx)
11553     return;
11554 
11555   // Create a register for the intialization value.
11556   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11557   unsigned NewDst = 0; // Final initialized value will be in here
11558 
11559   // If PRTStrictNull feature is enabled (the default) then initialize
11560   // all the result registers to 0, otherwise just the error indication
11561   // register (VGPRn+1)
11562   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11563   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11564 
11565   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11566   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11567     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11568     // Initialize dword
11569     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11570     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11571       .addImm(0);
11572     // Insert into the super-reg
11573     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11574       .addReg(PrevDst)
11575       .addReg(SubReg)
11576       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11577 
11578     PrevDst = NewDst;
11579   }
11580 
11581   // Add as an implicit operand
11582   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11583 
11584   // Tie the just added implicit operand to the dst
11585   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11586 }
11587 
11588 /// Assign the register class depending on the number of
11589 /// bits set in the writemask
11590 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11591                                                      SDNode *Node) const {
11592   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11593 
11594   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11595 
11596   if (TII->isVOP3(MI.getOpcode())) {
11597     // Make sure constant bus requirements are respected.
11598     TII->legalizeOperandsVOP3(MRI, MI);
11599 
11600     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11601     // This saves a chain-copy of registers and better ballance register
11602     // use between vgpr and agpr as agpr tuples tend to be big.
11603     if (MI.getDesc().OpInfo) {
11604       unsigned Opc = MI.getOpcode();
11605       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11606       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11607                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11608         if (I == -1)
11609           break;
11610         MachineOperand &Op = MI.getOperand(I);
11611         if (!Op.isReg() || !Op.getReg().isVirtual())
11612           continue;
11613         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11614         if (!TRI->hasAGPRs(RC))
11615           continue;
11616         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11617         if (!Src || !Src->isCopy() ||
11618             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11619           continue;
11620         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11621         // All uses of agpr64 and agpr32 can also accept vgpr except for
11622         // v_accvgpr_read, but we do not produce agpr reads during selection,
11623         // so no use checks are needed.
11624         MRI.setRegClass(Op.getReg(), NewRC);
11625       }
11626     }
11627 
11628     return;
11629   }
11630 
11631   // Replace unused atomics with the no return version.
11632   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11633   if (NoRetAtomicOp != -1) {
11634     if (!Node->hasAnyUseOfValue(0)) {
11635       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11636                                                AMDGPU::OpName::cpol);
11637       if (CPolIdx != -1) {
11638         MachineOperand &CPol = MI.getOperand(CPolIdx);
11639         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11640       }
11641       MI.RemoveOperand(0);
11642       MI.setDesc(TII->get(NoRetAtomicOp));
11643       return;
11644     }
11645 
11646     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11647     // instruction, because the return type of these instructions is a vec2 of
11648     // the memory type, so it can be tied to the input operand.
11649     // This means these instructions always have a use, so we need to add a
11650     // special case to check if the atomic has only one extract_subreg use,
11651     // which itself has no uses.
11652     if ((Node->hasNUsesOfValue(1, 0) &&
11653          Node->use_begin()->isMachineOpcode() &&
11654          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11655          !Node->use_begin()->hasAnyUseOfValue(0))) {
11656       Register Def = MI.getOperand(0).getReg();
11657 
11658       // Change this into a noret atomic.
11659       MI.setDesc(TII->get(NoRetAtomicOp));
11660       MI.RemoveOperand(0);
11661 
11662       // If we only remove the def operand from the atomic instruction, the
11663       // extract_subreg will be left with a use of a vreg without a def.
11664       // So we need to insert an implicit_def to avoid machine verifier
11665       // errors.
11666       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11667               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11668     }
11669     return;
11670   }
11671 
11672   if (TII->isMIMG(MI) && !MI.mayStore())
11673     AddIMGInit(MI);
11674 }
11675 
11676 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11677                               uint64_t Val) {
11678   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11679   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11680 }
11681 
11682 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11683                                                 const SDLoc &DL,
11684                                                 SDValue Ptr) const {
11685   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11686 
11687   // Build the half of the subregister with the constants before building the
11688   // full 128-bit register. If we are building multiple resource descriptors,
11689   // this will allow CSEing of the 2-component register.
11690   const SDValue Ops0[] = {
11691     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11692     buildSMovImm32(DAG, DL, 0),
11693     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11694     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11695     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11696   };
11697 
11698   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11699                                                 MVT::v2i32, Ops0), 0);
11700 
11701   // Combine the constants and the pointer.
11702   const SDValue Ops1[] = {
11703     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11704     Ptr,
11705     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11706     SubRegHi,
11707     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11708   };
11709 
11710   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11711 }
11712 
11713 /// Return a resource descriptor with the 'Add TID' bit enabled
11714 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11715 ///        of the resource descriptor) to create an offset, which is added to
11716 ///        the resource pointer.
11717 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11718                                            SDValue Ptr, uint32_t RsrcDword1,
11719                                            uint64_t RsrcDword2And3) const {
11720   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11721   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11722   if (RsrcDword1) {
11723     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11724                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11725                     0);
11726   }
11727 
11728   SDValue DataLo = buildSMovImm32(DAG, DL,
11729                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11730   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11731 
11732   const SDValue Ops[] = {
11733     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11734     PtrLo,
11735     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11736     PtrHi,
11737     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11738     DataLo,
11739     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11740     DataHi,
11741     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11742   };
11743 
11744   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11745 }
11746 
11747 //===----------------------------------------------------------------------===//
11748 //                         SI Inline Assembly Support
11749 //===----------------------------------------------------------------------===//
11750 
11751 std::pair<unsigned, const TargetRegisterClass *>
11752 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11753                                                StringRef Constraint,
11754                                                MVT VT) const {
11755   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11756 
11757   const TargetRegisterClass *RC = nullptr;
11758   if (Constraint.size() == 1) {
11759     const unsigned BitWidth = VT.getSizeInBits();
11760     switch (Constraint[0]) {
11761     default:
11762       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11763     case 's':
11764     case 'r':
11765       switch (BitWidth) {
11766       case 16:
11767         RC = &AMDGPU::SReg_32RegClass;
11768         break;
11769       case 64:
11770         RC = &AMDGPU::SGPR_64RegClass;
11771         break;
11772       default:
11773         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11774         if (!RC)
11775           return std::make_pair(0U, nullptr);
11776         break;
11777       }
11778       break;
11779     case 'v':
11780       switch (BitWidth) {
11781       case 16:
11782         RC = &AMDGPU::VGPR_32RegClass;
11783         break;
11784       default:
11785         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11786         if (!RC)
11787           return std::make_pair(0U, nullptr);
11788         break;
11789       }
11790       break;
11791     case 'a':
11792       if (!Subtarget->hasMAIInsts())
11793         break;
11794       switch (BitWidth) {
11795       case 16:
11796         RC = &AMDGPU::AGPR_32RegClass;
11797         break;
11798       default:
11799         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11800         if (!RC)
11801           return std::make_pair(0U, nullptr);
11802         break;
11803       }
11804       break;
11805     }
11806     // We actually support i128, i16 and f16 as inline parameters
11807     // even if they are not reported as legal
11808     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11809                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11810       return std::make_pair(0U, RC);
11811   }
11812 
11813   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11814     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11815     if (RegName.consume_front("v")) {
11816       RC = &AMDGPU::VGPR_32RegClass;
11817     } else if (RegName.consume_front("s")) {
11818       RC = &AMDGPU::SGPR_32RegClass;
11819     } else if (RegName.consume_front("a")) {
11820       RC = &AMDGPU::AGPR_32RegClass;
11821     }
11822 
11823     if (RC) {
11824       uint32_t Idx;
11825       if (RegName.consume_front("[")) {
11826         uint32_t End;
11827         bool Failed = RegName.consumeInteger(10, Idx);
11828         Failed |= !RegName.consume_front(":");
11829         Failed |= RegName.consumeInteger(10, End);
11830         Failed |= !RegName.consume_back("]");
11831         if (!Failed) {
11832           uint32_t Width = (End - Idx + 1) * 32;
11833           MCRegister Reg = RC->getRegister(Idx);
11834           if (SIRegisterInfo::isVGPRClass(RC))
11835             RC = TRI->getVGPRClassForBitWidth(Width);
11836           else if (SIRegisterInfo::isSGPRClass(RC))
11837             RC = TRI->getSGPRClassForBitWidth(Width);
11838           else if (SIRegisterInfo::isAGPRClass(RC))
11839             RC = TRI->getAGPRClassForBitWidth(Width);
11840           if (RC) {
11841             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11842             return std::make_pair(Reg, RC);
11843           }
11844         }
11845       } else {
11846         bool Failed = RegName.getAsInteger(10, Idx);
11847         if (!Failed && Idx < RC->getNumRegs())
11848           return std::make_pair(RC->getRegister(Idx), RC);
11849       }
11850     }
11851   }
11852 
11853   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11854   if (Ret.first)
11855     Ret.second = TRI->getPhysRegClass(Ret.first);
11856 
11857   return Ret;
11858 }
11859 
11860 static bool isImmConstraint(StringRef Constraint) {
11861   if (Constraint.size() == 1) {
11862     switch (Constraint[0]) {
11863     default: break;
11864     case 'I':
11865     case 'J':
11866     case 'A':
11867     case 'B':
11868     case 'C':
11869       return true;
11870     }
11871   } else if (Constraint == "DA" ||
11872              Constraint == "DB") {
11873     return true;
11874   }
11875   return false;
11876 }
11877 
11878 SITargetLowering::ConstraintType
11879 SITargetLowering::getConstraintType(StringRef Constraint) const {
11880   if (Constraint.size() == 1) {
11881     switch (Constraint[0]) {
11882     default: break;
11883     case 's':
11884     case 'v':
11885     case 'a':
11886       return C_RegisterClass;
11887     }
11888   }
11889   if (isImmConstraint(Constraint)) {
11890     return C_Other;
11891   }
11892   return TargetLowering::getConstraintType(Constraint);
11893 }
11894 
11895 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11896   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11897     Val = Val & maskTrailingOnes<uint64_t>(Size);
11898   }
11899   return Val;
11900 }
11901 
11902 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11903                                                     std::string &Constraint,
11904                                                     std::vector<SDValue> &Ops,
11905                                                     SelectionDAG &DAG) const {
11906   if (isImmConstraint(Constraint)) {
11907     uint64_t Val;
11908     if (getAsmOperandConstVal(Op, Val) &&
11909         checkAsmConstraintVal(Op, Constraint, Val)) {
11910       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11911       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11912     }
11913   } else {
11914     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11915   }
11916 }
11917 
11918 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11919   unsigned Size = Op.getScalarValueSizeInBits();
11920   if (Size > 64)
11921     return false;
11922 
11923   if (Size == 16 && !Subtarget->has16BitInsts())
11924     return false;
11925 
11926   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11927     Val = C->getSExtValue();
11928     return true;
11929   }
11930   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11931     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11932     return true;
11933   }
11934   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11935     if (Size != 16 || Op.getNumOperands() != 2)
11936       return false;
11937     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11938       return false;
11939     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11940       Val = C->getSExtValue();
11941       return true;
11942     }
11943     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11944       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11945       return true;
11946     }
11947   }
11948 
11949   return false;
11950 }
11951 
11952 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11953                                              const std::string &Constraint,
11954                                              uint64_t Val) const {
11955   if (Constraint.size() == 1) {
11956     switch (Constraint[0]) {
11957     case 'I':
11958       return AMDGPU::isInlinableIntLiteral(Val);
11959     case 'J':
11960       return isInt<16>(Val);
11961     case 'A':
11962       return checkAsmConstraintValA(Op, Val);
11963     case 'B':
11964       return isInt<32>(Val);
11965     case 'C':
11966       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11967              AMDGPU::isInlinableIntLiteral(Val);
11968     default:
11969       break;
11970     }
11971   } else if (Constraint.size() == 2) {
11972     if (Constraint == "DA") {
11973       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11974       int64_t LoBits = static_cast<int32_t>(Val);
11975       return checkAsmConstraintValA(Op, HiBits, 32) &&
11976              checkAsmConstraintValA(Op, LoBits, 32);
11977     }
11978     if (Constraint == "DB") {
11979       return true;
11980     }
11981   }
11982   llvm_unreachable("Invalid asm constraint");
11983 }
11984 
11985 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11986                                               uint64_t Val,
11987                                               unsigned MaxSize) const {
11988   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11989   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11990   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11991       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11992       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11993     return true;
11994   }
11995   return false;
11996 }
11997 
11998 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11999   switch (UnalignedClassID) {
12000   case AMDGPU::VReg_64RegClassID:
12001     return AMDGPU::VReg_64_Align2RegClassID;
12002   case AMDGPU::VReg_96RegClassID:
12003     return AMDGPU::VReg_96_Align2RegClassID;
12004   case AMDGPU::VReg_128RegClassID:
12005     return AMDGPU::VReg_128_Align2RegClassID;
12006   case AMDGPU::VReg_160RegClassID:
12007     return AMDGPU::VReg_160_Align2RegClassID;
12008   case AMDGPU::VReg_192RegClassID:
12009     return AMDGPU::VReg_192_Align2RegClassID;
12010   case AMDGPU::VReg_224RegClassID:
12011     return AMDGPU::VReg_224_Align2RegClassID;
12012   case AMDGPU::VReg_256RegClassID:
12013     return AMDGPU::VReg_256_Align2RegClassID;
12014   case AMDGPU::VReg_512RegClassID:
12015     return AMDGPU::VReg_512_Align2RegClassID;
12016   case AMDGPU::VReg_1024RegClassID:
12017     return AMDGPU::VReg_1024_Align2RegClassID;
12018   case AMDGPU::AReg_64RegClassID:
12019     return AMDGPU::AReg_64_Align2RegClassID;
12020   case AMDGPU::AReg_96RegClassID:
12021     return AMDGPU::AReg_96_Align2RegClassID;
12022   case AMDGPU::AReg_128RegClassID:
12023     return AMDGPU::AReg_128_Align2RegClassID;
12024   case AMDGPU::AReg_160RegClassID:
12025     return AMDGPU::AReg_160_Align2RegClassID;
12026   case AMDGPU::AReg_192RegClassID:
12027     return AMDGPU::AReg_192_Align2RegClassID;
12028   case AMDGPU::AReg_256RegClassID:
12029     return AMDGPU::AReg_256_Align2RegClassID;
12030   case AMDGPU::AReg_512RegClassID:
12031     return AMDGPU::AReg_512_Align2RegClassID;
12032   case AMDGPU::AReg_1024RegClassID:
12033     return AMDGPU::AReg_1024_Align2RegClassID;
12034   default:
12035     return -1;
12036   }
12037 }
12038 
12039 // Figure out which registers should be reserved for stack access. Only after
12040 // the function is legalized do we know all of the non-spill stack objects or if
12041 // calls are present.
12042 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12043   MachineRegisterInfo &MRI = MF.getRegInfo();
12044   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12045   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12046   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12047   const SIInstrInfo *TII = ST.getInstrInfo();
12048 
12049   if (Info->isEntryFunction()) {
12050     // Callable functions have fixed registers used for stack access.
12051     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12052   }
12053 
12054   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12055                              Info->getStackPtrOffsetReg()));
12056   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12057     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12058 
12059   // We need to worry about replacing the default register with itself in case
12060   // of MIR testcases missing the MFI.
12061   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12062     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12063 
12064   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12065     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12066 
12067   Info->limitOccupancy(MF);
12068 
12069   if (ST.isWave32() && !MF.empty()) {
12070     for (auto &MBB : MF) {
12071       for (auto &MI : MBB) {
12072         TII->fixImplicitOperands(MI);
12073       }
12074     }
12075   }
12076 
12077   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12078   // classes if required. Ideally the register class constraints would differ
12079   // per-subtarget, but there's no easy way to achieve that right now. This is
12080   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12081   // from using them as the register class for legal types.
12082   if (ST.needsAlignedVGPRs()) {
12083     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12084       const Register Reg = Register::index2VirtReg(I);
12085       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12086       if (!RC)
12087         continue;
12088       int NewClassID = getAlignedAGPRClassID(RC->getID());
12089       if (NewClassID != -1)
12090         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12091     }
12092   }
12093 
12094   TargetLoweringBase::finalizeLowering(MF);
12095 }
12096 
12097 void SITargetLowering::computeKnownBitsForFrameIndex(
12098   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12099   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12100 
12101   // Set the high bits to zero based on the maximum allowed scratch size per
12102   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12103   // calculation won't overflow, so assume the sign bit is never set.
12104   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12105 }
12106 
12107 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12108                                    KnownBits &Known, unsigned Dim) {
12109   unsigned MaxValue =
12110       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12111   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12112 }
12113 
12114 void SITargetLowering::computeKnownBitsForTargetInstr(
12115     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12116     const MachineRegisterInfo &MRI, unsigned Depth) const {
12117   const MachineInstr *MI = MRI.getVRegDef(R);
12118   switch (MI->getOpcode()) {
12119   case AMDGPU::G_INTRINSIC: {
12120     switch (MI->getIntrinsicID()) {
12121     case Intrinsic::amdgcn_workitem_id_x:
12122       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12123       break;
12124     case Intrinsic::amdgcn_workitem_id_y:
12125       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12126       break;
12127     case Intrinsic::amdgcn_workitem_id_z:
12128       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12129       break;
12130     case Intrinsic::amdgcn_mbcnt_lo:
12131     case Intrinsic::amdgcn_mbcnt_hi: {
12132       // These return at most the wavefront size - 1.
12133       unsigned Size = MRI.getType(R).getSizeInBits();
12134       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12135       break;
12136     }
12137     case Intrinsic::amdgcn_groupstaticsize: {
12138       // We can report everything over the maximum size as 0. We can't report
12139       // based on the actual size because we don't know if it's accurate or not
12140       // at any given point.
12141       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12142       break;
12143     }
12144     }
12145     break;
12146   }
12147   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12148     Known.Zero.setHighBits(24);
12149     break;
12150   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12151     Known.Zero.setHighBits(16);
12152     break;
12153   }
12154 }
12155 
12156 Align SITargetLowering::computeKnownAlignForTargetInstr(
12157   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12158   unsigned Depth) const {
12159   const MachineInstr *MI = MRI.getVRegDef(R);
12160   switch (MI->getOpcode()) {
12161   case AMDGPU::G_INTRINSIC:
12162   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12163     // FIXME: Can this move to generic code? What about the case where the call
12164     // site specifies a lower alignment?
12165     Intrinsic::ID IID = MI->getIntrinsicID();
12166     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12167     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12168     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12169       return *RetAlign;
12170     return Align(1);
12171   }
12172   default:
12173     return Align(1);
12174   }
12175 }
12176 
12177 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12178   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12179   const Align CacheLineAlign = Align(64);
12180 
12181   // Pre-GFX10 target did not benefit from loop alignment
12182   if (!ML || DisableLoopAlignment ||
12183       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12184       getSubtarget()->hasInstFwdPrefetchBug())
12185     return PrefAlign;
12186 
12187   // On GFX10 I$ is 4 x 64 bytes cache lines.
12188   // By default prefetcher keeps one cache line behind and reads two ahead.
12189   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12190   // behind and one ahead.
12191   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12192   // If loop fits 64 bytes it always spans no more than two cache lines and
12193   // does not need an alignment.
12194   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12195   // Else if loop is less or equal 192 bytes we need two lines behind.
12196 
12197   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12198   const MachineBasicBlock *Header = ML->getHeader();
12199   if (Header->getAlignment() != PrefAlign)
12200     return Header->getAlignment(); // Already processed.
12201 
12202   unsigned LoopSize = 0;
12203   for (const MachineBasicBlock *MBB : ML->blocks()) {
12204     // If inner loop block is aligned assume in average half of the alignment
12205     // size to be added as nops.
12206     if (MBB != Header)
12207       LoopSize += MBB->getAlignment().value() / 2;
12208 
12209     for (const MachineInstr &MI : *MBB) {
12210       LoopSize += TII->getInstSizeInBytes(MI);
12211       if (LoopSize > 192)
12212         return PrefAlign;
12213     }
12214   }
12215 
12216   if (LoopSize <= 64)
12217     return PrefAlign;
12218 
12219   if (LoopSize <= 128)
12220     return CacheLineAlign;
12221 
12222   // If any of parent loops is surrounded by prefetch instructions do not
12223   // insert new for inner loop, which would reset parent's settings.
12224   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12225     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12226       auto I = Exit->getFirstNonDebugInstr();
12227       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12228         return CacheLineAlign;
12229     }
12230   }
12231 
12232   MachineBasicBlock *Pre = ML->getLoopPreheader();
12233   MachineBasicBlock *Exit = ML->getExitBlock();
12234 
12235   if (Pre && Exit) {
12236     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12237             TII->get(AMDGPU::S_INST_PREFETCH))
12238       .addImm(1); // prefetch 2 lines behind PC
12239 
12240     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12241             TII->get(AMDGPU::S_INST_PREFETCH))
12242       .addImm(2); // prefetch 1 line behind PC
12243   }
12244 
12245   return CacheLineAlign;
12246 }
12247 
12248 LLVM_ATTRIBUTE_UNUSED
12249 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12250   assert(N->getOpcode() == ISD::CopyFromReg);
12251   do {
12252     // Follow the chain until we find an INLINEASM node.
12253     N = N->getOperand(0).getNode();
12254     if (N->getOpcode() == ISD::INLINEASM ||
12255         N->getOpcode() == ISD::INLINEASM_BR)
12256       return true;
12257   } while (N->getOpcode() == ISD::CopyFromReg);
12258   return false;
12259 }
12260 
12261 bool SITargetLowering::isSDNodeSourceOfDivergence(
12262     const SDNode *N, FunctionLoweringInfo *FLI,
12263     LegacyDivergenceAnalysis *KDA) const {
12264   switch (N->getOpcode()) {
12265   case ISD::CopyFromReg: {
12266     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12267     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12268     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12269     Register Reg = R->getReg();
12270 
12271     // FIXME: Why does this need to consider isLiveIn?
12272     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12273       return !TRI->isSGPRReg(MRI, Reg);
12274 
12275     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12276       return KDA->isDivergent(V);
12277 
12278     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12279     return !TRI->isSGPRReg(MRI, Reg);
12280   }
12281   case ISD::LOAD: {
12282     const LoadSDNode *L = cast<LoadSDNode>(N);
12283     unsigned AS = L->getAddressSpace();
12284     // A flat load may access private memory.
12285     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12286   }
12287   case ISD::CALLSEQ_END:
12288     return true;
12289   case ISD::INTRINSIC_WO_CHAIN:
12290     return AMDGPU::isIntrinsicSourceOfDivergence(
12291         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12292   case ISD::INTRINSIC_W_CHAIN:
12293     return AMDGPU::isIntrinsicSourceOfDivergence(
12294         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12295   case AMDGPUISD::ATOMIC_CMP_SWAP:
12296   case AMDGPUISD::ATOMIC_INC:
12297   case AMDGPUISD::ATOMIC_DEC:
12298   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12299   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12300   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12301   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12302   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12303   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12304   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12305   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12306   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12307   case AMDGPUISD::BUFFER_ATOMIC_AND:
12308   case AMDGPUISD::BUFFER_ATOMIC_OR:
12309   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12310   case AMDGPUISD::BUFFER_ATOMIC_INC:
12311   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12312   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12313   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12314   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12315   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12316   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12317     // Target-specific read-modify-write atomics are sources of divergence.
12318     return true;
12319   default:
12320     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12321       // Generic read-modify-write atomics are sources of divergence.
12322       return A->readMem() && A->writeMem();
12323     }
12324     return false;
12325   }
12326 }
12327 
12328 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12329                                                EVT VT) const {
12330   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12331   case MVT::f32:
12332     return hasFP32Denormals(DAG.getMachineFunction());
12333   case MVT::f64:
12334   case MVT::f16:
12335     return hasFP64FP16Denormals(DAG.getMachineFunction());
12336   default:
12337     return false;
12338   }
12339 }
12340 
12341 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12342                                                MachineFunction &MF) const {
12343   switch (Ty.getScalarSizeInBits()) {
12344   case 32:
12345     return hasFP32Denormals(MF);
12346   case 64:
12347   case 16:
12348     return hasFP64FP16Denormals(MF);
12349   default:
12350     return false;
12351   }
12352 }
12353 
12354 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12355                                                     const SelectionDAG &DAG,
12356                                                     bool SNaN,
12357                                                     unsigned Depth) const {
12358   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12359     const MachineFunction &MF = DAG.getMachineFunction();
12360     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12361 
12362     if (Info->getMode().DX10Clamp)
12363       return true; // Clamped to 0.
12364     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12365   }
12366 
12367   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12368                                                             SNaN, Depth);
12369 }
12370 
12371 // Global FP atomic instructions have a hardcoded FP mode and do not support
12372 // FP32 denormals, and only support v2f16 denormals.
12373 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12374   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12375   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12376   if (&Flt == &APFloat::IEEEsingle())
12377     return DenormMode == DenormalMode::getPreserveSign();
12378   return DenormMode == DenormalMode::getIEEE();
12379 }
12380 
12381 TargetLowering::AtomicExpansionKind
12382 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12383 
12384   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12385     OptimizationRemarkEmitter ORE(RMW->getFunction());
12386     LLVMContext &Ctx = RMW->getFunction()->getContext();
12387     SmallVector<StringRef> SSNs;
12388     Ctx.getSyncScopeNames(SSNs);
12389     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12390                         ? "system"
12391                         : SSNs[RMW->getSyncScopeID()];
12392     ORE.emit([&]() {
12393       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12394              << "Hardware instruction generated for atomic "
12395              << RMW->getOperationName(RMW->getOperation())
12396              << " operation at memory scope " << MemScope
12397              << " due to an unsafe request.";
12398     });
12399     return Kind;
12400   };
12401 
12402   switch (RMW->getOperation()) {
12403   case AtomicRMWInst::FAdd: {
12404     Type *Ty = RMW->getType();
12405 
12406     // We don't have a way to support 16-bit atomics now, so just leave them
12407     // as-is.
12408     if (Ty->isHalfTy())
12409       return AtomicExpansionKind::None;
12410 
12411     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12412       return AtomicExpansionKind::CmpXChg;
12413 
12414     unsigned AS = RMW->getPointerAddressSpace();
12415 
12416     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12417          Subtarget->hasAtomicFaddInsts()) {
12418       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12419       // floating point atomic instructions. May generate more efficient code,
12420       // but may not respect rounding and denormal modes, and may give incorrect
12421       // results for certain memory destinations.
12422       if (RMW->getFunction()
12423               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12424               .getValueAsString() != "true")
12425         return AtomicExpansionKind::CmpXChg;
12426 
12427       if (Subtarget->hasGFX90AInsts()) {
12428         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12429           return AtomicExpansionKind::CmpXChg;
12430 
12431         auto SSID = RMW->getSyncScopeID();
12432         if (SSID == SyncScope::System ||
12433             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12434           return AtomicExpansionKind::CmpXChg;
12435 
12436         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12437       }
12438 
12439       if (AS == AMDGPUAS::FLAT_ADDRESS)
12440         return AtomicExpansionKind::CmpXChg;
12441 
12442       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12443                               : AtomicExpansionKind::CmpXChg;
12444     }
12445 
12446     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12447     // to round-to-nearest-even.
12448     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12449     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12450       if (!Ty->isDoubleTy())
12451         return AtomicExpansionKind::None;
12452 
12453       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12454         return AtomicExpansionKind::None;
12455 
12456       return RMW->getFunction()
12457                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12458                          .getValueAsString() == "true"
12459                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12460                  : AtomicExpansionKind::CmpXChg;
12461     }
12462 
12463     return AtomicExpansionKind::CmpXChg;
12464   }
12465   default:
12466     break;
12467   }
12468 
12469   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12470 }
12471 
12472 const TargetRegisterClass *
12473 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12474   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12475   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12476   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12477     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12478                                                : &AMDGPU::SReg_32RegClass;
12479   if (!TRI->isSGPRClass(RC) && !isDivergent)
12480     return TRI->getEquivalentSGPRClass(RC);
12481   else if (TRI->isSGPRClass(RC) && isDivergent)
12482     return TRI->getEquivalentVGPRClass(RC);
12483 
12484   return RC;
12485 }
12486 
12487 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12488 // uniform values (as produced by the mask results of control flow intrinsics)
12489 // used outside of divergent blocks. The phi users need to also be treated as
12490 // always uniform.
12491 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12492                       unsigned WaveSize) {
12493   // FIXME: We asssume we never cast the mask results of a control flow
12494   // intrinsic.
12495   // Early exit if the type won't be consistent as a compile time hack.
12496   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12497   if (!IT || IT->getBitWidth() != WaveSize)
12498     return false;
12499 
12500   if (!isa<Instruction>(V))
12501     return false;
12502   if (!Visited.insert(V).second)
12503     return false;
12504   bool Result = false;
12505   for (auto U : V->users()) {
12506     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12507       if (V == U->getOperand(1)) {
12508         switch (Intrinsic->getIntrinsicID()) {
12509         default:
12510           Result = false;
12511           break;
12512         case Intrinsic::amdgcn_if_break:
12513         case Intrinsic::amdgcn_if:
12514         case Intrinsic::amdgcn_else:
12515           Result = true;
12516           break;
12517         }
12518       }
12519       if (V == U->getOperand(0)) {
12520         switch (Intrinsic->getIntrinsicID()) {
12521         default:
12522           Result = false;
12523           break;
12524         case Intrinsic::amdgcn_end_cf:
12525         case Intrinsic::amdgcn_loop:
12526           Result = true;
12527           break;
12528         }
12529       }
12530     } else {
12531       Result = hasCFUser(U, Visited, WaveSize);
12532     }
12533     if (Result)
12534       break;
12535   }
12536   return Result;
12537 }
12538 
12539 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12540                                                const Value *V) const {
12541   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12542     if (CI->isInlineAsm()) {
12543       // FIXME: This cannot give a correct answer. This should only trigger in
12544       // the case where inline asm returns mixed SGPR and VGPR results, used
12545       // outside the defining block. We don't have a specific result to
12546       // consider, so this assumes if any value is SGPR, the overall register
12547       // also needs to be SGPR.
12548       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12549       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12550           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12551       for (auto &TC : TargetConstraints) {
12552         if (TC.Type == InlineAsm::isOutput) {
12553           ComputeConstraintToUse(TC, SDValue());
12554           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12555               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12556           if (RC && SIRI->isSGPRClass(RC))
12557             return true;
12558         }
12559       }
12560     }
12561   }
12562   SmallPtrSet<const Value *, 16> Visited;
12563   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12564 }
12565 
12566 std::pair<InstructionCost, MVT>
12567 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12568                                           Type *Ty) const {
12569   std::pair<InstructionCost, MVT> Cost =
12570       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12571   auto Size = DL.getTypeSizeInBits(Ty);
12572   // Maximum load or store can handle 8 dwords for scalar and 4 for
12573   // vector ALU. Let's assume anything above 8 dwords is expensive
12574   // even if legal.
12575   if (Size <= 256)
12576     return Cost;
12577 
12578   Cost.first += (Size + 255) / 256;
12579   return Cost;
12580 }
12581