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/FloatingPointMode.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/IntrinsicsAMDGPU.h"
35 #include "llvm/IR/IntrinsicsR600.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "si-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 static cl::opt<bool> DisableLoopAlignment(
46   "amdgpu-disable-loop-alignment",
47   cl::desc("Do not align and prefetch loops"),
48   cl::init(false));
49 
50 static cl::opt<bool> UseDivergentRegisterIndexing(
51   "amdgpu-use-divergent-register-indexing",
52   cl::Hidden,
53   cl::desc("Use indirect register addressing for divergent indexes"),
54   cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
57   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
58   return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
62   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
63   return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70       return AMDGPU::SGPR0 + Reg;
71     }
72   }
73   llvm_unreachable("Cannot allocate sgpr");
74 }
75 
76 SITargetLowering::SITargetLowering(const TargetMachine &TM,
77                                    const GCNSubtarget &STI)
78     : AMDGPUTargetLowering(TM, STI),
79       Subtarget(&STI) {
80   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88   const SIRegisterInfo *TRI = STI.getRegisterInfo();
89   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91   addRegisterClass(MVT::f64, V64RegClass);
92   addRegisterClass(MVT::v2f32, V64RegClass);
93 
94   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130   if (Subtarget->has16BitInsts()) {
131     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134     // Unless there are also VOP3P operations, not operations are really legal.
135     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
140     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
141   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::i1, Custom);
165   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
166 
167   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
175   setOperationAction(ISD::STORE, MVT::i1, Custom);
176   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
177 
178   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
179   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
180   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
181   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
183   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
184   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
185   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
186   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
187   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
188   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
189   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
190   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
191   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
192   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
193   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
194 
195   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
197   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
200   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
201   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
202 
203   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
204   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
205 
206   setOperationAction(ISD::SELECT, MVT::i1, Promote);
207   setOperationAction(ISD::SELECT, MVT::i64, Custom);
208   setOperationAction(ISD::SELECT, MVT::f64, Promote);
209   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
210 
211   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
216 
217   setOperationAction(ISD::SETCC, MVT::i1, Promote);
218   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
219   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
220   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
221 
222   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
236   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
237   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
238 
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
246   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
247 
248   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
253   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
254 
255   setOperationAction(ISD::UADDO, MVT::i32, Legal);
256   setOperationAction(ISD::USUBO, MVT::i32, Legal);
257 
258   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
259   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
260 
261   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
263   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
264 
265 #if 0
266   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
267   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
268 #endif
269 
270   // We only support LOAD/STORE and vector manipulation ops for vectors
271   // with > 4 elements.
272   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
273                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
274                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
275                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
276                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
277                   MVT::v32i32, MVT::v32f32 }) {
278     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
279       switch (Op) {
280       case ISD::LOAD:
281       case ISD::STORE:
282       case ISD::BUILD_VECTOR:
283       case ISD::BITCAST:
284       case ISD::EXTRACT_VECTOR_ELT:
285       case ISD::INSERT_VECTOR_ELT:
286       case ISD::EXTRACT_SUBVECTOR:
287       case ISD::SCALAR_TO_VECTOR:
288         break;
289       case ISD::INSERT_SUBVECTOR:
290       case ISD::CONCAT_VECTORS:
291         setOperationAction(Op, VT, Custom);
292         break;
293       default:
294         setOperationAction(Op, VT, Expand);
295         break;
296       }
297     }
298   }
299 
300   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
301 
302   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
303   // is expanded to avoid having two separate loops in case the index is a VGPR.
304 
305   // Most operations are naturally 32-bit vector operations. We only support
306   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
307   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
308     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
310 
311     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
312     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
313 
314     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
315     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
316 
317     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
319   }
320 
321   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
322     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
323     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
324 
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
326     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
327 
328     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
330 
331     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
333   }
334 
335   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
336     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
337     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
338 
339     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
340     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
346     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
347   }
348 
349   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
350     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
351     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
352 
353     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
354     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
360     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
361   }
362 
363   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
364     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
365     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
366 
367     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
368     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
374     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
375   }
376 
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
381 
382   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
383   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
384 
385   // Avoid stack access for these.
386   // TODO: Generalize to more vector types.
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
391 
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
397   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
398 
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
403 
404   // Deal with vec3 vector operations when widened to vec4.
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
408   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
409 
410   // Deal with vec5/6/7 vector operations when widened to vec8.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
419 
420   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
421   // and output demarshalling
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
424 
425   // We can't return success/failure, only the old value,
426   // let LLVM add the comparison
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
429 
430   if (Subtarget->hasFlatAddressSpace()) {
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
433   }
434 
435   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
436   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
437 
438   // FIXME: This should be narrowed to i32, but that only happens if i64 is
439   // illegal.
440   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
441   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
442   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
443 
444   // On SI this is s_memtime and s_memrealtime on VI.
445   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446   setOperationAction(ISD::TRAP, MVT::Other, Custom);
447   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
448 
449   if (Subtarget->has16BitInsts()) {
450     setOperationAction(ISD::FPOW, MVT::f16, Promote);
451     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
452     setOperationAction(ISD::FLOG, MVT::f16, Custom);
453     setOperationAction(ISD::FEXP, MVT::f16, Custom);
454     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
455   }
456 
457   if (Subtarget->hasMadMacF32Insts())
458     setOperationAction(ISD::FMAD, MVT::f32, Legal);
459 
460   if (!Subtarget->hasBFI()) {
461     // fcopysign can be done in a single instruction with BFI.
462     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
463     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
464   }
465 
466   if (!Subtarget->hasBCNT(32))
467     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
468 
469   if (!Subtarget->hasBCNT(64))
470     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
471 
472   if (Subtarget->hasFFBH()) {
473     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475   }
476 
477   if (Subtarget->hasFFBL()) {
478     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
479     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
480   }
481 
482   // We only really have 32-bit BFE instructions (and 16-bit on VI).
483   //
484   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
485   // effort to match them now. We want this to be false for i64 cases when the
486   // extraction isn't restricted to the upper or lower half. Ideally we would
487   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
488   // span the midpoint are probably relatively rare, so don't worry about them
489   // for now.
490   if (Subtarget->hasBFE())
491     setHasExtractBitsInsn(true);
492 
493   // Clamp modifier on add/sub
494   if (Subtarget->hasIntClamp()) {
495     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
496     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
497   }
498 
499   if (Subtarget->hasAddNoCarry()) {
500     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
502     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
503     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
504   }
505 
506   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
508   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
509   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
510 
511 
512   // These are really only legal for ieee_mode functions. We should be avoiding
513   // them for functions that don't have ieee_mode enabled, so just say they are
514   // legal.
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
517   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
518   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
519 
520 
521   if (Subtarget->haveRoundOpsF64()) {
522     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
523     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
524     setOperationAction(ISD::FRINT, MVT::f64, Legal);
525   } else {
526     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
527     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
528     setOperationAction(ISD::FRINT, MVT::f64, Custom);
529     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
530   }
531 
532   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
533 
534   setOperationAction(ISD::FSIN, MVT::f32, Custom);
535   setOperationAction(ISD::FCOS, MVT::f32, Custom);
536   setOperationAction(ISD::FDIV, MVT::f32, Custom);
537   setOperationAction(ISD::FDIV, MVT::f64, Custom);
538 
539   if (Subtarget->has16BitInsts()) {
540     setOperationAction(ISD::Constant, MVT::i16, Legal);
541 
542     setOperationAction(ISD::SMIN, MVT::i16, Legal);
543     setOperationAction(ISD::SMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::UMIN, MVT::i16, Legal);
546     setOperationAction(ISD::UMAX, MVT::i16, Legal);
547 
548     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
549     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
550 
551     setOperationAction(ISD::ROTR, MVT::i16, Expand);
552     setOperationAction(ISD::ROTL, MVT::i16, Expand);
553 
554     setOperationAction(ISD::SDIV, MVT::i16, Promote);
555     setOperationAction(ISD::UDIV, MVT::i16, Promote);
556     setOperationAction(ISD::SREM, MVT::i16, Promote);
557     setOperationAction(ISD::UREM, MVT::i16, Promote);
558     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
559     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
560 
561     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
562 
563     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
566     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
567     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
568 
569     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
572 
573     setOperationAction(ISD::LOAD, MVT::i16, Custom);
574 
575     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
576 
577     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
579     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
580     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
581 
582     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
583     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
584 
585     // F16 - Constant Actions.
586     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
587 
588     // F16 - Load/Store Actions.
589     setOperationAction(ISD::LOAD, MVT::f16, Promote);
590     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
591     setOperationAction(ISD::STORE, MVT::f16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
593 
594     // F16 - VOP1 Actions.
595     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
596     setOperationAction(ISD::FCOS, MVT::f16, Custom);
597     setOperationAction(ISD::FSIN, MVT::f16, Custom);
598 
599     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
600     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
601 
602     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
603     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
604     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
605     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
606     setOperationAction(ISD::FROUND, MVT::f16, Custom);
607     setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom);
608 
609     // F16 - VOP2 Actions.
610     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
611     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
612 
613     setOperationAction(ISD::FDIV, MVT::f16, Custom);
614 
615     // F16 - VOP3 Actions.
616     setOperationAction(ISD::FMA, MVT::f16, Legal);
617     if (STI.hasMadF16())
618       setOperationAction(ISD::FMAD, MVT::f16, Legal);
619 
620     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
621                    MVT::v8f16}) {
622       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
623         switch (Op) {
624         case ISD::LOAD:
625         case ISD::STORE:
626         case ISD::BUILD_VECTOR:
627         case ISD::BITCAST:
628         case ISD::EXTRACT_VECTOR_ELT:
629         case ISD::INSERT_VECTOR_ELT:
630         case ISD::INSERT_SUBVECTOR:
631         case ISD::EXTRACT_SUBVECTOR:
632         case ISD::SCALAR_TO_VECTOR:
633           break;
634         case ISD::CONCAT_VECTORS:
635           setOperationAction(Op, VT, Custom);
636           break;
637         default:
638           setOperationAction(Op, VT, Expand);
639           break;
640         }
641       }
642     }
643 
644     // v_perm_b32 can handle either of these.
645     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
646     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
647     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
648 
649     // XXX - Do these do anything? Vector constants turn into build_vector.
650     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
651     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
654     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
655 
656     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
664     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
665 
666     setOperationAction(ISD::AND, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
668     setOperationAction(ISD::OR, MVT::v2i16, Promote);
669     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
670     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
671     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
672 
673     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
679     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
680     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
681     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
682 
683     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
684     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
685     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
686     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
687 
688     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
689     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
690     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
691     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
692 
693     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
694     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
695     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
696     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
697 
698     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
699     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
700     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
701     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
702 
703     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
704     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
705     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
706 
707     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
708     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
709     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
710 
711     if (!Subtarget->hasVOP3PInsts()) {
712       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
713       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
714     }
715 
716     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
717     // This isn't really legal, but this avoids the legalizer unrolling it (and
718     // allows matching fneg (fabs x) patterns)
719     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
720 
721     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
722     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
723     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
724     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
725 
726     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
727     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
728     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
729     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
730 
731     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
732     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
733     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
734     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
735 
736     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
737       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
738       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
739       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
740       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Custom);
741     }
742   }
743 
744   if (Subtarget->hasVOP3PInsts()) {
745     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
746     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
747     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
748     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
749     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
750     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
751     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
752     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
753     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
754     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
755 
756     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
757     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
758     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
759     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
760 
761     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
762     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
763     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
764 
765     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
766     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
767 
768     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
769 
770     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
771     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
772 
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
774     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
775     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
776     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
777 
778     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
779       // Split vector operations.
780       setOperationAction(ISD::SHL, VT, Custom);
781       setOperationAction(ISD::SRA, VT, Custom);
782       setOperationAction(ISD::SRL, VT, Custom);
783       setOperationAction(ISD::ADD, VT, Custom);
784       setOperationAction(ISD::SUB, VT, Custom);
785       setOperationAction(ISD::MUL, VT, Custom);
786 
787       setOperationAction(ISD::SMIN, VT, Custom);
788       setOperationAction(ISD::SMAX, VT, Custom);
789       setOperationAction(ISD::UMIN, VT, Custom);
790       setOperationAction(ISD::UMAX, VT, Custom);
791 
792       setOperationAction(ISD::UADDSAT, VT, Custom);
793       setOperationAction(ISD::SADDSAT, VT, Custom);
794       setOperationAction(ISD::USUBSAT, VT, Custom);
795       setOperationAction(ISD::SSUBSAT, VT, Custom);
796     }
797 
798     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
799       // Split vector operations.
800       setOperationAction(ISD::FADD, VT, Custom);
801       setOperationAction(ISD::FMUL, VT, Custom);
802       setOperationAction(ISD::FMA, VT, Custom);
803       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
804     }
805 
806     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
807     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
808 
809     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
810     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
811 
812     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
813     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
814     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
815 
816     if (Subtarget->hasPackedFP32Ops()) {
817       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
818       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
819       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
820       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
821 
822       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
823         setOperationAction(ISD::FADD, VT, Custom);
824         setOperationAction(ISD::FMUL, VT, Custom);
825         setOperationAction(ISD::FMA, VT, Custom);
826       }
827     }
828   }
829 
830   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
831   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
832 
833   if (Subtarget->has16BitInsts()) {
834     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
835     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
836     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
837     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
838   } else {
839     // Legalization hack.
840     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
841     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
842 
843     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
844     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
845   }
846 
847   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
848                   MVT::v8i16, MVT::v8f16 }) {
849     setOperationAction(ISD::SELECT, VT, Custom);
850   }
851 
852   setOperationAction(ISD::SMULO, MVT::i64, Custom);
853   setOperationAction(ISD::UMULO, MVT::i64, Custom);
854 
855   if (Subtarget->hasMad64_32()) {
856     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
857     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
858   }
859 
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
864   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
865   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
866   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
867 
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
876   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
877   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
878   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
879 
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
887   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
888   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
889   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
890 
891   setTargetDAGCombine({ISD::ADD,
892                        ISD::ADDCARRY,
893                        ISD::SUB,
894                        ISD::SUBCARRY,
895                        ISD::FADD,
896                        ISD::FSUB,
897                        ISD::FMINNUM,
898                        ISD::FMAXNUM,
899                        ISD::FMINNUM_IEEE,
900                        ISD::FMAXNUM_IEEE,
901                        ISD::FMA,
902                        ISD::SMIN,
903                        ISD::SMAX,
904                        ISD::UMIN,
905                        ISD::UMAX,
906                        ISD::SETCC,
907                        ISD::AND,
908                        ISD::OR,
909                        ISD::XOR,
910                        ISD::SINT_TO_FP,
911                        ISD::UINT_TO_FP,
912                        ISD::FCANONICALIZE,
913                        ISD::SCALAR_TO_VECTOR,
914                        ISD::ZERO_EXTEND,
915                        ISD::SIGN_EXTEND_INREG,
916                        ISD::EXTRACT_VECTOR_ELT,
917                        ISD::INSERT_VECTOR_ELT});
918 
919   // All memory operations. Some folding on the pointer operand is done to help
920   // matching the constant offsets in the addressing modes.
921   setTargetDAGCombine({ISD::LOAD,
922                        ISD::STORE,
923                        ISD::ATOMIC_LOAD,
924                        ISD::ATOMIC_STORE,
925                        ISD::ATOMIC_CMP_SWAP,
926                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
927                        ISD::ATOMIC_SWAP,
928                        ISD::ATOMIC_LOAD_ADD,
929                        ISD::ATOMIC_LOAD_SUB,
930                        ISD::ATOMIC_LOAD_AND,
931                        ISD::ATOMIC_LOAD_OR,
932                        ISD::ATOMIC_LOAD_XOR,
933                        ISD::ATOMIC_LOAD_NAND,
934                        ISD::ATOMIC_LOAD_MIN,
935                        ISD::ATOMIC_LOAD_MAX,
936                        ISD::ATOMIC_LOAD_UMIN,
937                        ISD::ATOMIC_LOAD_UMAX,
938                        ISD::ATOMIC_LOAD_FADD,
939                        ISD::INTRINSIC_VOID,
940                        ISD::INTRINSIC_W_CHAIN});
941 
942   // FIXME: In other contexts we pretend this is a per-function property.
943   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
944 
945   setSchedulingPreference(Sched::RegPressure);
946 }
947 
948 const GCNSubtarget *SITargetLowering::getSubtarget() const {
949   return Subtarget;
950 }
951 
952 //===----------------------------------------------------------------------===//
953 // TargetLowering queries
954 //===----------------------------------------------------------------------===//
955 
956 // v_mad_mix* support a conversion from f16 to f32.
957 //
958 // There is only one special case when denormals are enabled we don't currently,
959 // where this is OK to use.
960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
961                                        EVT DestVT, EVT SrcVT) const {
962   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
963           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
964     DestVT.getScalarType() == MVT::f32 &&
965     SrcVT.getScalarType() == MVT::f16 &&
966     // TODO: This probably only requires no input flushing?
967     !hasFP32Denormals(DAG.getMachineFunction());
968 }
969 
970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
971                                        LLT DestTy, LLT SrcTy) const {
972   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
973           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
974          DestTy.getScalarSizeInBits() == 32 &&
975          SrcTy.getScalarSizeInBits() == 16 &&
976          // TODO: This probably only requires no input flushing?
977          !hasFP32Denormals(*MI.getMF());
978 }
979 
980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
981   // SI has some legal vector types, but no legal vector operations. Say no
982   // shuffles are legal in order to prefer scalarizing some vector operations.
983   return false;
984 }
985 
986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
987                                                     CallingConv::ID CC,
988                                                     EVT VT) const {
989   if (CC == CallingConv::AMDGPU_KERNEL)
990     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
991 
992   if (VT.isVector()) {
993     EVT ScalarVT = VT.getScalarType();
994     unsigned Size = ScalarVT.getSizeInBits();
995     if (Size == 16) {
996       if (Subtarget->has16BitInsts())
997         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
998       return VT.isInteger() ? MVT::i32 : MVT::f32;
999     }
1000 
1001     if (Size < 16)
1002       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1003     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1004   }
1005 
1006   if (VT.getSizeInBits() > 32)
1007     return MVT::i32;
1008 
1009   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1010 }
1011 
1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1013                                                          CallingConv::ID CC,
1014                                                          EVT VT) const {
1015   if (CC == CallingConv::AMDGPU_KERNEL)
1016     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1017 
1018   if (VT.isVector()) {
1019     unsigned NumElts = VT.getVectorNumElements();
1020     EVT ScalarVT = VT.getScalarType();
1021     unsigned Size = ScalarVT.getSizeInBits();
1022 
1023     // FIXME: Should probably promote 8-bit vectors to i16.
1024     if (Size == 16 && Subtarget->has16BitInsts())
1025       return (NumElts + 1) / 2;
1026 
1027     if (Size <= 32)
1028       return NumElts;
1029 
1030     if (Size > 32)
1031       return NumElts * ((Size + 31) / 32);
1032   } else if (VT.getSizeInBits() > 32)
1033     return (VT.getSizeInBits() + 31) / 32;
1034 
1035   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1036 }
1037 
1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1039   LLVMContext &Context, CallingConv::ID CC,
1040   EVT VT, EVT &IntermediateVT,
1041   unsigned &NumIntermediates, MVT &RegisterVT) const {
1042   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1043     unsigned NumElts = VT.getVectorNumElements();
1044     EVT ScalarVT = VT.getScalarType();
1045     unsigned Size = ScalarVT.getSizeInBits();
1046     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1047     // support, but unless we can properly handle 3-vectors, it will be still be
1048     // inconsistent.
1049     if (Size == 16 && Subtarget->has16BitInsts()) {
1050       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1051       IntermediateVT = RegisterVT;
1052       NumIntermediates = (NumElts + 1) / 2;
1053       return NumIntermediates;
1054     }
1055 
1056     if (Size == 32) {
1057       RegisterVT = ScalarVT.getSimpleVT();
1058       IntermediateVT = RegisterVT;
1059       NumIntermediates = NumElts;
1060       return NumIntermediates;
1061     }
1062 
1063     if (Size < 16 && Subtarget->has16BitInsts()) {
1064       // FIXME: Should probably form v2i16 pieces
1065       RegisterVT = MVT::i16;
1066       IntermediateVT = ScalarVT;
1067       NumIntermediates = NumElts;
1068       return NumIntermediates;
1069     }
1070 
1071 
1072     if (Size != 16 && Size <= 32) {
1073       RegisterVT = MVT::i32;
1074       IntermediateVT = ScalarVT;
1075       NumIntermediates = NumElts;
1076       return NumIntermediates;
1077     }
1078 
1079     if (Size > 32) {
1080       RegisterVT = MVT::i32;
1081       IntermediateVT = RegisterVT;
1082       NumIntermediates = NumElts * ((Size + 31) / 32);
1083       return NumIntermediates;
1084     }
1085   }
1086 
1087   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1088     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1089 }
1090 
1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1092   assert(DMaskLanes != 0);
1093 
1094   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1095     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1096     return EVT::getVectorVT(Ty->getContext(),
1097                             EVT::getEVT(VT->getElementType()),
1098                             NumElts);
1099   }
1100 
1101   return EVT::getEVT(Ty);
1102 }
1103 
1104 // Peek through TFE struct returns to only use the data size.
1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1106   auto *ST = dyn_cast<StructType>(Ty);
1107   if (!ST)
1108     return memVTFromImageData(Ty, DMaskLanes);
1109 
1110   // Some intrinsics return an aggregate type - special case to work out the
1111   // correct memVT.
1112   //
1113   // Only limited forms of aggregate type currently expected.
1114   if (ST->getNumContainedTypes() != 2 ||
1115       !ST->getContainedType(1)->isIntegerTy(32))
1116     return EVT();
1117   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1118 }
1119 
1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1121                                           const CallInst &CI,
1122                                           MachineFunction &MF,
1123                                           unsigned IntrID) const {
1124   Info.flags = MachineMemOperand::MONone;
1125   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1126     Info.flags |= MachineMemOperand::MOInvariant;
1127 
1128   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1129           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1130     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1131                                                   (Intrinsic::ID)IntrID);
1132     if (Attr.hasFnAttr(Attribute::ReadNone))
1133       return false;
1134 
1135     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1136 
1137     if (RsrcIntr->IsImage) {
1138       Info.ptrVal =
1139           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1140       Info.align.reset();
1141     } else {
1142       Info.ptrVal =
1143           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1144     }
1145 
1146     Info.flags |= MachineMemOperand::MODereferenceable;
1147     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1148       unsigned DMaskLanes = 4;
1149 
1150       if (RsrcIntr->IsImage) {
1151         const AMDGPU::ImageDimIntrinsicInfo *Intr
1152           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1153         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1154           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1155 
1156         if (!BaseOpcode->Gather4) {
1157           // If this isn't a gather, we may have excess loaded elements in the
1158           // IR type. Check the dmask for the real number of elements loaded.
1159           unsigned DMask
1160             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1161           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1162         }
1163 
1164         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1165       } else
1166         Info.memVT = EVT::getEVT(CI.getType());
1167 
1168       // FIXME: What does alignment mean for an image?
1169       Info.opc = ISD::INTRINSIC_W_CHAIN;
1170       Info.flags |= MachineMemOperand::MOLoad;
1171     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1172       Info.opc = ISD::INTRINSIC_VOID;
1173 
1174       Type *DataTy = CI.getArgOperand(0)->getType();
1175       if (RsrcIntr->IsImage) {
1176         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1177         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1178         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1179       } else
1180         Info.memVT = EVT::getEVT(DataTy);
1181 
1182       Info.flags |= MachineMemOperand::MOStore;
1183     } else {
1184       // Atomic
1185       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1186                                             ISD::INTRINSIC_W_CHAIN;
1187       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1188       Info.flags |= MachineMemOperand::MOLoad |
1189                     MachineMemOperand::MOStore |
1190                     MachineMemOperand::MODereferenceable;
1191 
1192       // XXX - Should this be volatile without known ordering?
1193       Info.flags |= MachineMemOperand::MOVolatile;
1194     }
1195     return true;
1196   }
1197 
1198   switch (IntrID) {
1199   case Intrinsic::amdgcn_atomic_inc:
1200   case Intrinsic::amdgcn_atomic_dec:
1201   case Intrinsic::amdgcn_ds_ordered_add:
1202   case Intrinsic::amdgcn_ds_ordered_swap:
1203   case Intrinsic::amdgcn_ds_fadd:
1204   case Intrinsic::amdgcn_ds_fmin:
1205   case Intrinsic::amdgcn_ds_fmax: {
1206     Info.opc = ISD::INTRINSIC_W_CHAIN;
1207     Info.memVT = MVT::getVT(CI.getType());
1208     Info.ptrVal = CI.getOperand(0);
1209     Info.align.reset();
1210     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1211 
1212     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1213     if (!Vol->isZero())
1214       Info.flags |= MachineMemOperand::MOVolatile;
1215 
1216     return true;
1217   }
1218   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1219     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1220 
1221     Info.opc = ISD::INTRINSIC_W_CHAIN;
1222     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1223     Info.ptrVal =
1224         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1225     Info.align.reset();
1226     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1227 
1228     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1229     if (!Vol || !Vol->isZero())
1230       Info.flags |= MachineMemOperand::MOVolatile;
1231 
1232     return true;
1233   }
1234   case Intrinsic::amdgcn_ds_append:
1235   case Intrinsic::amdgcn_ds_consume: {
1236     Info.opc = ISD::INTRINSIC_W_CHAIN;
1237     Info.memVT = MVT::getVT(CI.getType());
1238     Info.ptrVal = CI.getOperand(0);
1239     Info.align.reset();
1240     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1241 
1242     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1243     if (!Vol->isZero())
1244       Info.flags |= MachineMemOperand::MOVolatile;
1245 
1246     return true;
1247   }
1248   case Intrinsic::amdgcn_global_atomic_csub: {
1249     Info.opc = ISD::INTRINSIC_W_CHAIN;
1250     Info.memVT = MVT::getVT(CI.getType());
1251     Info.ptrVal = CI.getOperand(0);
1252     Info.align.reset();
1253     Info.flags |= MachineMemOperand::MOLoad |
1254                   MachineMemOperand::MOStore |
1255                   MachineMemOperand::MOVolatile;
1256     return true;
1257   }
1258   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1259     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1260     Info.opc = ISD::INTRINSIC_W_CHAIN;
1261     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1262     Info.ptrVal =
1263         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1264     Info.align.reset();
1265     Info.flags |= MachineMemOperand::MOLoad |
1266                   MachineMemOperand::MODereferenceable;
1267     return true;
1268   }
1269   case Intrinsic::amdgcn_global_atomic_fadd:
1270   case Intrinsic::amdgcn_global_atomic_fmin:
1271   case Intrinsic::amdgcn_global_atomic_fmax:
1272   case Intrinsic::amdgcn_flat_atomic_fadd:
1273   case Intrinsic::amdgcn_flat_atomic_fmin:
1274   case Intrinsic::amdgcn_flat_atomic_fmax:
1275   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1276   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1277     Info.opc = ISD::INTRINSIC_W_CHAIN;
1278     Info.memVT = MVT::getVT(CI.getType());
1279     Info.ptrVal = CI.getOperand(0);
1280     Info.align.reset();
1281     Info.flags |= MachineMemOperand::MOLoad |
1282                   MachineMemOperand::MOStore |
1283                   MachineMemOperand::MODereferenceable |
1284                   MachineMemOperand::MOVolatile;
1285     return true;
1286   }
1287   case Intrinsic::amdgcn_ds_gws_init:
1288   case Intrinsic::amdgcn_ds_gws_barrier:
1289   case Intrinsic::amdgcn_ds_gws_sema_v:
1290   case Intrinsic::amdgcn_ds_gws_sema_br:
1291   case Intrinsic::amdgcn_ds_gws_sema_p:
1292   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1293     Info.opc = ISD::INTRINSIC_VOID;
1294 
1295     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1296     Info.ptrVal =
1297         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1298 
1299     // This is an abstract access, but we need to specify a type and size.
1300     Info.memVT = MVT::i32;
1301     Info.size = 4;
1302     Info.align = Align(4);
1303 
1304     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1305       Info.flags |= MachineMemOperand::MOLoad;
1306     else
1307       Info.flags |= MachineMemOperand::MOStore;
1308     return true;
1309   }
1310   default:
1311     return false;
1312   }
1313 }
1314 
1315 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1316                                             SmallVectorImpl<Value*> &Ops,
1317                                             Type *&AccessTy) const {
1318   switch (II->getIntrinsicID()) {
1319   case Intrinsic::amdgcn_atomic_inc:
1320   case Intrinsic::amdgcn_atomic_dec:
1321   case Intrinsic::amdgcn_ds_ordered_add:
1322   case Intrinsic::amdgcn_ds_ordered_swap:
1323   case Intrinsic::amdgcn_ds_append:
1324   case Intrinsic::amdgcn_ds_consume:
1325   case Intrinsic::amdgcn_ds_fadd:
1326   case Intrinsic::amdgcn_ds_fmin:
1327   case Intrinsic::amdgcn_ds_fmax:
1328   case Intrinsic::amdgcn_global_atomic_fadd:
1329   case Intrinsic::amdgcn_flat_atomic_fadd:
1330   case Intrinsic::amdgcn_flat_atomic_fmin:
1331   case Intrinsic::amdgcn_flat_atomic_fmax:
1332   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1333   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1334   case Intrinsic::amdgcn_global_atomic_csub: {
1335     Value *Ptr = II->getArgOperand(0);
1336     AccessTy = II->getType();
1337     Ops.push_back(Ptr);
1338     return true;
1339   }
1340   default:
1341     return false;
1342   }
1343 }
1344 
1345 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1346   if (!Subtarget->hasFlatInstOffsets()) {
1347     // Flat instructions do not have offsets, and only have the register
1348     // address.
1349     return AM.BaseOffs == 0 && AM.Scale == 0;
1350   }
1351 
1352   return AM.Scale == 0 &&
1353          (AM.BaseOffs == 0 ||
1354           Subtarget->getInstrInfo()->isLegalFLATOffset(
1355               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1356 }
1357 
1358 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1359   if (Subtarget->hasFlatGlobalInsts())
1360     return AM.Scale == 0 &&
1361            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1362                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1363                                     SIInstrFlags::FlatGlobal));
1364 
1365   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1366       // Assume the we will use FLAT for all global memory accesses
1367       // on VI.
1368       // FIXME: This assumption is currently wrong.  On VI we still use
1369       // MUBUF instructions for the r + i addressing mode.  As currently
1370       // implemented, the MUBUF instructions only work on buffer < 4GB.
1371       // It may be possible to support > 4GB buffers with MUBUF instructions,
1372       // by setting the stride value in the resource descriptor which would
1373       // increase the size limit to (stride * 4GB).  However, this is risky,
1374       // because it has never been validated.
1375     return isLegalFlatAddressingMode(AM);
1376   }
1377 
1378   return isLegalMUBUFAddressingMode(AM);
1379 }
1380 
1381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1382   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1383   // additionally can do r + r + i with addr64. 32-bit has more addressing
1384   // mode options. Depending on the resource constant, it can also do
1385   // (i64 r0) + (i32 r1) * (i14 i).
1386   //
1387   // Private arrays end up using a scratch buffer most of the time, so also
1388   // assume those use MUBUF instructions. Scratch loads / stores are currently
1389   // implemented as mubuf instructions with offen bit set, so slightly
1390   // different than the normal addr64.
1391   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1392     return false;
1393 
1394   // FIXME: Since we can split immediate into soffset and immediate offset,
1395   // would it make sense to allow any immediate?
1396 
1397   switch (AM.Scale) {
1398   case 0: // r + i or just i, depending on HasBaseReg.
1399     return true;
1400   case 1:
1401     return true; // We have r + r or r + i.
1402   case 2:
1403     if (AM.HasBaseReg) {
1404       // Reject 2 * r + r.
1405       return false;
1406     }
1407 
1408     // Allow 2 * r as r + r
1409     // Or  2 * r + i is allowed as r + r + i.
1410     return true;
1411   default: // Don't allow n * r
1412     return false;
1413   }
1414 }
1415 
1416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1417                                              const AddrMode &AM, Type *Ty,
1418                                              unsigned AS, Instruction *I) const {
1419   // No global is ever allowed as a base.
1420   if (AM.BaseGV)
1421     return false;
1422 
1423   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1424     return isLegalGlobalAddressingMode(AM);
1425 
1426   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1427       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1428       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1429     // If the offset isn't a multiple of 4, it probably isn't going to be
1430     // correctly aligned.
1431     // FIXME: Can we get the real alignment here?
1432     if (AM.BaseOffs % 4 != 0)
1433       return isLegalMUBUFAddressingMode(AM);
1434 
1435     // There are no SMRD extloads, so if we have to do a small type access we
1436     // will use a MUBUF load.
1437     // FIXME?: We also need to do this if unaligned, but we don't know the
1438     // alignment here.
1439     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1440       return isLegalGlobalAddressingMode(AM);
1441 
1442     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1443       // SMRD instructions have an 8-bit, dword offset on SI.
1444       if (!isUInt<8>(AM.BaseOffs / 4))
1445         return false;
1446     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1447       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1448       // in 8-bits, it can use a smaller encoding.
1449       if (!isUInt<32>(AM.BaseOffs / 4))
1450         return false;
1451     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1452       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1453       if (!isUInt<20>(AM.BaseOffs))
1454         return false;
1455     } else
1456       llvm_unreachable("unhandled generation");
1457 
1458     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1459       return true;
1460 
1461     if (AM.Scale == 1 && AM.HasBaseReg)
1462       return true;
1463 
1464     return false;
1465 
1466   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1467     return isLegalMUBUFAddressingMode(AM);
1468   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1469              AS == AMDGPUAS::REGION_ADDRESS) {
1470     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1471     // field.
1472     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1473     // an 8-bit dword offset but we don't know the alignment here.
1474     if (!isUInt<16>(AM.BaseOffs))
1475       return false;
1476 
1477     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1478       return true;
1479 
1480     if (AM.Scale == 1 && AM.HasBaseReg)
1481       return true;
1482 
1483     return false;
1484   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1485              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1486     // For an unknown address space, this usually means that this is for some
1487     // reason being used for pure arithmetic, and not based on some addressing
1488     // computation. We don't have instructions that compute pointers with any
1489     // addressing modes, so treat them as having no offset like flat
1490     // instructions.
1491     return isLegalFlatAddressingMode(AM);
1492   }
1493 
1494   // Assume a user alias of global for unknown address spaces.
1495   return isLegalGlobalAddressingMode(AM);
1496 }
1497 
1498 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1499                                         const MachineFunction &MF) const {
1500   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1501     return (MemVT.getSizeInBits() <= 4 * 32);
1502   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1503     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1504     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1505   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1506     return (MemVT.getSizeInBits() <= 2 * 32);
1507   }
1508   return true;
1509 }
1510 
1511 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1512     unsigned Size, unsigned AddrSpace, Align Alignment,
1513     MachineMemOperand::Flags Flags, bool *IsFast) const {
1514   if (IsFast)
1515     *IsFast = false;
1516 
1517   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1518       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1519     // Check if alignment requirements for ds_read/write instructions are
1520     // disabled.
1521     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1522       return false;
1523 
1524     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1525     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1526         Alignment < RequiredAlignment)
1527       return false;
1528 
1529     // Either, the alignment requirements are "enabled", or there is an
1530     // unaligned LDS access related hardware bug though alignment requirements
1531     // are "disabled". In either case, we need to check for proper alignment
1532     // requirements.
1533     //
1534     switch (Size) {
1535     case 64:
1536       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1537       // address is negative, then the instruction is incorrectly treated as
1538       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1539       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1540       // load later in the SILoadStoreOptimizer.
1541       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1542         return false;
1543 
1544       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1545       // can do a 4 byte aligned, 8 byte access in a single operation using
1546       // ds_read2/write2_b32 with adjacent offsets.
1547       RequiredAlignment = Align(4);
1548 
1549       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1550         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1551         // ds_write2_b32 depending on the alignment. In either case with either
1552         // alignment there is no faster way of doing this.
1553         if (IsFast)
1554           *IsFast = true;
1555         return true;
1556       }
1557 
1558       break;
1559     case 96:
1560       if (!Subtarget->hasDS96AndDS128())
1561         return false;
1562 
1563       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1564       // gfx8 and older.
1565 
1566       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1567         // Naturally aligned access is fastest. However, also report it is Fast
1568         // if memory is aligned less than DWORD. A narrow load or store will be
1569         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1570         // be more of them, so overall we will pay less penalty issuing a single
1571         // instruction.
1572         if (IsFast)
1573           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1574         return true;
1575       }
1576 
1577       break;
1578     case 128:
1579       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1580         return false;
1581 
1582       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1583       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1584       // single operation using ds_read2/write2_b64.
1585       RequiredAlignment = Align(8);
1586 
1587       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1588         // Naturally aligned access is fastest. However, also report it is Fast
1589         // if memory is aligned less than DWORD. A narrow load or store will be
1590         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1591         // will be more of them, so overall we will pay less penalty issuing a
1592         // single instruction.
1593         if (IsFast)
1594           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1595         return true;
1596       }
1597 
1598       break;
1599     default:
1600       if (Size > 32)
1601         return false;
1602 
1603       break;
1604     }
1605 
1606     if (IsFast)
1607       *IsFast = Alignment >= RequiredAlignment;
1608 
1609     return Alignment >= RequiredAlignment ||
1610            Subtarget->hasUnalignedDSAccessEnabled();
1611   }
1612 
1613   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1614     bool AlignedBy4 = Alignment >= Align(4);
1615     if (IsFast)
1616       *IsFast = AlignedBy4;
1617 
1618     return AlignedBy4 ||
1619            Subtarget->enableFlatScratch() ||
1620            Subtarget->hasUnalignedScratchAccess();
1621   }
1622 
1623   // FIXME: We have to be conservative here and assume that flat operations
1624   // will access scratch.  If we had access to the IR function, then we
1625   // could determine if any private memory was used in the function.
1626   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1627       !Subtarget->hasUnalignedScratchAccess()) {
1628     bool AlignedBy4 = Alignment >= Align(4);
1629     if (IsFast)
1630       *IsFast = AlignedBy4;
1631 
1632     return AlignedBy4;
1633   }
1634 
1635   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1636     // If we have a uniform constant load, it still requires using a slow
1637     // buffer instruction if unaligned.
1638     if (IsFast) {
1639       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1640       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1641       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1642                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1643         Alignment >= Align(4) : Alignment != Align(2);
1644     }
1645 
1646     return true;
1647   }
1648 
1649   // Smaller than dword value must be aligned.
1650   if (Size < 32)
1651     return false;
1652 
1653   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1654   // byte-address are ignored, thus forcing Dword alignment.
1655   // This applies to private, global, and constant memory.
1656   if (IsFast)
1657     *IsFast = true;
1658 
1659   return Size >= 32 && Alignment >= Align(4);
1660 }
1661 
1662 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1663     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1664     bool *IsFast) const {
1665   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1666                                                   Alignment, Flags, IsFast);
1667 
1668   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1669       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1670        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1671     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1672     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1673     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1674     // which would be equally misaligned.
1675     // This is only used by the common passes, selection always calls the
1676     // allowsMisalignedMemoryAccessesImpl version.
1677     *IsFast = true;
1678   }
1679 
1680   return Allow;
1681 }
1682 
1683 EVT SITargetLowering::getOptimalMemOpType(
1684     const MemOp &Op, const AttributeList &FuncAttributes) const {
1685   // FIXME: Should account for address space here.
1686 
1687   // The default fallback uses the private pointer size as a guess for a type to
1688   // use. Make sure we switch these to 64-bit accesses.
1689 
1690   if (Op.size() >= 16 &&
1691       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1692     return MVT::v4i32;
1693 
1694   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1695     return MVT::v2i32;
1696 
1697   // Use the default.
1698   return MVT::Other;
1699 }
1700 
1701 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1702   const MemSDNode *MemNode = cast<MemSDNode>(N);
1703   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1704 }
1705 
1706 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1707   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1708          AS == AMDGPUAS::PRIVATE_ADDRESS;
1709 }
1710 
1711 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1712                                            unsigned DestAS) const {
1713   // Flat -> private/local is a simple truncate.
1714   // Flat -> global is no-op
1715   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1716     return true;
1717 
1718   const GCNTargetMachine &TM =
1719       static_cast<const GCNTargetMachine &>(getTargetMachine());
1720   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1721 }
1722 
1723 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1724   const MemSDNode *MemNode = cast<MemSDNode>(N);
1725 
1726   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1727 }
1728 
1729 TargetLoweringBase::LegalizeTypeAction
1730 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1731   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1732       VT.getScalarType().bitsLE(MVT::i16))
1733     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1734   return TargetLoweringBase::getPreferredVectorAction(VT);
1735 }
1736 
1737 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1738                                                          Type *Ty) const {
1739   // FIXME: Could be smarter if called for vector constants.
1740   return true;
1741 }
1742 
1743 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1744   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1745     switch (Op) {
1746     case ISD::LOAD:
1747     case ISD::STORE:
1748 
1749     // These operations are done with 32-bit instructions anyway.
1750     case ISD::AND:
1751     case ISD::OR:
1752     case ISD::XOR:
1753     case ISD::SELECT:
1754       // TODO: Extensions?
1755       return true;
1756     default:
1757       return false;
1758     }
1759   }
1760 
1761   // SimplifySetCC uses this function to determine whether or not it should
1762   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1763   if (VT == MVT::i1 && Op == ISD::SETCC)
1764     return false;
1765 
1766   return TargetLowering::isTypeDesirableForOp(Op, VT);
1767 }
1768 
1769 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1770                                                    const SDLoc &SL,
1771                                                    SDValue Chain,
1772                                                    uint64_t Offset) const {
1773   const DataLayout &DL = DAG.getDataLayout();
1774   MachineFunction &MF = DAG.getMachineFunction();
1775   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1776 
1777   const ArgDescriptor *InputPtrReg;
1778   const TargetRegisterClass *RC;
1779   LLT ArgTy;
1780   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1781 
1782   std::tie(InputPtrReg, RC, ArgTy) =
1783       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1784 
1785   // We may not have the kernarg segment argument if we have no kernel
1786   // arguments.
1787   if (!InputPtrReg)
1788     return DAG.getConstant(0, SL, PtrVT);
1789 
1790   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1791   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1792     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1793 
1794   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1795 }
1796 
1797 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1798                                             const SDLoc &SL) const {
1799   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1800                                                FIRST_IMPLICIT);
1801   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1802 }
1803 
1804 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1805                                          const SDLoc &SL, SDValue Val,
1806                                          bool Signed,
1807                                          const ISD::InputArg *Arg) const {
1808   // First, if it is a widened vector, narrow it.
1809   if (VT.isVector() &&
1810       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1811     EVT NarrowedVT =
1812         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1813                          VT.getVectorNumElements());
1814     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1815                       DAG.getConstant(0, SL, MVT::i32));
1816   }
1817 
1818   // Then convert the vector elements or scalar value.
1819   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1820       VT.bitsLT(MemVT)) {
1821     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1822     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1823   }
1824 
1825   if (MemVT.isFloatingPoint())
1826     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1827   else if (Signed)
1828     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1829   else
1830     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1831 
1832   return Val;
1833 }
1834 
1835 SDValue SITargetLowering::lowerKernargMemParameter(
1836     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1837     uint64_t Offset, Align Alignment, bool Signed,
1838     const ISD::InputArg *Arg) const {
1839   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1840 
1841   // Try to avoid using an extload by loading earlier than the argument address,
1842   // and extracting the relevant bits. The load should hopefully be merged with
1843   // the previous argument.
1844   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1845     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1846     int64_t AlignDownOffset = alignDown(Offset, 4);
1847     int64_t OffsetDiff = Offset - AlignDownOffset;
1848 
1849     EVT IntVT = MemVT.changeTypeToInteger();
1850 
1851     // TODO: If we passed in the base kernel offset we could have a better
1852     // alignment than 4, but we don't really need it.
1853     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1854     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1855                                MachineMemOperand::MODereferenceable |
1856                                    MachineMemOperand::MOInvariant);
1857 
1858     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1859     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1860 
1861     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1862     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1863     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1864 
1865 
1866     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1867   }
1868 
1869   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1870   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1871                              MachineMemOperand::MODereferenceable |
1872                                  MachineMemOperand::MOInvariant);
1873 
1874   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1875   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1876 }
1877 
1878 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1879                                               const SDLoc &SL, SDValue Chain,
1880                                               const ISD::InputArg &Arg) const {
1881   MachineFunction &MF = DAG.getMachineFunction();
1882   MachineFrameInfo &MFI = MF.getFrameInfo();
1883 
1884   if (Arg.Flags.isByVal()) {
1885     unsigned Size = Arg.Flags.getByValSize();
1886     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1887     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1888   }
1889 
1890   unsigned ArgOffset = VA.getLocMemOffset();
1891   unsigned ArgSize = VA.getValVT().getStoreSize();
1892 
1893   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1894 
1895   // Create load nodes to retrieve arguments from the stack.
1896   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1897   SDValue ArgValue;
1898 
1899   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1900   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1901   MVT MemVT = VA.getValVT();
1902 
1903   switch (VA.getLocInfo()) {
1904   default:
1905     break;
1906   case CCValAssign::BCvt:
1907     MemVT = VA.getLocVT();
1908     break;
1909   case CCValAssign::SExt:
1910     ExtType = ISD::SEXTLOAD;
1911     break;
1912   case CCValAssign::ZExt:
1913     ExtType = ISD::ZEXTLOAD;
1914     break;
1915   case CCValAssign::AExt:
1916     ExtType = ISD::EXTLOAD;
1917     break;
1918   }
1919 
1920   ArgValue = DAG.getExtLoad(
1921     ExtType, SL, VA.getLocVT(), Chain, FIN,
1922     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1923     MemVT);
1924   return ArgValue;
1925 }
1926 
1927 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1928   const SIMachineFunctionInfo &MFI,
1929   EVT VT,
1930   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1931   const ArgDescriptor *Reg;
1932   const TargetRegisterClass *RC;
1933   LLT Ty;
1934 
1935   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1936   if (!Reg) {
1937     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1938       // It's possible for a kernarg intrinsic call to appear in a kernel with
1939       // no allocated segment, in which case we do not add the user sgpr
1940       // argument, so just return null.
1941       return DAG.getConstant(0, SDLoc(), VT);
1942     }
1943 
1944     // It's undefined behavior if a function marked with the amdgpu-no-*
1945     // attributes uses the corresponding intrinsic.
1946     return DAG.getUNDEF(VT);
1947   }
1948 
1949   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1950 }
1951 
1952 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1953                                CallingConv::ID CallConv,
1954                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1955                                FunctionType *FType,
1956                                SIMachineFunctionInfo *Info) {
1957   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1958     const ISD::InputArg *Arg = &Ins[I];
1959 
1960     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1961            "vector type argument should have been split");
1962 
1963     // First check if it's a PS input addr.
1964     if (CallConv == CallingConv::AMDGPU_PS &&
1965         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1966       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1967 
1968       // Inconveniently only the first part of the split is marked as isSplit,
1969       // so skip to the end. We only want to increment PSInputNum once for the
1970       // entire split argument.
1971       if (Arg->Flags.isSplit()) {
1972         while (!Arg->Flags.isSplitEnd()) {
1973           assert((!Arg->VT.isVector() ||
1974                   Arg->VT.getScalarSizeInBits() == 16) &&
1975                  "unexpected vector split in ps argument type");
1976           if (!SkipArg)
1977             Splits.push_back(*Arg);
1978           Arg = &Ins[++I];
1979         }
1980       }
1981 
1982       if (SkipArg) {
1983         // We can safely skip PS inputs.
1984         Skipped.set(Arg->getOrigArgIndex());
1985         ++PSInputNum;
1986         continue;
1987       }
1988 
1989       Info->markPSInputAllocated(PSInputNum);
1990       if (Arg->Used)
1991         Info->markPSInputEnabled(PSInputNum);
1992 
1993       ++PSInputNum;
1994     }
1995 
1996     Splits.push_back(*Arg);
1997   }
1998 }
1999 
2000 // Allocate special inputs passed in VGPRs.
2001 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
2002                                                       MachineFunction &MF,
2003                                                       const SIRegisterInfo &TRI,
2004                                                       SIMachineFunctionInfo &Info) const {
2005   const LLT S32 = LLT::scalar(32);
2006   MachineRegisterInfo &MRI = MF.getRegInfo();
2007 
2008   if (Info.hasWorkItemIDX()) {
2009     Register Reg = AMDGPU::VGPR0;
2010     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2011 
2012     CCInfo.AllocateReg(Reg);
2013     unsigned Mask = (Subtarget->hasPackedTID() &&
2014                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2015     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2016   }
2017 
2018   if (Info.hasWorkItemIDY()) {
2019     assert(Info.hasWorkItemIDX());
2020     if (Subtarget->hasPackedTID()) {
2021       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2022                                                         0x3ff << 10));
2023     } else {
2024       unsigned Reg = AMDGPU::VGPR1;
2025       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2026 
2027       CCInfo.AllocateReg(Reg);
2028       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2029     }
2030   }
2031 
2032   if (Info.hasWorkItemIDZ()) {
2033     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2034     if (Subtarget->hasPackedTID()) {
2035       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2036                                                         0x3ff << 20));
2037     } else {
2038       unsigned Reg = AMDGPU::VGPR2;
2039       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2040 
2041       CCInfo.AllocateReg(Reg);
2042       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2043     }
2044   }
2045 }
2046 
2047 // Try to allocate a VGPR at the end of the argument list, or if no argument
2048 // VGPRs are left allocating a stack slot.
2049 // If \p Mask is is given it indicates bitfield position in the register.
2050 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2051 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2052                                          ArgDescriptor Arg = ArgDescriptor()) {
2053   if (Arg.isSet())
2054     return ArgDescriptor::createArg(Arg, Mask);
2055 
2056   ArrayRef<MCPhysReg> ArgVGPRs
2057     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2058   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2059   if (RegIdx == ArgVGPRs.size()) {
2060     // Spill to stack required.
2061     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2062 
2063     return ArgDescriptor::createStack(Offset, Mask);
2064   }
2065 
2066   unsigned Reg = ArgVGPRs[RegIdx];
2067   Reg = CCInfo.AllocateReg(Reg);
2068   assert(Reg != AMDGPU::NoRegister);
2069 
2070   MachineFunction &MF = CCInfo.getMachineFunction();
2071   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2072   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2073   return ArgDescriptor::createRegister(Reg, Mask);
2074 }
2075 
2076 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2077                                              const TargetRegisterClass *RC,
2078                                              unsigned NumArgRegs) {
2079   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2080   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2081   if (RegIdx == ArgSGPRs.size())
2082     report_fatal_error("ran out of SGPRs for arguments");
2083 
2084   unsigned Reg = ArgSGPRs[RegIdx];
2085   Reg = CCInfo.AllocateReg(Reg);
2086   assert(Reg != AMDGPU::NoRegister);
2087 
2088   MachineFunction &MF = CCInfo.getMachineFunction();
2089   MF.addLiveIn(Reg, RC);
2090   return ArgDescriptor::createRegister(Reg);
2091 }
2092 
2093 // If this has a fixed position, we still should allocate the register in the
2094 // CCInfo state. Technically we could get away with this for values passed
2095 // outside of the normal argument range.
2096 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2097                                        const TargetRegisterClass *RC,
2098                                        MCRegister Reg) {
2099   Reg = CCInfo.AllocateReg(Reg);
2100   assert(Reg != AMDGPU::NoRegister);
2101   MachineFunction &MF = CCInfo.getMachineFunction();
2102   MF.addLiveIn(Reg, RC);
2103 }
2104 
2105 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2106   if (Arg) {
2107     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2108                                Arg.getRegister());
2109   } else
2110     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2111 }
2112 
2113 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2114   if (Arg) {
2115     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2116                                Arg.getRegister());
2117   } else
2118     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2119 }
2120 
2121 /// Allocate implicit function VGPR arguments at the end of allocated user
2122 /// arguments.
2123 void SITargetLowering::allocateSpecialInputVGPRs(
2124   CCState &CCInfo, MachineFunction &MF,
2125   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2126   const unsigned Mask = 0x3ff;
2127   ArgDescriptor Arg;
2128 
2129   if (Info.hasWorkItemIDX()) {
2130     Arg = allocateVGPR32Input(CCInfo, Mask);
2131     Info.setWorkItemIDX(Arg);
2132   }
2133 
2134   if (Info.hasWorkItemIDY()) {
2135     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2136     Info.setWorkItemIDY(Arg);
2137   }
2138 
2139   if (Info.hasWorkItemIDZ())
2140     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2141 }
2142 
2143 /// Allocate implicit function VGPR arguments in fixed registers.
2144 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2145   CCState &CCInfo, MachineFunction &MF,
2146   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2147   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2148   if (!Reg)
2149     report_fatal_error("failed to allocated VGPR for implicit arguments");
2150 
2151   const unsigned Mask = 0x3ff;
2152   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2153   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2154   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2155 }
2156 
2157 void SITargetLowering::allocateSpecialInputSGPRs(
2158   CCState &CCInfo,
2159   MachineFunction &MF,
2160   const SIRegisterInfo &TRI,
2161   SIMachineFunctionInfo &Info) const {
2162   auto &ArgInfo = Info.getArgInfo();
2163 
2164   // TODO: Unify handling with private memory pointers.
2165   if (Info.hasDispatchPtr())
2166     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2167 
2168   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2169     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2170 
2171   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2172   // constant offset from the kernarg segment.
2173   if (Info.hasImplicitArgPtr())
2174     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2175 
2176   if (Info.hasDispatchID())
2177     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2178 
2179   // flat_scratch_init is not applicable for non-kernel functions.
2180 
2181   if (Info.hasWorkGroupIDX())
2182     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2183 
2184   if (Info.hasWorkGroupIDY())
2185     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2186 
2187   if (Info.hasWorkGroupIDZ())
2188     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2189 }
2190 
2191 // Allocate special inputs passed in user SGPRs.
2192 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2193                                             MachineFunction &MF,
2194                                             const SIRegisterInfo &TRI,
2195                                             SIMachineFunctionInfo &Info) const {
2196   if (Info.hasImplicitBufferPtr()) {
2197     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2198     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2199     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2200   }
2201 
2202   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2203   if (Info.hasPrivateSegmentBuffer()) {
2204     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2205     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2206     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2207   }
2208 
2209   if (Info.hasDispatchPtr()) {
2210     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2211     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2212     CCInfo.AllocateReg(DispatchPtrReg);
2213   }
2214 
2215   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2216     Register QueuePtrReg = Info.addQueuePtr(TRI);
2217     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2218     CCInfo.AllocateReg(QueuePtrReg);
2219   }
2220 
2221   if (Info.hasKernargSegmentPtr()) {
2222     MachineRegisterInfo &MRI = MF.getRegInfo();
2223     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2224     CCInfo.AllocateReg(InputPtrReg);
2225 
2226     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2227     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2228   }
2229 
2230   if (Info.hasDispatchID()) {
2231     Register DispatchIDReg = Info.addDispatchID(TRI);
2232     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2233     CCInfo.AllocateReg(DispatchIDReg);
2234   }
2235 
2236   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2237     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2238     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2239     CCInfo.AllocateReg(FlatScratchInitReg);
2240   }
2241 
2242   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2243   // these from the dispatch pointer.
2244 }
2245 
2246 // Allocate special input registers that are initialized per-wave.
2247 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2248                                            MachineFunction &MF,
2249                                            SIMachineFunctionInfo &Info,
2250                                            CallingConv::ID CallConv,
2251                                            bool IsShader) const {
2252   if (Info.hasWorkGroupIDX()) {
2253     Register Reg = Info.addWorkGroupIDX();
2254     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2255     CCInfo.AllocateReg(Reg);
2256   }
2257 
2258   if (Info.hasWorkGroupIDY()) {
2259     Register Reg = Info.addWorkGroupIDY();
2260     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2261     CCInfo.AllocateReg(Reg);
2262   }
2263 
2264   if (Info.hasWorkGroupIDZ()) {
2265     Register Reg = Info.addWorkGroupIDZ();
2266     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2267     CCInfo.AllocateReg(Reg);
2268   }
2269 
2270   if (Info.hasWorkGroupInfo()) {
2271     Register Reg = Info.addWorkGroupInfo();
2272     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2273     CCInfo.AllocateReg(Reg);
2274   }
2275 
2276   if (Info.hasPrivateSegmentWaveByteOffset()) {
2277     // Scratch wave offset passed in system SGPR.
2278     unsigned PrivateSegmentWaveByteOffsetReg;
2279 
2280     if (IsShader) {
2281       PrivateSegmentWaveByteOffsetReg =
2282         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2283 
2284       // This is true if the scratch wave byte offset doesn't have a fixed
2285       // location.
2286       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2287         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2288         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2289       }
2290     } else
2291       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2292 
2293     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2294     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2295   }
2296 }
2297 
2298 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2299                                      MachineFunction &MF,
2300                                      const SIRegisterInfo &TRI,
2301                                      SIMachineFunctionInfo &Info) {
2302   // Now that we've figured out where the scratch register inputs are, see if
2303   // should reserve the arguments and use them directly.
2304   MachineFrameInfo &MFI = MF.getFrameInfo();
2305   bool HasStackObjects = MFI.hasStackObjects();
2306   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2307 
2308   // Record that we know we have non-spill stack objects so we don't need to
2309   // check all stack objects later.
2310   if (HasStackObjects)
2311     Info.setHasNonSpillStackObjects(true);
2312 
2313   // Everything live out of a block is spilled with fast regalloc, so it's
2314   // almost certain that spilling will be required.
2315   if (TM.getOptLevel() == CodeGenOpt::None)
2316     HasStackObjects = true;
2317 
2318   // For now assume stack access is needed in any callee functions, so we need
2319   // the scratch registers to pass in.
2320   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2321 
2322   if (!ST.enableFlatScratch()) {
2323     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2324       // If we have stack objects, we unquestionably need the private buffer
2325       // resource. For the Code Object V2 ABI, this will be the first 4 user
2326       // SGPR inputs. We can reserve those and use them directly.
2327 
2328       Register PrivateSegmentBufferReg =
2329           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2330       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2331     } else {
2332       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2333       // We tentatively reserve the last registers (skipping the last registers
2334       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2335       // we'll replace these with the ones immediately after those which were
2336       // really allocated. In the prologue copies will be inserted from the
2337       // argument to these reserved registers.
2338 
2339       // Without HSA, relocations are used for the scratch pointer and the
2340       // buffer resource setup is always inserted in the prologue. Scratch wave
2341       // offset is still in an input SGPR.
2342       Info.setScratchRSrcReg(ReservedBufferReg);
2343     }
2344   }
2345 
2346   MachineRegisterInfo &MRI = MF.getRegInfo();
2347 
2348   // For entry functions we have to set up the stack pointer if we use it,
2349   // whereas non-entry functions get this "for free". This means there is no
2350   // intrinsic advantage to using S32 over S34 in cases where we do not have
2351   // calls but do need a frame pointer (i.e. if we are requested to have one
2352   // because frame pointer elimination is disabled). To keep things simple we
2353   // only ever use S32 as the call ABI stack pointer, and so using it does not
2354   // imply we need a separate frame pointer.
2355   //
2356   // Try to use s32 as the SP, but move it if it would interfere with input
2357   // arguments. This won't work with calls though.
2358   //
2359   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2360   // registers.
2361   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2362     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2363   } else {
2364     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2365 
2366     if (MFI.hasCalls())
2367       report_fatal_error("call in graphics shader with too many input SGPRs");
2368 
2369     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2370       if (!MRI.isLiveIn(Reg)) {
2371         Info.setStackPtrOffsetReg(Reg);
2372         break;
2373       }
2374     }
2375 
2376     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2377       report_fatal_error("failed to find register for SP");
2378   }
2379 
2380   // hasFP should be accurate for entry functions even before the frame is
2381   // finalized, because it does not rely on the known stack size, only
2382   // properties like whether variable sized objects are present.
2383   if (ST.getFrameLowering()->hasFP(MF)) {
2384     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2385   }
2386 }
2387 
2388 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2389   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2390   return !Info->isEntryFunction();
2391 }
2392 
2393 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2394 
2395 }
2396 
2397 void SITargetLowering::insertCopiesSplitCSR(
2398   MachineBasicBlock *Entry,
2399   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2400   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2401 
2402   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2403   if (!IStart)
2404     return;
2405 
2406   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2407   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2408   MachineBasicBlock::iterator MBBI = Entry->begin();
2409   for (const MCPhysReg *I = IStart; *I; ++I) {
2410     const TargetRegisterClass *RC = nullptr;
2411     if (AMDGPU::SReg_64RegClass.contains(*I))
2412       RC = &AMDGPU::SGPR_64RegClass;
2413     else if (AMDGPU::SReg_32RegClass.contains(*I))
2414       RC = &AMDGPU::SGPR_32RegClass;
2415     else
2416       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2417 
2418     Register NewVR = MRI->createVirtualRegister(RC);
2419     // Create copy from CSR to a virtual register.
2420     Entry->addLiveIn(*I);
2421     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2422       .addReg(*I);
2423 
2424     // Insert the copy-back instructions right before the terminator.
2425     for (auto *Exit : Exits)
2426       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2427               TII->get(TargetOpcode::COPY), *I)
2428         .addReg(NewVR);
2429   }
2430 }
2431 
2432 SDValue SITargetLowering::LowerFormalArguments(
2433     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2434     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2435     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2436   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2437 
2438   MachineFunction &MF = DAG.getMachineFunction();
2439   const Function &Fn = MF.getFunction();
2440   FunctionType *FType = MF.getFunction().getFunctionType();
2441   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2442 
2443   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2444     DiagnosticInfoUnsupported NoGraphicsHSA(
2445         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2446     DAG.getContext()->diagnose(NoGraphicsHSA);
2447     return DAG.getEntryNode();
2448   }
2449 
2450   Info->allocateModuleLDSGlobal(Fn);
2451 
2452   SmallVector<ISD::InputArg, 16> Splits;
2453   SmallVector<CCValAssign, 16> ArgLocs;
2454   BitVector Skipped(Ins.size());
2455   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2456                  *DAG.getContext());
2457 
2458   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2459   bool IsKernel = AMDGPU::isKernel(CallConv);
2460   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2461 
2462   if (IsGraphics) {
2463     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2464            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2465            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2466            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2467            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2468            !Info->hasWorkItemIDZ());
2469   }
2470 
2471   if (CallConv == CallingConv::AMDGPU_PS) {
2472     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2473 
2474     // At least one interpolation mode must be enabled or else the GPU will
2475     // hang.
2476     //
2477     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2478     // set PSInputAddr, the user wants to enable some bits after the compilation
2479     // based on run-time states. Since we can't know what the final PSInputEna
2480     // will look like, so we shouldn't do anything here and the user should take
2481     // responsibility for the correct programming.
2482     //
2483     // Otherwise, the following restrictions apply:
2484     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2485     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2486     //   enabled too.
2487     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2488         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2489       CCInfo.AllocateReg(AMDGPU::VGPR0);
2490       CCInfo.AllocateReg(AMDGPU::VGPR1);
2491       Info->markPSInputAllocated(0);
2492       Info->markPSInputEnabled(0);
2493     }
2494     if (Subtarget->isAmdPalOS()) {
2495       // For isAmdPalOS, the user does not enable some bits after compilation
2496       // based on run-time states; the register values being generated here are
2497       // the final ones set in hardware. Therefore we need to apply the
2498       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2499       // a bit is set in PSInputAddr but not PSInputEnable is where the
2500       // frontend set up an input arg for a particular interpolation mode, but
2501       // nothing uses that input arg. Really we should have an earlier pass
2502       // that removes such an arg.)
2503       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2504       if ((PsInputBits & 0x7F) == 0 ||
2505           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2506         Info->markPSInputEnabled(
2507             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2508     }
2509   } else if (IsKernel) {
2510     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2511   } else {
2512     Splits.append(Ins.begin(), Ins.end());
2513   }
2514 
2515   if (IsEntryFunc) {
2516     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2517     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2518   } else if (!IsGraphics) {
2519     // For the fixed ABI, pass workitem IDs in the last argument register.
2520     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2521   }
2522 
2523   if (IsKernel) {
2524     analyzeFormalArgumentsCompute(CCInfo, Ins);
2525   } else {
2526     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2527     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2528   }
2529 
2530   SmallVector<SDValue, 16> Chains;
2531 
2532   // FIXME: This is the minimum kernel argument alignment. We should improve
2533   // this to the maximum alignment of the arguments.
2534   //
2535   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2536   // kern arg offset.
2537   const Align KernelArgBaseAlign = Align(16);
2538 
2539   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2540     const ISD::InputArg &Arg = Ins[i];
2541     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2542       InVals.push_back(DAG.getUNDEF(Arg.VT));
2543       continue;
2544     }
2545 
2546     CCValAssign &VA = ArgLocs[ArgIdx++];
2547     MVT VT = VA.getLocVT();
2548 
2549     if (IsEntryFunc && VA.isMemLoc()) {
2550       VT = Ins[i].VT;
2551       EVT MemVT = VA.getLocVT();
2552 
2553       const uint64_t Offset = VA.getLocMemOffset();
2554       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2555 
2556       if (Arg.Flags.isByRef()) {
2557         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2558 
2559         const GCNTargetMachine &TM =
2560             static_cast<const GCNTargetMachine &>(getTargetMachine());
2561         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2562                                     Arg.Flags.getPointerAddrSpace())) {
2563           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2564                                      Arg.Flags.getPointerAddrSpace());
2565         }
2566 
2567         InVals.push_back(Ptr);
2568         continue;
2569       }
2570 
2571       SDValue Arg = lowerKernargMemParameter(
2572         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2573       Chains.push_back(Arg.getValue(1));
2574 
2575       auto *ParamTy =
2576         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2577       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2578           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2579                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2580         // On SI local pointers are just offsets into LDS, so they are always
2581         // less than 16-bits.  On CI and newer they could potentially be
2582         // real pointers, so we can't guarantee their size.
2583         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2584                           DAG.getValueType(MVT::i16));
2585       }
2586 
2587       InVals.push_back(Arg);
2588       continue;
2589     } else if (!IsEntryFunc && VA.isMemLoc()) {
2590       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2591       InVals.push_back(Val);
2592       if (!Arg.Flags.isByVal())
2593         Chains.push_back(Val.getValue(1));
2594       continue;
2595     }
2596 
2597     assert(VA.isRegLoc() && "Parameter must be in a register!");
2598 
2599     Register Reg = VA.getLocReg();
2600     const TargetRegisterClass *RC = nullptr;
2601     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2602       RC = &AMDGPU::VGPR_32RegClass;
2603     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2604       RC = &AMDGPU::SGPR_32RegClass;
2605     else
2606       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2607     EVT ValVT = VA.getValVT();
2608 
2609     Reg = MF.addLiveIn(Reg, RC);
2610     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2611 
2612     if (Arg.Flags.isSRet()) {
2613       // The return object should be reasonably addressable.
2614 
2615       // FIXME: This helps when the return is a real sret. If it is a
2616       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2617       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2618       unsigned NumBits
2619         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2620       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2621         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2622     }
2623 
2624     // If this is an 8 or 16-bit value, it is really passed promoted
2625     // to 32 bits. Insert an assert[sz]ext to capture this, then
2626     // truncate to the right size.
2627     switch (VA.getLocInfo()) {
2628     case CCValAssign::Full:
2629       break;
2630     case CCValAssign::BCvt:
2631       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2632       break;
2633     case CCValAssign::SExt:
2634       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2635                         DAG.getValueType(ValVT));
2636       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2637       break;
2638     case CCValAssign::ZExt:
2639       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2640                         DAG.getValueType(ValVT));
2641       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2642       break;
2643     case CCValAssign::AExt:
2644       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2645       break;
2646     default:
2647       llvm_unreachable("Unknown loc info!");
2648     }
2649 
2650     InVals.push_back(Val);
2651   }
2652 
2653   // Start adding system SGPRs.
2654   if (IsEntryFunc) {
2655     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2656   } else {
2657     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2658     if (!IsGraphics)
2659       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2660   }
2661 
2662   auto &ArgUsageInfo =
2663     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2664   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2665 
2666   unsigned StackArgSize = CCInfo.getNextStackOffset();
2667   Info->setBytesInStackArgArea(StackArgSize);
2668 
2669   return Chains.empty() ? Chain :
2670     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2671 }
2672 
2673 // TODO: If return values can't fit in registers, we should return as many as
2674 // possible in registers before passing on stack.
2675 bool SITargetLowering::CanLowerReturn(
2676   CallingConv::ID CallConv,
2677   MachineFunction &MF, bool IsVarArg,
2678   const SmallVectorImpl<ISD::OutputArg> &Outs,
2679   LLVMContext &Context) const {
2680   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2681   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2682   // for shaders. Vector types should be explicitly handled by CC.
2683   if (AMDGPU::isEntryFunctionCC(CallConv))
2684     return true;
2685 
2686   SmallVector<CCValAssign, 16> RVLocs;
2687   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2688   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2689 }
2690 
2691 SDValue
2692 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2693                               bool isVarArg,
2694                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2695                               const SmallVectorImpl<SDValue> &OutVals,
2696                               const SDLoc &DL, SelectionDAG &DAG) const {
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2699 
2700   if (AMDGPU::isKernel(CallConv)) {
2701     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2702                                              OutVals, DL, DAG);
2703   }
2704 
2705   bool IsShader = AMDGPU::isShader(CallConv);
2706 
2707   Info->setIfReturnsVoid(Outs.empty());
2708   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2709 
2710   // CCValAssign - represent the assignment of the return value to a location.
2711   SmallVector<CCValAssign, 48> RVLocs;
2712   SmallVector<ISD::OutputArg, 48> Splits;
2713 
2714   // CCState - Info about the registers and stack slots.
2715   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2716                  *DAG.getContext());
2717 
2718   // Analyze outgoing return values.
2719   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2720 
2721   SDValue Flag;
2722   SmallVector<SDValue, 48> RetOps;
2723   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2724 
2725   // Copy the result values into the output registers.
2726   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2727        ++I, ++RealRVLocIdx) {
2728     CCValAssign &VA = RVLocs[I];
2729     assert(VA.isRegLoc() && "Can only return in registers!");
2730     // TODO: Partially return in registers if return values don't fit.
2731     SDValue Arg = OutVals[RealRVLocIdx];
2732 
2733     // Copied from other backends.
2734     switch (VA.getLocInfo()) {
2735     case CCValAssign::Full:
2736       break;
2737     case CCValAssign::BCvt:
2738       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2739       break;
2740     case CCValAssign::SExt:
2741       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2742       break;
2743     case CCValAssign::ZExt:
2744       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2745       break;
2746     case CCValAssign::AExt:
2747       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2748       break;
2749     default:
2750       llvm_unreachable("Unknown loc info!");
2751     }
2752 
2753     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2754     Flag = Chain.getValue(1);
2755     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2756   }
2757 
2758   // FIXME: Does sret work properly?
2759   if (!Info->isEntryFunction()) {
2760     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2761     const MCPhysReg *I =
2762       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2763     if (I) {
2764       for (; *I; ++I) {
2765         if (AMDGPU::SReg_64RegClass.contains(*I))
2766           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2767         else if (AMDGPU::SReg_32RegClass.contains(*I))
2768           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2769         else
2770           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2771       }
2772     }
2773   }
2774 
2775   // Update chain and glue.
2776   RetOps[0] = Chain;
2777   if (Flag.getNode())
2778     RetOps.push_back(Flag);
2779 
2780   unsigned Opc = AMDGPUISD::ENDPGM;
2781   if (!IsWaveEnd)
2782     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2783   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2784 }
2785 
2786 SDValue SITargetLowering::LowerCallResult(
2787     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2788     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2789     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2790     SDValue ThisVal) const {
2791   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2792 
2793   // Assign locations to each value returned by this call.
2794   SmallVector<CCValAssign, 16> RVLocs;
2795   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2796                  *DAG.getContext());
2797   CCInfo.AnalyzeCallResult(Ins, RetCC);
2798 
2799   // Copy all of the result registers out of their specified physreg.
2800   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2801     CCValAssign VA = RVLocs[i];
2802     SDValue Val;
2803 
2804     if (VA.isRegLoc()) {
2805       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2806       Chain = Val.getValue(1);
2807       InFlag = Val.getValue(2);
2808     } else if (VA.isMemLoc()) {
2809       report_fatal_error("TODO: return values in memory");
2810     } else
2811       llvm_unreachable("unknown argument location type");
2812 
2813     switch (VA.getLocInfo()) {
2814     case CCValAssign::Full:
2815       break;
2816     case CCValAssign::BCvt:
2817       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2818       break;
2819     case CCValAssign::ZExt:
2820       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2821                         DAG.getValueType(VA.getValVT()));
2822       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2823       break;
2824     case CCValAssign::SExt:
2825       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2826                         DAG.getValueType(VA.getValVT()));
2827       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2828       break;
2829     case CCValAssign::AExt:
2830       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2831       break;
2832     default:
2833       llvm_unreachable("Unknown loc info!");
2834     }
2835 
2836     InVals.push_back(Val);
2837   }
2838 
2839   return Chain;
2840 }
2841 
2842 // Add code to pass special inputs required depending on used features separate
2843 // from the explicit user arguments present in the IR.
2844 void SITargetLowering::passSpecialInputs(
2845     CallLoweringInfo &CLI,
2846     CCState &CCInfo,
2847     const SIMachineFunctionInfo &Info,
2848     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2849     SmallVectorImpl<SDValue> &MemOpChains,
2850     SDValue Chain) const {
2851   // If we don't have a call site, this was a call inserted by
2852   // legalization. These can never use special inputs.
2853   if (!CLI.CB)
2854     return;
2855 
2856   SelectionDAG &DAG = CLI.DAG;
2857   const SDLoc &DL = CLI.DL;
2858   const Function &F = DAG.getMachineFunction().getFunction();
2859 
2860   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2861   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2862 
2863   const AMDGPUFunctionArgInfo *CalleeArgInfo
2864     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2865   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2866     auto &ArgUsageInfo =
2867       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2868     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2869   }
2870 
2871   // TODO: Unify with private memory register handling. This is complicated by
2872   // the fact that at least in kernels, the input argument is not necessarily
2873   // in the same location as the input.
2874   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2875                              StringLiteral> ImplicitAttrs[] = {
2876     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2877     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2878     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2879     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2880     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2881     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2882     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2883   };
2884 
2885   for (auto Attr : ImplicitAttrs) {
2886     const ArgDescriptor *OutgoingArg;
2887     const TargetRegisterClass *ArgRC;
2888     LLT ArgTy;
2889 
2890     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2891 
2892     // If the callee does not use the attribute value, skip copying the value.
2893     if (CLI.CB->hasFnAttr(Attr.second))
2894       continue;
2895 
2896     std::tie(OutgoingArg, ArgRC, ArgTy) =
2897         CalleeArgInfo->getPreloadedValue(InputID);
2898     if (!OutgoingArg)
2899       continue;
2900 
2901     const ArgDescriptor *IncomingArg;
2902     const TargetRegisterClass *IncomingArgRC;
2903     LLT Ty;
2904     std::tie(IncomingArg, IncomingArgRC, Ty) =
2905         CallerArgInfo.getPreloadedValue(InputID);
2906     assert(IncomingArgRC == ArgRC);
2907 
2908     // All special arguments are ints for now.
2909     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2910     SDValue InputReg;
2911 
2912     if (IncomingArg) {
2913       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2914     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2915       // The implicit arg ptr is special because it doesn't have a corresponding
2916       // input for kernels, and is computed from the kernarg segment pointer.
2917       InputReg = getImplicitArgPtr(DAG, DL);
2918     } else {
2919       // We may have proven the input wasn't needed, although the ABI is
2920       // requiring it. We just need to allocate the register appropriately.
2921       InputReg = DAG.getUNDEF(ArgVT);
2922     }
2923 
2924     if (OutgoingArg->isRegister()) {
2925       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2926       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2927         report_fatal_error("failed to allocate implicit input argument");
2928     } else {
2929       unsigned SpecialArgOffset =
2930           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2931       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2932                                               SpecialArgOffset);
2933       MemOpChains.push_back(ArgStore);
2934     }
2935   }
2936 
2937   // Pack workitem IDs into a single register or pass it as is if already
2938   // packed.
2939   const ArgDescriptor *OutgoingArg;
2940   const TargetRegisterClass *ArgRC;
2941   LLT Ty;
2942 
2943   std::tie(OutgoingArg, ArgRC, Ty) =
2944       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2945   if (!OutgoingArg)
2946     std::tie(OutgoingArg, ArgRC, Ty) =
2947         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2948   if (!OutgoingArg)
2949     std::tie(OutgoingArg, ArgRC, Ty) =
2950         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2951   if (!OutgoingArg)
2952     return;
2953 
2954   const ArgDescriptor *IncomingArgX = std::get<0>(
2955       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2956   const ArgDescriptor *IncomingArgY = std::get<0>(
2957       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2958   const ArgDescriptor *IncomingArgZ = std::get<0>(
2959       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2960 
2961   SDValue InputReg;
2962   SDLoc SL;
2963 
2964   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2965   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2966   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2967 
2968   // If incoming ids are not packed we need to pack them.
2969   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2970       NeedWorkItemIDX) {
2971     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2972       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2973     } else {
2974       InputReg = DAG.getConstant(0, DL, MVT::i32);
2975     }
2976   }
2977 
2978   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2979       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2980     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2981     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2982                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2983     InputReg = InputReg.getNode() ?
2984                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2985   }
2986 
2987   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2988       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2989     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2990     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2991                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2992     InputReg = InputReg.getNode() ?
2993                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2994   }
2995 
2996   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2997     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2998       // We're in a situation where the outgoing function requires the workitem
2999       // ID, but the calling function does not have it (e.g a graphics function
3000       // calling a C calling convention function). This is illegal, but we need
3001       // to produce something.
3002       InputReg = DAG.getUNDEF(MVT::i32);
3003     } else {
3004       // Workitem ids are already packed, any of present incoming arguments
3005       // will carry all required fields.
3006       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
3007         IncomingArgX ? *IncomingArgX :
3008         IncomingArgY ? *IncomingArgY :
3009         *IncomingArgZ, ~0u);
3010       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3011     }
3012   }
3013 
3014   if (OutgoingArg->isRegister()) {
3015     if (InputReg)
3016       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3017 
3018     CCInfo.AllocateReg(OutgoingArg->getRegister());
3019   } else {
3020     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3021     if (InputReg) {
3022       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3023                                               SpecialArgOffset);
3024       MemOpChains.push_back(ArgStore);
3025     }
3026   }
3027 }
3028 
3029 static bool canGuaranteeTCO(CallingConv::ID CC) {
3030   return CC == CallingConv::Fast;
3031 }
3032 
3033 /// Return true if we might ever do TCO for calls with this calling convention.
3034 static bool mayTailCallThisCC(CallingConv::ID CC) {
3035   switch (CC) {
3036   case CallingConv::C:
3037   case CallingConv::AMDGPU_Gfx:
3038     return true;
3039   default:
3040     return canGuaranteeTCO(CC);
3041   }
3042 }
3043 
3044 bool SITargetLowering::isEligibleForTailCallOptimization(
3045     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3046     const SmallVectorImpl<ISD::OutputArg> &Outs,
3047     const SmallVectorImpl<SDValue> &OutVals,
3048     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3049   if (!mayTailCallThisCC(CalleeCC))
3050     return false;
3051 
3052   // For a divergent call target, we need to do a waterfall loop over the
3053   // possible callees which precludes us from using a simple jump.
3054   if (Callee->isDivergent())
3055     return false;
3056 
3057   MachineFunction &MF = DAG.getMachineFunction();
3058   const Function &CallerF = MF.getFunction();
3059   CallingConv::ID CallerCC = CallerF.getCallingConv();
3060   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3061   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3062 
3063   // Kernels aren't callable, and don't have a live in return address so it
3064   // doesn't make sense to do a tail call with entry functions.
3065   if (!CallerPreserved)
3066     return false;
3067 
3068   bool CCMatch = CallerCC == CalleeCC;
3069 
3070   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3071     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3072       return true;
3073     return false;
3074   }
3075 
3076   // TODO: Can we handle var args?
3077   if (IsVarArg)
3078     return false;
3079 
3080   for (const Argument &Arg : CallerF.args()) {
3081     if (Arg.hasByValAttr())
3082       return false;
3083   }
3084 
3085   LLVMContext &Ctx = *DAG.getContext();
3086 
3087   // Check that the call results are passed in the same way.
3088   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3089                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3090                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3091     return false;
3092 
3093   // The callee has to preserve all registers the caller needs to preserve.
3094   if (!CCMatch) {
3095     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3096     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3097       return false;
3098   }
3099 
3100   // Nothing more to check if the callee is taking no arguments.
3101   if (Outs.empty())
3102     return true;
3103 
3104   SmallVector<CCValAssign, 16> ArgLocs;
3105   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3106 
3107   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3108 
3109   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3110   // If the stack arguments for this call do not fit into our own save area then
3111   // the call cannot be made tail.
3112   // TODO: Is this really necessary?
3113   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3114     return false;
3115 
3116   const MachineRegisterInfo &MRI = MF.getRegInfo();
3117   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3118 }
3119 
3120 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3121   if (!CI->isTailCall())
3122     return false;
3123 
3124   const Function *ParentFn = CI->getParent()->getParent();
3125   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3126     return false;
3127   return true;
3128 }
3129 
3130 // The wave scratch offset register is used as the global base pointer.
3131 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3132                                     SmallVectorImpl<SDValue> &InVals) const {
3133   SelectionDAG &DAG = CLI.DAG;
3134   const SDLoc &DL = CLI.DL;
3135   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3136   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3137   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3138   SDValue Chain = CLI.Chain;
3139   SDValue Callee = CLI.Callee;
3140   bool &IsTailCall = CLI.IsTailCall;
3141   CallingConv::ID CallConv = CLI.CallConv;
3142   bool IsVarArg = CLI.IsVarArg;
3143   bool IsSibCall = false;
3144   bool IsThisReturn = false;
3145   MachineFunction &MF = DAG.getMachineFunction();
3146 
3147   if (Callee.isUndef() || isNullConstant(Callee)) {
3148     if (!CLI.IsTailCall) {
3149       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3150         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3151     }
3152 
3153     return Chain;
3154   }
3155 
3156   if (IsVarArg) {
3157     return lowerUnhandledCall(CLI, InVals,
3158                               "unsupported call to variadic function ");
3159   }
3160 
3161   if (!CLI.CB)
3162     report_fatal_error("unsupported libcall legalization");
3163 
3164   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3165     return lowerUnhandledCall(CLI, InVals,
3166                               "unsupported required tail call to function ");
3167   }
3168 
3169   if (AMDGPU::isShader(CallConv)) {
3170     // Note the issue is with the CC of the called function, not of the call
3171     // itself.
3172     return lowerUnhandledCall(CLI, InVals,
3173                               "unsupported call to a shader function ");
3174   }
3175 
3176   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3177       CallConv != CallingConv::AMDGPU_Gfx) {
3178     // Only allow calls with specific calling conventions.
3179     return lowerUnhandledCall(CLI, InVals,
3180                               "unsupported calling convention for call from "
3181                               "graphics shader of function ");
3182   }
3183 
3184   if (IsTailCall) {
3185     IsTailCall = isEligibleForTailCallOptimization(
3186       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3187     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3188       report_fatal_error("failed to perform tail call elimination on a call "
3189                          "site marked musttail");
3190     }
3191 
3192     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3193 
3194     // A sibling call is one where we're under the usual C ABI and not planning
3195     // to change that but can still do a tail call:
3196     if (!TailCallOpt && IsTailCall)
3197       IsSibCall = true;
3198 
3199     if (IsTailCall)
3200       ++NumTailCalls;
3201   }
3202 
3203   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3204   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3205   SmallVector<SDValue, 8> MemOpChains;
3206 
3207   // Analyze operands of the call, assigning locations to each operand.
3208   SmallVector<CCValAssign, 16> ArgLocs;
3209   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3210   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3211 
3212   if (CallConv != CallingConv::AMDGPU_Gfx) {
3213     // With a fixed ABI, allocate fixed registers before user arguments.
3214     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3215   }
3216 
3217   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3218 
3219   // Get a count of how many bytes are to be pushed on the stack.
3220   unsigned NumBytes = CCInfo.getNextStackOffset();
3221 
3222   if (IsSibCall) {
3223     // Since we're not changing the ABI to make this a tail call, the memory
3224     // operands are already available in the caller's incoming argument space.
3225     NumBytes = 0;
3226   }
3227 
3228   // FPDiff is the byte offset of the call's argument area from the callee's.
3229   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3230   // by this amount for a tail call. In a sibling call it must be 0 because the
3231   // caller will deallocate the entire stack and the callee still expects its
3232   // arguments to begin at SP+0. Completely unused for non-tail calls.
3233   int32_t FPDiff = 0;
3234   MachineFrameInfo &MFI = MF.getFrameInfo();
3235 
3236   // Adjust the stack pointer for the new arguments...
3237   // These operations are automatically eliminated by the prolog/epilog pass
3238   if (!IsSibCall) {
3239     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3240 
3241     if (!Subtarget->enableFlatScratch()) {
3242       SmallVector<SDValue, 4> CopyFromChains;
3243 
3244       // In the HSA case, this should be an identity copy.
3245       SDValue ScratchRSrcReg
3246         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3247       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3248       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3249       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3250     }
3251   }
3252 
3253   MVT PtrVT = MVT::i32;
3254 
3255   // Walk the register/memloc assignments, inserting copies/loads.
3256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3257     CCValAssign &VA = ArgLocs[i];
3258     SDValue Arg = OutVals[i];
3259 
3260     // Promote the value if needed.
3261     switch (VA.getLocInfo()) {
3262     case CCValAssign::Full:
3263       break;
3264     case CCValAssign::BCvt:
3265       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3266       break;
3267     case CCValAssign::ZExt:
3268       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3269       break;
3270     case CCValAssign::SExt:
3271       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3272       break;
3273     case CCValAssign::AExt:
3274       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3275       break;
3276     case CCValAssign::FPExt:
3277       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3278       break;
3279     default:
3280       llvm_unreachable("Unknown loc info!");
3281     }
3282 
3283     if (VA.isRegLoc()) {
3284       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3285     } else {
3286       assert(VA.isMemLoc());
3287 
3288       SDValue DstAddr;
3289       MachinePointerInfo DstInfo;
3290 
3291       unsigned LocMemOffset = VA.getLocMemOffset();
3292       int32_t Offset = LocMemOffset;
3293 
3294       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3295       MaybeAlign Alignment;
3296 
3297       if (IsTailCall) {
3298         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3299         unsigned OpSize = Flags.isByVal() ?
3300           Flags.getByValSize() : VA.getValVT().getStoreSize();
3301 
3302         // FIXME: We can have better than the minimum byval required alignment.
3303         Alignment =
3304             Flags.isByVal()
3305                 ? Flags.getNonZeroByValAlign()
3306                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3307 
3308         Offset = Offset + FPDiff;
3309         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3310 
3311         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3312         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3313 
3314         // Make sure any stack arguments overlapping with where we're storing
3315         // are loaded before this eventual operation. Otherwise they'll be
3316         // clobbered.
3317 
3318         // FIXME: Why is this really necessary? This seems to just result in a
3319         // lot of code to copy the stack and write them back to the same
3320         // locations, which are supposed to be immutable?
3321         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3322       } else {
3323         // Stores to the argument stack area are relative to the stack pointer.
3324         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3325                                         MVT::i32);
3326         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3327         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3328         Alignment =
3329             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3330       }
3331 
3332       if (Outs[i].Flags.isByVal()) {
3333         SDValue SizeNode =
3334             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3335         SDValue Cpy =
3336             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3337                           Outs[i].Flags.getNonZeroByValAlign(),
3338                           /*isVol = */ false, /*AlwaysInline = */ true,
3339                           /*isTailCall = */ false, DstInfo,
3340                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3341 
3342         MemOpChains.push_back(Cpy);
3343       } else {
3344         SDValue Store =
3345             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3346         MemOpChains.push_back(Store);
3347       }
3348     }
3349   }
3350 
3351   if (!MemOpChains.empty())
3352     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3353 
3354   // Build a sequence of copy-to-reg nodes chained together with token chain
3355   // and flag operands which copy the outgoing args into the appropriate regs.
3356   SDValue InFlag;
3357   for (auto &RegToPass : RegsToPass) {
3358     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3359                              RegToPass.second, InFlag);
3360     InFlag = Chain.getValue(1);
3361   }
3362 
3363 
3364   // We don't usually want to end the call-sequence here because we would tidy
3365   // the frame up *after* the call, however in the ABI-changing tail-call case
3366   // we've carefully laid out the parameters so that when sp is reset they'll be
3367   // in the correct location.
3368   if (IsTailCall && !IsSibCall) {
3369     Chain = DAG.getCALLSEQ_END(Chain,
3370                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3371                                DAG.getTargetConstant(0, DL, MVT::i32),
3372                                InFlag, DL);
3373     InFlag = Chain.getValue(1);
3374   }
3375 
3376   std::vector<SDValue> Ops;
3377   Ops.push_back(Chain);
3378   Ops.push_back(Callee);
3379   // Add a redundant copy of the callee global which will not be legalized, as
3380   // we need direct access to the callee later.
3381   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3382     const GlobalValue *GV = GSD->getGlobal();
3383     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3384   } else {
3385     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3386   }
3387 
3388   if (IsTailCall) {
3389     // Each tail call may have to adjust the stack by a different amount, so
3390     // this information must travel along with the operation for eventual
3391     // consumption by emitEpilogue.
3392     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3393   }
3394 
3395   // Add argument registers to the end of the list so that they are known live
3396   // into the call.
3397   for (auto &RegToPass : RegsToPass) {
3398     Ops.push_back(DAG.getRegister(RegToPass.first,
3399                                   RegToPass.second.getValueType()));
3400   }
3401 
3402   // Add a register mask operand representing the call-preserved registers.
3403 
3404   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3405   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3406   assert(Mask && "Missing call preserved mask for calling convention");
3407   Ops.push_back(DAG.getRegisterMask(Mask));
3408 
3409   if (InFlag.getNode())
3410     Ops.push_back(InFlag);
3411 
3412   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3413 
3414   // If we're doing a tall call, use a TC_RETURN here rather than an
3415   // actual call instruction.
3416   if (IsTailCall) {
3417     MFI.setHasTailCall();
3418     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3419   }
3420 
3421   // Returns a chain and a flag for retval copy to use.
3422   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3423   Chain = Call.getValue(0);
3424   InFlag = Call.getValue(1);
3425 
3426   uint64_t CalleePopBytes = NumBytes;
3427   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3428                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3429                              InFlag, DL);
3430   if (!Ins.empty())
3431     InFlag = Chain.getValue(1);
3432 
3433   // Handle result values, copying them out of physregs into vregs that we
3434   // return.
3435   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3436                          InVals, IsThisReturn,
3437                          IsThisReturn ? OutVals[0] : SDValue());
3438 }
3439 
3440 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3441 // except for applying the wave size scale to the increment amount.
3442 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3443     SDValue Op, SelectionDAG &DAG) const {
3444   const MachineFunction &MF = DAG.getMachineFunction();
3445   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3446 
3447   SDLoc dl(Op);
3448   EVT VT = Op.getValueType();
3449   SDValue Tmp1 = Op;
3450   SDValue Tmp2 = Op.getValue(1);
3451   SDValue Tmp3 = Op.getOperand(2);
3452   SDValue Chain = Tmp1.getOperand(0);
3453 
3454   Register SPReg = Info->getStackPtrOffsetReg();
3455 
3456   // Chain the dynamic stack allocation so that it doesn't modify the stack
3457   // pointer when other instructions are using the stack.
3458   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3459 
3460   SDValue Size  = Tmp2.getOperand(1);
3461   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3462   Chain = SP.getValue(1);
3463   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3464   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3465   const TargetFrameLowering *TFL = ST.getFrameLowering();
3466   unsigned Opc =
3467     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3468     ISD::ADD : ISD::SUB;
3469 
3470   SDValue ScaledSize = DAG.getNode(
3471       ISD::SHL, dl, VT, Size,
3472       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3473 
3474   Align StackAlign = TFL->getStackAlign();
3475   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3476   if (Alignment && *Alignment > StackAlign) {
3477     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3478                        DAG.getConstant(-(uint64_t)Alignment->value()
3479                                            << ST.getWavefrontSizeLog2(),
3480                                        dl, VT));
3481   }
3482 
3483   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3484   Tmp2 = DAG.getCALLSEQ_END(
3485       Chain, DAG.getIntPtrConstant(0, dl, true),
3486       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3487 
3488   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3489 }
3490 
3491 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3492                                                   SelectionDAG &DAG) const {
3493   // We only handle constant sizes here to allow non-entry block, static sized
3494   // allocas. A truly dynamic value is more difficult to support because we
3495   // don't know if the size value is uniform or not. If the size isn't uniform,
3496   // we would need to do a wave reduction to get the maximum size to know how
3497   // much to increment the uniform stack pointer.
3498   SDValue Size = Op.getOperand(1);
3499   if (isa<ConstantSDNode>(Size))
3500       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3501 
3502   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3503 }
3504 
3505 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3506                                              const MachineFunction &MF) const {
3507   Register Reg = StringSwitch<Register>(RegName)
3508     .Case("m0", AMDGPU::M0)
3509     .Case("exec", AMDGPU::EXEC)
3510     .Case("exec_lo", AMDGPU::EXEC_LO)
3511     .Case("exec_hi", AMDGPU::EXEC_HI)
3512     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3513     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3514     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3515     .Default(Register());
3516 
3517   if (Reg == AMDGPU::NoRegister) {
3518     report_fatal_error(Twine("invalid register name \""
3519                              + StringRef(RegName)  + "\"."));
3520 
3521   }
3522 
3523   if (!Subtarget->hasFlatScrRegister() &&
3524        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3525     report_fatal_error(Twine("invalid register \""
3526                              + StringRef(RegName)  + "\" for subtarget."));
3527   }
3528 
3529   switch (Reg) {
3530   case AMDGPU::M0:
3531   case AMDGPU::EXEC_LO:
3532   case AMDGPU::EXEC_HI:
3533   case AMDGPU::FLAT_SCR_LO:
3534   case AMDGPU::FLAT_SCR_HI:
3535     if (VT.getSizeInBits() == 32)
3536       return Reg;
3537     break;
3538   case AMDGPU::EXEC:
3539   case AMDGPU::FLAT_SCR:
3540     if (VT.getSizeInBits() == 64)
3541       return Reg;
3542     break;
3543   default:
3544     llvm_unreachable("missing register type checking");
3545   }
3546 
3547   report_fatal_error(Twine("invalid type for register \""
3548                            + StringRef(RegName) + "\"."));
3549 }
3550 
3551 // If kill is not the last instruction, split the block so kill is always a
3552 // proper terminator.
3553 MachineBasicBlock *
3554 SITargetLowering::splitKillBlock(MachineInstr &MI,
3555                                  MachineBasicBlock *BB) const {
3556   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3557   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3558   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3559   return SplitBB;
3560 }
3561 
3562 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3563 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3564 // be the first instruction in the remainder block.
3565 //
3566 /// \returns { LoopBody, Remainder }
3567 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3568 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3569   MachineFunction *MF = MBB.getParent();
3570   MachineBasicBlock::iterator I(&MI);
3571 
3572   // To insert the loop we need to split the block. Move everything after this
3573   // point to a new block, and insert a new empty block between the two.
3574   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3575   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3576   MachineFunction::iterator MBBI(MBB);
3577   ++MBBI;
3578 
3579   MF->insert(MBBI, LoopBB);
3580   MF->insert(MBBI, RemainderBB);
3581 
3582   LoopBB->addSuccessor(LoopBB);
3583   LoopBB->addSuccessor(RemainderBB);
3584 
3585   // Move the rest of the block into a new block.
3586   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3587 
3588   if (InstInLoop) {
3589     auto Next = std::next(I);
3590 
3591     // Move instruction to loop body.
3592     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3593 
3594     // Move the rest of the block.
3595     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3596   } else {
3597     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3598   }
3599 
3600   MBB.addSuccessor(LoopBB);
3601 
3602   return std::make_pair(LoopBB, RemainderBB);
3603 }
3604 
3605 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3606 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3607   MachineBasicBlock *MBB = MI.getParent();
3608   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3609   auto I = MI.getIterator();
3610   auto E = std::next(I);
3611 
3612   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3613     .addImm(0);
3614 
3615   MIBundleBuilder Bundler(*MBB, I, E);
3616   finalizeBundle(*MBB, Bundler.begin());
3617 }
3618 
3619 MachineBasicBlock *
3620 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3621                                          MachineBasicBlock *BB) const {
3622   const DebugLoc &DL = MI.getDebugLoc();
3623 
3624   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3625 
3626   MachineBasicBlock *LoopBB;
3627   MachineBasicBlock *RemainderBB;
3628   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3629 
3630   // Apparently kill flags are only valid if the def is in the same block?
3631   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3632     Src->setIsKill(false);
3633 
3634   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3635 
3636   MachineBasicBlock::iterator I = LoopBB->end();
3637 
3638   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3639     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3640 
3641   // Clear TRAP_STS.MEM_VIOL
3642   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3643     .addImm(0)
3644     .addImm(EncodedReg);
3645 
3646   bundleInstWithWaitcnt(MI);
3647 
3648   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3649 
3650   // Load and check TRAP_STS.MEM_VIOL
3651   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3652     .addImm(EncodedReg);
3653 
3654   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3655   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3656     .addReg(Reg, RegState::Kill)
3657     .addImm(0);
3658   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3659     .addMBB(LoopBB);
3660 
3661   return RemainderBB;
3662 }
3663 
3664 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3665 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3666 // will only do one iteration. In the worst case, this will loop 64 times.
3667 //
3668 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3669 static MachineBasicBlock::iterator
3670 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3671                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3672                        const DebugLoc &DL, const MachineOperand &Idx,
3673                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3674                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3675                        Register &SGPRIdxReg) {
3676 
3677   MachineFunction *MF = OrigBB.getParent();
3678   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3679   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3680   MachineBasicBlock::iterator I = LoopBB.begin();
3681 
3682   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3683   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3684   Register NewExec = MRI.createVirtualRegister(BoolRC);
3685   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3686   Register CondReg = MRI.createVirtualRegister(BoolRC);
3687 
3688   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3689     .addReg(InitReg)
3690     .addMBB(&OrigBB)
3691     .addReg(ResultReg)
3692     .addMBB(&LoopBB);
3693 
3694   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3695     .addReg(InitSaveExecReg)
3696     .addMBB(&OrigBB)
3697     .addReg(NewExec)
3698     .addMBB(&LoopBB);
3699 
3700   // Read the next variant <- also loop target.
3701   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3702       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3703 
3704   // Compare the just read M0 value to all possible Idx values.
3705   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3706       .addReg(CurrentIdxReg)
3707       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3708 
3709   // Update EXEC, save the original EXEC value to VCC.
3710   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3711                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3712           NewExec)
3713     .addReg(CondReg, RegState::Kill);
3714 
3715   MRI.setSimpleHint(NewExec, CondReg);
3716 
3717   if (UseGPRIdxMode) {
3718     if (Offset == 0) {
3719       SGPRIdxReg = CurrentIdxReg;
3720     } else {
3721       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3722       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3723           .addReg(CurrentIdxReg, RegState::Kill)
3724           .addImm(Offset);
3725     }
3726   } else {
3727     // Move index from VCC into M0
3728     if (Offset == 0) {
3729       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3730         .addReg(CurrentIdxReg, RegState::Kill);
3731     } else {
3732       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3733         .addReg(CurrentIdxReg, RegState::Kill)
3734         .addImm(Offset);
3735     }
3736   }
3737 
3738   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3739   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3740   MachineInstr *InsertPt =
3741     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3742                                                   : AMDGPU::S_XOR_B64_term), Exec)
3743       .addReg(Exec)
3744       .addReg(NewExec);
3745 
3746   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3747   // s_cbranch_scc0?
3748 
3749   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3750   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3751     .addMBB(&LoopBB);
3752 
3753   return InsertPt->getIterator();
3754 }
3755 
3756 // This has slightly sub-optimal regalloc when the source vector is killed by
3757 // the read. The register allocator does not understand that the kill is
3758 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3759 // subregister from it, using 1 more VGPR than necessary. This was saved when
3760 // this was expanded after register allocation.
3761 static MachineBasicBlock::iterator
3762 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3763                unsigned InitResultReg, unsigned PhiReg, int Offset,
3764                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3765   MachineFunction *MF = MBB.getParent();
3766   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3767   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3768   MachineRegisterInfo &MRI = MF->getRegInfo();
3769   const DebugLoc &DL = MI.getDebugLoc();
3770   MachineBasicBlock::iterator I(&MI);
3771 
3772   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3773   Register DstReg = MI.getOperand(0).getReg();
3774   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3775   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3776   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3777   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3778 
3779   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3780 
3781   // Save the EXEC mask
3782   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3783     .addReg(Exec);
3784 
3785   MachineBasicBlock *LoopBB;
3786   MachineBasicBlock *RemainderBB;
3787   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3788 
3789   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3790 
3791   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3792                                       InitResultReg, DstReg, PhiReg, TmpExec,
3793                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3794 
3795   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3796   MachineFunction::iterator MBBI(LoopBB);
3797   ++MBBI;
3798   MF->insert(MBBI, LandingPad);
3799   LoopBB->removeSuccessor(RemainderBB);
3800   LandingPad->addSuccessor(RemainderBB);
3801   LoopBB->addSuccessor(LandingPad);
3802   MachineBasicBlock::iterator First = LandingPad->begin();
3803   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3804     .addReg(SaveExec);
3805 
3806   return InsPt;
3807 }
3808 
3809 // Returns subreg index, offset
3810 static std::pair<unsigned, int>
3811 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3812                             const TargetRegisterClass *SuperRC,
3813                             unsigned VecReg,
3814                             int Offset) {
3815   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3816 
3817   // Skip out of bounds offsets, or else we would end up using an undefined
3818   // register.
3819   if (Offset >= NumElts || Offset < 0)
3820     return std::make_pair(AMDGPU::sub0, Offset);
3821 
3822   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3823 }
3824 
3825 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3826                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3827                                  int Offset) {
3828   MachineBasicBlock *MBB = MI.getParent();
3829   const DebugLoc &DL = MI.getDebugLoc();
3830   MachineBasicBlock::iterator I(&MI);
3831 
3832   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3833 
3834   assert(Idx->getReg() != AMDGPU::NoRegister);
3835 
3836   if (Offset == 0) {
3837     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3838   } else {
3839     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3840         .add(*Idx)
3841         .addImm(Offset);
3842   }
3843 }
3844 
3845 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3846                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3847                                    int Offset) {
3848   MachineBasicBlock *MBB = MI.getParent();
3849   const DebugLoc &DL = MI.getDebugLoc();
3850   MachineBasicBlock::iterator I(&MI);
3851 
3852   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3853 
3854   if (Offset == 0)
3855     return Idx->getReg();
3856 
3857   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3858   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3859       .add(*Idx)
3860       .addImm(Offset);
3861   return Tmp;
3862 }
3863 
3864 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3865                                           MachineBasicBlock &MBB,
3866                                           const GCNSubtarget &ST) {
3867   const SIInstrInfo *TII = ST.getInstrInfo();
3868   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3869   MachineFunction *MF = MBB.getParent();
3870   MachineRegisterInfo &MRI = MF->getRegInfo();
3871 
3872   Register Dst = MI.getOperand(0).getReg();
3873   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3874   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3875   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3876 
3877   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3878   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3879 
3880   unsigned SubReg;
3881   std::tie(SubReg, Offset)
3882     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3883 
3884   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3885 
3886   // Check for a SGPR index.
3887   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3888     MachineBasicBlock::iterator I(&MI);
3889     const DebugLoc &DL = MI.getDebugLoc();
3890 
3891     if (UseGPRIdxMode) {
3892       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3893       // to avoid interfering with other uses, so probably requires a new
3894       // optimization pass.
3895       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3896 
3897       const MCInstrDesc &GPRIDXDesc =
3898           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3899       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3900           .addReg(SrcReg)
3901           .addReg(Idx)
3902           .addImm(SubReg);
3903     } else {
3904       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3905 
3906       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3907         .addReg(SrcReg, 0, SubReg)
3908         .addReg(SrcReg, RegState::Implicit);
3909     }
3910 
3911     MI.eraseFromParent();
3912 
3913     return &MBB;
3914   }
3915 
3916   // Control flow needs to be inserted if indexing with a VGPR.
3917   const DebugLoc &DL = MI.getDebugLoc();
3918   MachineBasicBlock::iterator I(&MI);
3919 
3920   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3921   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3922 
3923   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3924 
3925   Register SGPRIdxReg;
3926   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3927                               UseGPRIdxMode, SGPRIdxReg);
3928 
3929   MachineBasicBlock *LoopBB = InsPt->getParent();
3930 
3931   if (UseGPRIdxMode) {
3932     const MCInstrDesc &GPRIDXDesc =
3933         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3934 
3935     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3936         .addReg(SrcReg)
3937         .addReg(SGPRIdxReg)
3938         .addImm(SubReg);
3939   } else {
3940     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3941       .addReg(SrcReg, 0, SubReg)
3942       .addReg(SrcReg, RegState::Implicit);
3943   }
3944 
3945   MI.eraseFromParent();
3946 
3947   return LoopBB;
3948 }
3949 
3950 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3951                                           MachineBasicBlock &MBB,
3952                                           const GCNSubtarget &ST) {
3953   const SIInstrInfo *TII = ST.getInstrInfo();
3954   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3955   MachineFunction *MF = MBB.getParent();
3956   MachineRegisterInfo &MRI = MF->getRegInfo();
3957 
3958   Register Dst = MI.getOperand(0).getReg();
3959   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3960   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3961   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3962   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3963   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3964   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3965 
3966   // This can be an immediate, but will be folded later.
3967   assert(Val->getReg());
3968 
3969   unsigned SubReg;
3970   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3971                                                          SrcVec->getReg(),
3972                                                          Offset);
3973   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3974 
3975   if (Idx->getReg() == AMDGPU::NoRegister) {
3976     MachineBasicBlock::iterator I(&MI);
3977     const DebugLoc &DL = MI.getDebugLoc();
3978 
3979     assert(Offset == 0);
3980 
3981     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3982         .add(*SrcVec)
3983         .add(*Val)
3984         .addImm(SubReg);
3985 
3986     MI.eraseFromParent();
3987     return &MBB;
3988   }
3989 
3990   // Check for a SGPR index.
3991   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3992     MachineBasicBlock::iterator I(&MI);
3993     const DebugLoc &DL = MI.getDebugLoc();
3994 
3995     if (UseGPRIdxMode) {
3996       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3997 
3998       const MCInstrDesc &GPRIDXDesc =
3999           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4000       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4001           .addReg(SrcVec->getReg())
4002           .add(*Val)
4003           .addReg(Idx)
4004           .addImm(SubReg);
4005     } else {
4006       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4007 
4008       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4009           TRI.getRegSizeInBits(*VecRC), 32, false);
4010       BuildMI(MBB, I, DL, MovRelDesc, Dst)
4011           .addReg(SrcVec->getReg())
4012           .add(*Val)
4013           .addImm(SubReg);
4014     }
4015     MI.eraseFromParent();
4016     return &MBB;
4017   }
4018 
4019   // Control flow needs to be inserted if indexing with a VGPR.
4020   if (Val->isReg())
4021     MRI.clearKillFlags(Val->getReg());
4022 
4023   const DebugLoc &DL = MI.getDebugLoc();
4024 
4025   Register PhiReg = MRI.createVirtualRegister(VecRC);
4026 
4027   Register SGPRIdxReg;
4028   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4029                               UseGPRIdxMode, SGPRIdxReg);
4030   MachineBasicBlock *LoopBB = InsPt->getParent();
4031 
4032   if (UseGPRIdxMode) {
4033     const MCInstrDesc &GPRIDXDesc =
4034         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4035 
4036     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4037         .addReg(PhiReg)
4038         .add(*Val)
4039         .addReg(SGPRIdxReg)
4040         .addImm(AMDGPU::sub0);
4041   } else {
4042     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4043         TRI.getRegSizeInBits(*VecRC), 32, false);
4044     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4045         .addReg(PhiReg)
4046         .add(*Val)
4047         .addImm(AMDGPU::sub0);
4048   }
4049 
4050   MI.eraseFromParent();
4051   return LoopBB;
4052 }
4053 
4054 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4055   MachineInstr &MI, MachineBasicBlock *BB) const {
4056 
4057   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4058   MachineFunction *MF = BB->getParent();
4059   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4060 
4061   switch (MI.getOpcode()) {
4062   case AMDGPU::S_UADDO_PSEUDO:
4063   case AMDGPU::S_USUBO_PSEUDO: {
4064     const DebugLoc &DL = MI.getDebugLoc();
4065     MachineOperand &Dest0 = MI.getOperand(0);
4066     MachineOperand &Dest1 = MI.getOperand(1);
4067     MachineOperand &Src0 = MI.getOperand(2);
4068     MachineOperand &Src1 = MI.getOperand(3);
4069 
4070     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4071                        ? AMDGPU::S_ADD_I32
4072                        : AMDGPU::S_SUB_I32;
4073     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4074 
4075     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4076         .addImm(1)
4077         .addImm(0);
4078 
4079     MI.eraseFromParent();
4080     return BB;
4081   }
4082   case AMDGPU::S_ADD_U64_PSEUDO:
4083   case AMDGPU::S_SUB_U64_PSEUDO: {
4084     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4085     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4086     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4087     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4088     const DebugLoc &DL = MI.getDebugLoc();
4089 
4090     MachineOperand &Dest = MI.getOperand(0);
4091     MachineOperand &Src0 = MI.getOperand(1);
4092     MachineOperand &Src1 = MI.getOperand(2);
4093 
4094     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4095     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4096 
4097     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4098         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4099     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4100         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4101 
4102     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4103         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4104     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4105         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4106 
4107     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4108 
4109     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4110     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4111     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4112     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4113     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4114         .addReg(DestSub0)
4115         .addImm(AMDGPU::sub0)
4116         .addReg(DestSub1)
4117         .addImm(AMDGPU::sub1);
4118     MI.eraseFromParent();
4119     return BB;
4120   }
4121   case AMDGPU::V_ADD_U64_PSEUDO:
4122   case AMDGPU::V_SUB_U64_PSEUDO: {
4123     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4124     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4125     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4126     const DebugLoc &DL = MI.getDebugLoc();
4127 
4128     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4129 
4130     MachineOperand &Dest = MI.getOperand(0);
4131     MachineOperand &Src0 = MI.getOperand(1);
4132     MachineOperand &Src1 = MI.getOperand(2);
4133 
4134     if (IsAdd && ST.hasLshlAddB64()) {
4135       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4136                          Dest.getReg())
4137                      .add(Src0)
4138                      .addImm(0)
4139                      .add(Src1);
4140       TII->legalizeOperands(*Add);
4141       MI.eraseFromParent();
4142       return BB;
4143     }
4144 
4145     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4146 
4147     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4148     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4149 
4150     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4151     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4152 
4153     const TargetRegisterClass *Src0RC = Src0.isReg()
4154                                             ? MRI.getRegClass(Src0.getReg())
4155                                             : &AMDGPU::VReg_64RegClass;
4156     const TargetRegisterClass *Src1RC = Src1.isReg()
4157                                             ? MRI.getRegClass(Src1.getReg())
4158                                             : &AMDGPU::VReg_64RegClass;
4159 
4160     const TargetRegisterClass *Src0SubRC =
4161         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4162     const TargetRegisterClass *Src1SubRC =
4163         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4164 
4165     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4166         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4167     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4168         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4169 
4170     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4171         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4172     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4173         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4174 
4175     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4176     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4177                                .addReg(CarryReg, RegState::Define)
4178                                .add(SrcReg0Sub0)
4179                                .add(SrcReg1Sub0)
4180                                .addImm(0); // clamp bit
4181 
4182     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4183     MachineInstr *HiHalf =
4184         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4185             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4186             .add(SrcReg0Sub1)
4187             .add(SrcReg1Sub1)
4188             .addReg(CarryReg, RegState::Kill)
4189             .addImm(0); // clamp bit
4190 
4191     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4192         .addReg(DestSub0)
4193         .addImm(AMDGPU::sub0)
4194         .addReg(DestSub1)
4195         .addImm(AMDGPU::sub1);
4196     TII->legalizeOperands(*LoHalf);
4197     TII->legalizeOperands(*HiHalf);
4198     MI.eraseFromParent();
4199     return BB;
4200   }
4201   case AMDGPU::S_ADD_CO_PSEUDO:
4202   case AMDGPU::S_SUB_CO_PSEUDO: {
4203     // This pseudo has a chance to be selected
4204     // only from uniform add/subcarry node. All the VGPR operands
4205     // therefore assumed to be splat vectors.
4206     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4207     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4208     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4209     MachineBasicBlock::iterator MII = MI;
4210     const DebugLoc &DL = MI.getDebugLoc();
4211     MachineOperand &Dest = MI.getOperand(0);
4212     MachineOperand &CarryDest = MI.getOperand(1);
4213     MachineOperand &Src0 = MI.getOperand(2);
4214     MachineOperand &Src1 = MI.getOperand(3);
4215     MachineOperand &Src2 = MI.getOperand(4);
4216     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4217                        ? AMDGPU::S_ADDC_U32
4218                        : AMDGPU::S_SUBB_U32;
4219     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4220       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4221       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4222           .addReg(Src0.getReg());
4223       Src0.setReg(RegOp0);
4224     }
4225     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4226       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4227       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4228           .addReg(Src1.getReg());
4229       Src1.setReg(RegOp1);
4230     }
4231     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4232     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4233       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4234           .addReg(Src2.getReg());
4235       Src2.setReg(RegOp2);
4236     }
4237 
4238     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4239     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4240     assert(WaveSize == 64 || WaveSize == 32);
4241 
4242     if (WaveSize == 64) {
4243       if (ST.hasScalarCompareEq64()) {
4244         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4245             .addReg(Src2.getReg())
4246             .addImm(0);
4247       } else {
4248         const TargetRegisterClass *SubRC =
4249             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4250         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4251             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4252         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4253             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4254         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4255 
4256         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4257             .add(Src2Sub0)
4258             .add(Src2Sub1);
4259 
4260         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4261             .addReg(Src2_32, RegState::Kill)
4262             .addImm(0);
4263       }
4264     } else {
4265       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4266           .addReg(Src2.getReg())
4267           .addImm(0);
4268     }
4269 
4270     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4271 
4272     unsigned SelOpc =
4273         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4274 
4275     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4276         .addImm(-1)
4277         .addImm(0);
4278 
4279     MI.eraseFromParent();
4280     return BB;
4281   }
4282   case AMDGPU::SI_INIT_M0: {
4283     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4284             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4285         .add(MI.getOperand(0));
4286     MI.eraseFromParent();
4287     return BB;
4288   }
4289   case AMDGPU::GET_GROUPSTATICSIZE: {
4290     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4291            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4292     DebugLoc DL = MI.getDebugLoc();
4293     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4294         .add(MI.getOperand(0))
4295         .addImm(MFI->getLDSSize());
4296     MI.eraseFromParent();
4297     return BB;
4298   }
4299   case AMDGPU::SI_INDIRECT_SRC_V1:
4300   case AMDGPU::SI_INDIRECT_SRC_V2:
4301   case AMDGPU::SI_INDIRECT_SRC_V4:
4302   case AMDGPU::SI_INDIRECT_SRC_V8:
4303   case AMDGPU::SI_INDIRECT_SRC_V16:
4304   case AMDGPU::SI_INDIRECT_SRC_V32:
4305     return emitIndirectSrc(MI, *BB, *getSubtarget());
4306   case AMDGPU::SI_INDIRECT_DST_V1:
4307   case AMDGPU::SI_INDIRECT_DST_V2:
4308   case AMDGPU::SI_INDIRECT_DST_V4:
4309   case AMDGPU::SI_INDIRECT_DST_V8:
4310   case AMDGPU::SI_INDIRECT_DST_V16:
4311   case AMDGPU::SI_INDIRECT_DST_V32:
4312     return emitIndirectDst(MI, *BB, *getSubtarget());
4313   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4314   case AMDGPU::SI_KILL_I1_PSEUDO:
4315     return splitKillBlock(MI, BB);
4316   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4317     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4318     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4319     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4320 
4321     Register Dst = MI.getOperand(0).getReg();
4322     Register Src0 = MI.getOperand(1).getReg();
4323     Register Src1 = MI.getOperand(2).getReg();
4324     const DebugLoc &DL = MI.getDebugLoc();
4325     Register SrcCond = MI.getOperand(3).getReg();
4326 
4327     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4328     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4329     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4330     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4331 
4332     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4333       .addReg(SrcCond);
4334     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4335       .addImm(0)
4336       .addReg(Src0, 0, AMDGPU::sub0)
4337       .addImm(0)
4338       .addReg(Src1, 0, AMDGPU::sub0)
4339       .addReg(SrcCondCopy);
4340     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4341       .addImm(0)
4342       .addReg(Src0, 0, AMDGPU::sub1)
4343       .addImm(0)
4344       .addReg(Src1, 0, AMDGPU::sub1)
4345       .addReg(SrcCondCopy);
4346 
4347     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4348       .addReg(DstLo)
4349       .addImm(AMDGPU::sub0)
4350       .addReg(DstHi)
4351       .addImm(AMDGPU::sub1);
4352     MI.eraseFromParent();
4353     return BB;
4354   }
4355   case AMDGPU::SI_BR_UNDEF: {
4356     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4357     const DebugLoc &DL = MI.getDebugLoc();
4358     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4359                            .add(MI.getOperand(0));
4360     Br->getOperand(1).setIsUndef(true); // read undef SCC
4361     MI.eraseFromParent();
4362     return BB;
4363   }
4364   case AMDGPU::ADJCALLSTACKUP:
4365   case AMDGPU::ADJCALLSTACKDOWN: {
4366     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4367     MachineInstrBuilder MIB(*MF, &MI);
4368     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4369        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4370     return BB;
4371   }
4372   case AMDGPU::SI_CALL_ISEL: {
4373     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4374     const DebugLoc &DL = MI.getDebugLoc();
4375 
4376     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4377 
4378     MachineInstrBuilder MIB;
4379     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4380 
4381     for (const MachineOperand &MO : MI.operands())
4382       MIB.add(MO);
4383 
4384     MIB.cloneMemRefs(MI);
4385     MI.eraseFromParent();
4386     return BB;
4387   }
4388   case AMDGPU::V_ADD_CO_U32_e32:
4389   case AMDGPU::V_SUB_CO_U32_e32:
4390   case AMDGPU::V_SUBREV_CO_U32_e32: {
4391     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4392     const DebugLoc &DL = MI.getDebugLoc();
4393     unsigned Opc = MI.getOpcode();
4394 
4395     bool NeedClampOperand = false;
4396     if (TII->pseudoToMCOpcode(Opc) == -1) {
4397       Opc = AMDGPU::getVOPe64(Opc);
4398       NeedClampOperand = true;
4399     }
4400 
4401     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4402     if (TII->isVOP3(*I)) {
4403       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4404       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4405       I.addReg(TRI->getVCC(), RegState::Define);
4406     }
4407     I.add(MI.getOperand(1))
4408      .add(MI.getOperand(2));
4409     if (NeedClampOperand)
4410       I.addImm(0); // clamp bit for e64 encoding
4411 
4412     TII->legalizeOperands(*I);
4413 
4414     MI.eraseFromParent();
4415     return BB;
4416   }
4417   case AMDGPU::V_ADDC_U32_e32:
4418   case AMDGPU::V_SUBB_U32_e32:
4419   case AMDGPU::V_SUBBREV_U32_e32:
4420     // These instructions have an implicit use of vcc which counts towards the
4421     // constant bus limit.
4422     TII->legalizeOperands(MI);
4423     return BB;
4424   case AMDGPU::DS_GWS_INIT:
4425   case AMDGPU::DS_GWS_SEMA_BR:
4426   case AMDGPU::DS_GWS_BARRIER:
4427     if (Subtarget->needsAlignedVGPRs()) {
4428       // Add implicit aligned super-reg to force alignment on the data operand.
4429       const DebugLoc &DL = MI.getDebugLoc();
4430       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4431       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4432       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4433       Register DataReg = Op->getReg();
4434       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4435       Register Undef = MRI.createVirtualRegister(
4436           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4437       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4438       Register NewVR =
4439           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4440                                            : &AMDGPU::VReg_64_Align2RegClass);
4441       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4442           .addReg(DataReg, 0, Op->getSubReg())
4443           .addImm(AMDGPU::sub0)
4444           .addReg(Undef)
4445           .addImm(AMDGPU::sub1);
4446       Op->setReg(NewVR);
4447       Op->setSubReg(AMDGPU::sub0);
4448       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4449     }
4450     LLVM_FALLTHROUGH;
4451   case AMDGPU::DS_GWS_SEMA_V:
4452   case AMDGPU::DS_GWS_SEMA_P:
4453   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4454     // A s_waitcnt 0 is required to be the instruction immediately following.
4455     if (getSubtarget()->hasGWSAutoReplay()) {
4456       bundleInstWithWaitcnt(MI);
4457       return BB;
4458     }
4459 
4460     return emitGWSMemViolTestLoop(MI, BB);
4461   case AMDGPU::S_SETREG_B32: {
4462     // Try to optimize cases that only set the denormal mode or rounding mode.
4463     //
4464     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4465     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4466     // instead.
4467     //
4468     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4469     // allow you to have a no side effect instruction in the output of a
4470     // sideeffecting pattern.
4471     unsigned ID, Offset, Width;
4472     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4473     if (ID != AMDGPU::Hwreg::ID_MODE)
4474       return BB;
4475 
4476     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4477     const unsigned SetMask = WidthMask << Offset;
4478 
4479     if (getSubtarget()->hasDenormModeInst()) {
4480       unsigned SetDenormOp = 0;
4481       unsigned SetRoundOp = 0;
4482 
4483       // The dedicated instructions can only set the whole denorm or round mode
4484       // at once, not a subset of bits in either.
4485       if (SetMask ==
4486           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4487         // If this fully sets both the round and denorm mode, emit the two
4488         // dedicated instructions for these.
4489         SetRoundOp = AMDGPU::S_ROUND_MODE;
4490         SetDenormOp = AMDGPU::S_DENORM_MODE;
4491       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4492         SetRoundOp = AMDGPU::S_ROUND_MODE;
4493       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4494         SetDenormOp = AMDGPU::S_DENORM_MODE;
4495       }
4496 
4497       if (SetRoundOp || SetDenormOp) {
4498         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4499         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4500         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4501           unsigned ImmVal = Def->getOperand(1).getImm();
4502           if (SetRoundOp) {
4503             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4504                 .addImm(ImmVal & 0xf);
4505 
4506             // If we also have the denorm mode, get just the denorm mode bits.
4507             ImmVal >>= 4;
4508           }
4509 
4510           if (SetDenormOp) {
4511             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4512                 .addImm(ImmVal & 0xf);
4513           }
4514 
4515           MI.eraseFromParent();
4516           return BB;
4517         }
4518       }
4519     }
4520 
4521     // If only FP bits are touched, used the no side effects pseudo.
4522     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4523                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4524       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4525 
4526     return BB;
4527   }
4528   default:
4529     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4530   }
4531 }
4532 
4533 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4534   return isTypeLegal(VT.getScalarType());
4535 }
4536 
4537 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4538   // This currently forces unfolding various combinations of fsub into fma with
4539   // free fneg'd operands. As long as we have fast FMA (controlled by
4540   // isFMAFasterThanFMulAndFAdd), we should perform these.
4541 
4542   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4543   // most of these combines appear to be cycle neutral but save on instruction
4544   // count / code size.
4545   return true;
4546 }
4547 
4548 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4549 
4550 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4551                                          EVT VT) const {
4552   if (!VT.isVector()) {
4553     return MVT::i1;
4554   }
4555   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4556 }
4557 
4558 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4559   // TODO: Should i16 be used always if legal? For now it would force VALU
4560   // shifts.
4561   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4562 }
4563 
4564 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4565   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4566              ? Ty.changeElementSize(16)
4567              : Ty.changeElementSize(32);
4568 }
4569 
4570 // Answering this is somewhat tricky and depends on the specific device which
4571 // have different rates for fma or all f64 operations.
4572 //
4573 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4574 // regardless of which device (although the number of cycles differs between
4575 // devices), so it is always profitable for f64.
4576 //
4577 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4578 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4579 // which we can always do even without fused FP ops since it returns the same
4580 // result as the separate operations and since it is always full
4581 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4582 // however does not support denormals, so we do report fma as faster if we have
4583 // a fast fma device and require denormals.
4584 //
4585 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4586                                                   EVT VT) const {
4587   VT = VT.getScalarType();
4588 
4589   switch (VT.getSimpleVT().SimpleTy) {
4590   case MVT::f32: {
4591     // If mad is not available this depends only on if f32 fma is full rate.
4592     if (!Subtarget->hasMadMacF32Insts())
4593       return Subtarget->hasFastFMAF32();
4594 
4595     // Otherwise f32 mad is always full rate and returns the same result as
4596     // the separate operations so should be preferred over fma.
4597     // However does not support denormals.
4598     if (hasFP32Denormals(MF))
4599       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4600 
4601     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4602     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4603   }
4604   case MVT::f64:
4605     return true;
4606   case MVT::f16:
4607     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4608   default:
4609     break;
4610   }
4611 
4612   return false;
4613 }
4614 
4615 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4616                                                   LLT Ty) const {
4617   switch (Ty.getScalarSizeInBits()) {
4618   case 16:
4619     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4620   case 32:
4621     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4622   case 64:
4623     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4624   default:
4625     break;
4626   }
4627 
4628   return false;
4629 }
4630 
4631 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4632   if (!Ty.isScalar())
4633     return false;
4634 
4635   if (Ty.getScalarSizeInBits() == 16)
4636     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4637   if (Ty.getScalarSizeInBits() == 32)
4638     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4639 
4640   return false;
4641 }
4642 
4643 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4644                                    const SDNode *N) const {
4645   // TODO: Check future ftz flag
4646   // v_mad_f32/v_mac_f32 do not support denormals.
4647   EVT VT = N->getValueType(0);
4648   if (VT == MVT::f32)
4649     return Subtarget->hasMadMacF32Insts() &&
4650            !hasFP32Denormals(DAG.getMachineFunction());
4651   if (VT == MVT::f16) {
4652     return Subtarget->hasMadF16() &&
4653            !hasFP64FP16Denormals(DAG.getMachineFunction());
4654   }
4655 
4656   return false;
4657 }
4658 
4659 //===----------------------------------------------------------------------===//
4660 // Custom DAG Lowering Operations
4661 //===----------------------------------------------------------------------===//
4662 
4663 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4664 // wider vector type is legal.
4665 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4666                                              SelectionDAG &DAG) const {
4667   unsigned Opc = Op.getOpcode();
4668   EVT VT = Op.getValueType();
4669   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4670 
4671   SDValue Lo, Hi;
4672   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4673 
4674   SDLoc SL(Op);
4675   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4676                              Op->getFlags());
4677   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4678                              Op->getFlags());
4679 
4680   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4681 }
4682 
4683 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4684 // wider vector type is legal.
4685 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4686                                               SelectionDAG &DAG) const {
4687   unsigned Opc = Op.getOpcode();
4688   EVT VT = Op.getValueType();
4689   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4690          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4691          VT == MVT::v16f32 || VT == MVT::v32f32);
4692 
4693   SDValue Lo0, Hi0;
4694   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4695   SDValue Lo1, Hi1;
4696   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4697 
4698   SDLoc SL(Op);
4699 
4700   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4701                              Op->getFlags());
4702   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4703                              Op->getFlags());
4704 
4705   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4706 }
4707 
4708 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4709                                               SelectionDAG &DAG) const {
4710   unsigned Opc = Op.getOpcode();
4711   EVT VT = Op.getValueType();
4712   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4713          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4714          VT == MVT::v16f32 || VT == MVT::v32f32);
4715 
4716   SDValue Lo0, Hi0;
4717   SDValue Op0 = Op.getOperand(0);
4718   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4719                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4720                          : std::make_pair(Op0, Op0);
4721   SDValue Lo1, Hi1;
4722   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4723   SDValue Lo2, Hi2;
4724   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4725 
4726   SDLoc SL(Op);
4727   auto ResVT = DAG.GetSplitDestVTs(VT);
4728 
4729   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4730                              Op->getFlags());
4731   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4732                              Op->getFlags());
4733 
4734   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4735 }
4736 
4737 
4738 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4739   switch (Op.getOpcode()) {
4740   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4741   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4742   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4743   case ISD::LOAD: {
4744     SDValue Result = LowerLOAD(Op, DAG);
4745     assert((!Result.getNode() ||
4746             Result.getNode()->getNumValues() == 2) &&
4747            "Load should return a value and a chain");
4748     return Result;
4749   }
4750 
4751   case ISD::FSIN:
4752   case ISD::FCOS:
4753     return LowerTrig(Op, DAG);
4754   case ISD::SELECT: return LowerSELECT(Op, DAG);
4755   case ISD::FDIV: return LowerFDIV(Op, DAG);
4756   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4757   case ISD::STORE: return LowerSTORE(Op, DAG);
4758   case ISD::GlobalAddress: {
4759     MachineFunction &MF = DAG.getMachineFunction();
4760     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4761     return LowerGlobalAddress(MFI, Op, DAG);
4762   }
4763   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4764   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4765   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4766   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4767   case ISD::INSERT_SUBVECTOR:
4768     return lowerINSERT_SUBVECTOR(Op, DAG);
4769   case ISD::INSERT_VECTOR_ELT:
4770     return lowerINSERT_VECTOR_ELT(Op, DAG);
4771   case ISD::EXTRACT_VECTOR_ELT:
4772     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4773   case ISD::VECTOR_SHUFFLE:
4774     return lowerVECTOR_SHUFFLE(Op, DAG);
4775   case ISD::SCALAR_TO_VECTOR:
4776     return lowerSCALAR_TO_VECTOR(Op, DAG);
4777   case ISD::BUILD_VECTOR:
4778     return lowerBUILD_VECTOR(Op, DAG);
4779   case ISD::FP_ROUND:
4780     return lowerFP_ROUND(Op, DAG);
4781   case ISD::FPTRUNC_ROUND: {
4782     unsigned Opc;
4783     SDLoc DL(Op);
4784 
4785     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4786       return SDValue();
4787 
4788     // Get the rounding mode from the last operand
4789     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4790     if (RoundMode == (int)RoundingMode::TowardPositive)
4791       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4792     else if (RoundMode == (int)RoundingMode::TowardNegative)
4793       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4794     else
4795       return SDValue();
4796 
4797     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4798   }
4799   case ISD::TRAP:
4800     return lowerTRAP(Op, DAG);
4801   case ISD::DEBUGTRAP:
4802     return lowerDEBUGTRAP(Op, DAG);
4803   case ISD::FABS:
4804   case ISD::FNEG:
4805   case ISD::FCANONICALIZE:
4806   case ISD::BSWAP:
4807     return splitUnaryVectorOp(Op, DAG);
4808   case ISD::FMINNUM:
4809   case ISD::FMAXNUM:
4810     return lowerFMINNUM_FMAXNUM(Op, DAG);
4811   case ISD::FMA:
4812     return splitTernaryVectorOp(Op, DAG);
4813   case ISD::FP_TO_SINT:
4814   case ISD::FP_TO_UINT:
4815     return LowerFP_TO_INT(Op, DAG);
4816   case ISD::SHL:
4817   case ISD::SRA:
4818   case ISD::SRL:
4819   case ISD::ADD:
4820   case ISD::SUB:
4821   case ISD::MUL:
4822   case ISD::SMIN:
4823   case ISD::SMAX:
4824   case ISD::UMIN:
4825   case ISD::UMAX:
4826   case ISD::FADD:
4827   case ISD::FMUL:
4828   case ISD::FMINNUM_IEEE:
4829   case ISD::FMAXNUM_IEEE:
4830   case ISD::UADDSAT:
4831   case ISD::USUBSAT:
4832   case ISD::SADDSAT:
4833   case ISD::SSUBSAT:
4834     return splitBinaryVectorOp(Op, DAG);
4835   case ISD::SMULO:
4836   case ISD::UMULO:
4837     return lowerXMULO(Op, DAG);
4838   case ISD::SMUL_LOHI:
4839   case ISD::UMUL_LOHI:
4840     return lowerXMUL_LOHI(Op, DAG);
4841   case ISD::DYNAMIC_STACKALLOC:
4842     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4843   }
4844   return SDValue();
4845 }
4846 
4847 // Used for D16: Casts the result of an instruction into the right vector,
4848 // packs values if loads return unpacked values.
4849 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4850                                        const SDLoc &DL,
4851                                        SelectionDAG &DAG, bool Unpacked) {
4852   if (!LoadVT.isVector())
4853     return Result;
4854 
4855   // Cast back to the original packed type or to a larger type that is a
4856   // multiple of 32 bit for D16. Widening the return type is a required for
4857   // legalization.
4858   EVT FittingLoadVT = LoadVT;
4859   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4860     FittingLoadVT =
4861         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4862                          LoadVT.getVectorNumElements() + 1);
4863   }
4864 
4865   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4866     // Truncate to v2i16/v4i16.
4867     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4868 
4869     // Workaround legalizer not scalarizing truncate after vector op
4870     // legalization but not creating intermediate vector trunc.
4871     SmallVector<SDValue, 4> Elts;
4872     DAG.ExtractVectorElements(Result, Elts);
4873     for (SDValue &Elt : Elts)
4874       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4875 
4876     // Pad illegal v1i16/v3fi6 to v4i16
4877     if ((LoadVT.getVectorNumElements() % 2) == 1)
4878       Elts.push_back(DAG.getUNDEF(MVT::i16));
4879 
4880     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4881 
4882     // Bitcast to original type (v2f16/v4f16).
4883     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4884   }
4885 
4886   // Cast back to the original packed type.
4887   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4888 }
4889 
4890 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4891                                               MemSDNode *M,
4892                                               SelectionDAG &DAG,
4893                                               ArrayRef<SDValue> Ops,
4894                                               bool IsIntrinsic) const {
4895   SDLoc DL(M);
4896 
4897   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4898   EVT LoadVT = M->getValueType(0);
4899 
4900   EVT EquivLoadVT = LoadVT;
4901   if (LoadVT.isVector()) {
4902     if (Unpacked) {
4903       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4904                                      LoadVT.getVectorNumElements());
4905     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4906       // Widen v3f16 to legal type
4907       EquivLoadVT =
4908           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4909                            LoadVT.getVectorNumElements() + 1);
4910     }
4911   }
4912 
4913   // Change from v4f16/v2f16 to EquivLoadVT.
4914   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4915 
4916   SDValue Load
4917     = DAG.getMemIntrinsicNode(
4918       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4919       VTList, Ops, M->getMemoryVT(),
4920       M->getMemOperand());
4921 
4922   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4923 
4924   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4925 }
4926 
4927 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4928                                              SelectionDAG &DAG,
4929                                              ArrayRef<SDValue> Ops) const {
4930   SDLoc DL(M);
4931   EVT LoadVT = M->getValueType(0);
4932   EVT EltType = LoadVT.getScalarType();
4933   EVT IntVT = LoadVT.changeTypeToInteger();
4934 
4935   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4936 
4937   unsigned Opc =
4938       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4939 
4940   if (IsD16) {
4941     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4942   }
4943 
4944   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4945   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4946     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4947 
4948   if (isTypeLegal(LoadVT)) {
4949     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4950                                M->getMemOperand(), DAG);
4951   }
4952 
4953   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4954   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4955   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4956                                         M->getMemOperand(), DAG);
4957   return DAG.getMergeValues(
4958       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4959       DL);
4960 }
4961 
4962 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4963                                   SDNode *N, SelectionDAG &DAG) {
4964   EVT VT = N->getValueType(0);
4965   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4966   unsigned CondCode = CD->getZExtValue();
4967   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4968     return DAG.getUNDEF(VT);
4969 
4970   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4971 
4972   SDValue LHS = N->getOperand(1);
4973   SDValue RHS = N->getOperand(2);
4974 
4975   SDLoc DL(N);
4976 
4977   EVT CmpVT = LHS.getValueType();
4978   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4979     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4980       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4981     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4982     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4983   }
4984 
4985   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4986 
4987   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4988   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4989 
4990   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4991                               DAG.getCondCode(CCOpcode));
4992   if (VT.bitsEq(CCVT))
4993     return SetCC;
4994   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4995 }
4996 
4997 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4998                                   SDNode *N, SelectionDAG &DAG) {
4999   EVT VT = N->getValueType(0);
5000   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
5001 
5002   unsigned CondCode = CD->getZExtValue();
5003   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
5004     return DAG.getUNDEF(VT);
5005 
5006   SDValue Src0 = N->getOperand(1);
5007   SDValue Src1 = N->getOperand(2);
5008   EVT CmpVT = Src0.getValueType();
5009   SDLoc SL(N);
5010 
5011   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5012     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5013     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5014   }
5015 
5016   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5017   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5018   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5019   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5020   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5021                               Src1, DAG.getCondCode(CCOpcode));
5022   if (VT.bitsEq(CCVT))
5023     return SetCC;
5024   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5025 }
5026 
5027 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5028                                     SelectionDAG &DAG) {
5029   EVT VT = N->getValueType(0);
5030   SDValue Src = N->getOperand(1);
5031   SDLoc SL(N);
5032 
5033   if (Src.getOpcode() == ISD::SETCC) {
5034     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5035     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5036                        Src.getOperand(1), Src.getOperand(2));
5037   }
5038   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5039     // (ballot 0) -> 0
5040     if (Arg->isZero())
5041       return DAG.getConstant(0, SL, VT);
5042 
5043     // (ballot 1) -> EXEC/EXEC_LO
5044     if (Arg->isOne()) {
5045       Register Exec;
5046       if (VT.getScalarSizeInBits() == 32)
5047         Exec = AMDGPU::EXEC_LO;
5048       else if (VT.getScalarSizeInBits() == 64)
5049         Exec = AMDGPU::EXEC;
5050       else
5051         return SDValue();
5052 
5053       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5054     }
5055   }
5056 
5057   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5058   // ISD::SETNE)
5059   return DAG.getNode(
5060       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5061       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5062 }
5063 
5064 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5065                                           SmallVectorImpl<SDValue> &Results,
5066                                           SelectionDAG &DAG) const {
5067   switch (N->getOpcode()) {
5068   case ISD::INSERT_VECTOR_ELT: {
5069     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5070       Results.push_back(Res);
5071     return;
5072   }
5073   case ISD::EXTRACT_VECTOR_ELT: {
5074     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5075       Results.push_back(Res);
5076     return;
5077   }
5078   case ISD::INTRINSIC_WO_CHAIN: {
5079     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5080     switch (IID) {
5081     case Intrinsic::amdgcn_cvt_pkrtz: {
5082       SDValue Src0 = N->getOperand(1);
5083       SDValue Src1 = N->getOperand(2);
5084       SDLoc SL(N);
5085       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5086                                 Src0, Src1);
5087       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5088       return;
5089     }
5090     case Intrinsic::amdgcn_cvt_pknorm_i16:
5091     case Intrinsic::amdgcn_cvt_pknorm_u16:
5092     case Intrinsic::amdgcn_cvt_pk_i16:
5093     case Intrinsic::amdgcn_cvt_pk_u16: {
5094       SDValue Src0 = N->getOperand(1);
5095       SDValue Src1 = N->getOperand(2);
5096       SDLoc SL(N);
5097       unsigned Opcode;
5098 
5099       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5100         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5101       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5102         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5103       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5104         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5105       else
5106         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5107 
5108       EVT VT = N->getValueType(0);
5109       if (isTypeLegal(VT))
5110         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5111       else {
5112         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5113         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5114       }
5115       return;
5116     }
5117     }
5118     break;
5119   }
5120   case ISD::INTRINSIC_W_CHAIN: {
5121     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5122       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5123         // FIXME: Hacky
5124         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5125           Results.push_back(Res.getOperand(I));
5126         }
5127       } else {
5128         Results.push_back(Res);
5129         Results.push_back(Res.getValue(1));
5130       }
5131       return;
5132     }
5133 
5134     break;
5135   }
5136   case ISD::SELECT: {
5137     SDLoc SL(N);
5138     EVT VT = N->getValueType(0);
5139     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5140     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5141     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5142 
5143     EVT SelectVT = NewVT;
5144     if (NewVT.bitsLT(MVT::i32)) {
5145       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5146       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5147       SelectVT = MVT::i32;
5148     }
5149 
5150     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5151                                     N->getOperand(0), LHS, RHS);
5152 
5153     if (NewVT != SelectVT)
5154       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5155     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5156     return;
5157   }
5158   case ISD::FNEG: {
5159     if (N->getValueType(0) != MVT::v2f16)
5160       break;
5161 
5162     SDLoc SL(N);
5163     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5164 
5165     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5166                              BC,
5167                              DAG.getConstant(0x80008000, SL, MVT::i32));
5168     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5169     return;
5170   }
5171   case ISD::FABS: {
5172     if (N->getValueType(0) != MVT::v2f16)
5173       break;
5174 
5175     SDLoc SL(N);
5176     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5177 
5178     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5179                              BC,
5180                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5181     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5182     return;
5183   }
5184   default:
5185     break;
5186   }
5187 }
5188 
5189 /// Helper function for LowerBRCOND
5190 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5191 
5192   SDNode *Parent = Value.getNode();
5193   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5194        I != E; ++I) {
5195 
5196     if (I.getUse().get() != Value)
5197       continue;
5198 
5199     if (I->getOpcode() == Opcode)
5200       return *I;
5201   }
5202   return nullptr;
5203 }
5204 
5205 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5206   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5207     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5208     case Intrinsic::amdgcn_if:
5209       return AMDGPUISD::IF;
5210     case Intrinsic::amdgcn_else:
5211       return AMDGPUISD::ELSE;
5212     case Intrinsic::amdgcn_loop:
5213       return AMDGPUISD::LOOP;
5214     case Intrinsic::amdgcn_end_cf:
5215       llvm_unreachable("should not occur");
5216     default:
5217       return 0;
5218     }
5219   }
5220 
5221   // break, if_break, else_break are all only used as inputs to loop, not
5222   // directly as branch conditions.
5223   return 0;
5224 }
5225 
5226 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5227   const Triple &TT = getTargetMachine().getTargetTriple();
5228   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5229           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5230          AMDGPU::shouldEmitConstantsToTextSection(TT);
5231 }
5232 
5233 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5234   // FIXME: Either avoid relying on address space here or change the default
5235   // address space for functions to avoid the explicit check.
5236   return (GV->getValueType()->isFunctionTy() ||
5237           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5238          !shouldEmitFixup(GV) &&
5239          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5240 }
5241 
5242 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5243   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5244 }
5245 
5246 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5247   if (!GV->hasExternalLinkage())
5248     return true;
5249 
5250   const auto OS = getTargetMachine().getTargetTriple().getOS();
5251   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5252 }
5253 
5254 /// This transforms the control flow intrinsics to get the branch destination as
5255 /// last parameter, also switches branch target with BR if the need arise
5256 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5257                                       SelectionDAG &DAG) const {
5258   SDLoc DL(BRCOND);
5259 
5260   SDNode *Intr = BRCOND.getOperand(1).getNode();
5261   SDValue Target = BRCOND.getOperand(2);
5262   SDNode *BR = nullptr;
5263   SDNode *SetCC = nullptr;
5264 
5265   if (Intr->getOpcode() == ISD::SETCC) {
5266     // As long as we negate the condition everything is fine
5267     SetCC = Intr;
5268     Intr = SetCC->getOperand(0).getNode();
5269 
5270   } else {
5271     // Get the target from BR if we don't negate the condition
5272     BR = findUser(BRCOND, ISD::BR);
5273     assert(BR && "brcond missing unconditional branch user");
5274     Target = BR->getOperand(1);
5275   }
5276 
5277   unsigned CFNode = isCFIntrinsic(Intr);
5278   if (CFNode == 0) {
5279     // This is a uniform branch so we don't need to legalize.
5280     return BRCOND;
5281   }
5282 
5283   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5284                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5285 
5286   assert(!SetCC ||
5287         (SetCC->getConstantOperandVal(1) == 1 &&
5288          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5289                                                              ISD::SETNE));
5290 
5291   // operands of the new intrinsic call
5292   SmallVector<SDValue, 4> Ops;
5293   if (HaveChain)
5294     Ops.push_back(BRCOND.getOperand(0));
5295 
5296   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5297   Ops.push_back(Target);
5298 
5299   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5300 
5301   // build the new intrinsic call
5302   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5303 
5304   if (!HaveChain) {
5305     SDValue Ops[] =  {
5306       SDValue(Result, 0),
5307       BRCOND.getOperand(0)
5308     };
5309 
5310     Result = DAG.getMergeValues(Ops, DL).getNode();
5311   }
5312 
5313   if (BR) {
5314     // Give the branch instruction our target
5315     SDValue Ops[] = {
5316       BR->getOperand(0),
5317       BRCOND.getOperand(2)
5318     };
5319     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5320     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5321   }
5322 
5323   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5324 
5325   // Copy the intrinsic results to registers
5326   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5327     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5328     if (!CopyToReg)
5329       continue;
5330 
5331     Chain = DAG.getCopyToReg(
5332       Chain, DL,
5333       CopyToReg->getOperand(1),
5334       SDValue(Result, i - 1),
5335       SDValue());
5336 
5337     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5338   }
5339 
5340   // Remove the old intrinsic from the chain
5341   DAG.ReplaceAllUsesOfValueWith(
5342     SDValue(Intr, Intr->getNumValues() - 1),
5343     Intr->getOperand(0));
5344 
5345   return Chain;
5346 }
5347 
5348 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5349                                           SelectionDAG &DAG) const {
5350   MVT VT = Op.getSimpleValueType();
5351   SDLoc DL(Op);
5352   // Checking the depth
5353   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5354     return DAG.getConstant(0, DL, VT);
5355 
5356   MachineFunction &MF = DAG.getMachineFunction();
5357   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5358   // Check for kernel and shader functions
5359   if (Info->isEntryFunction())
5360     return DAG.getConstant(0, DL, VT);
5361 
5362   MachineFrameInfo &MFI = MF.getFrameInfo();
5363   // There is a call to @llvm.returnaddress in this function
5364   MFI.setReturnAddressIsTaken(true);
5365 
5366   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5367   // Get the return address reg and mark it as an implicit live-in
5368   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5369 
5370   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5371 }
5372 
5373 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5374                                             SDValue Op,
5375                                             const SDLoc &DL,
5376                                             EVT VT) const {
5377   return Op.getValueType().bitsLE(VT) ?
5378       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5379     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5380                 DAG.getTargetConstant(0, DL, MVT::i32));
5381 }
5382 
5383 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5384   assert(Op.getValueType() == MVT::f16 &&
5385          "Do not know how to custom lower FP_ROUND for non-f16 type");
5386 
5387   SDValue Src = Op.getOperand(0);
5388   EVT SrcVT = Src.getValueType();
5389   if (SrcVT != MVT::f64)
5390     return Op;
5391 
5392   SDLoc DL(Op);
5393 
5394   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5395   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5396   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5397 }
5398 
5399 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5400                                                SelectionDAG &DAG) const {
5401   EVT VT = Op.getValueType();
5402   const MachineFunction &MF = DAG.getMachineFunction();
5403   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5404   bool IsIEEEMode = Info->getMode().IEEE;
5405 
5406   // FIXME: Assert during selection that this is only selected for
5407   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5408   // mode functions, but this happens to be OK since it's only done in cases
5409   // where there is known no sNaN.
5410   if (IsIEEEMode)
5411     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5412 
5413   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5414     return splitBinaryVectorOp(Op, DAG);
5415   return Op;
5416 }
5417 
5418 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5419   EVT VT = Op.getValueType();
5420   SDLoc SL(Op);
5421   SDValue LHS = Op.getOperand(0);
5422   SDValue RHS = Op.getOperand(1);
5423   bool isSigned = Op.getOpcode() == ISD::SMULO;
5424 
5425   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5426     const APInt &C = RHSC->getAPIntValue();
5427     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5428     if (C.isPowerOf2()) {
5429       // smulo(x, signed_min) is same as umulo(x, signed_min).
5430       bool UseArithShift = isSigned && !C.isMinSignedValue();
5431       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5432       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5433       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5434           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5435                       SL, VT, Result, ShiftAmt),
5436           LHS, ISD::SETNE);
5437       return DAG.getMergeValues({ Result, Overflow }, SL);
5438     }
5439   }
5440 
5441   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5442   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5443                             SL, VT, LHS, RHS);
5444 
5445   SDValue Sign = isSigned
5446     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5447                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5448     : DAG.getConstant(0, SL, VT);
5449   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5450 
5451   return DAG.getMergeValues({ Result, Overflow }, SL);
5452 }
5453 
5454 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5455   if (Op->isDivergent()) {
5456     // Select to V_MAD_[IU]64_[IU]32.
5457     return Op;
5458   }
5459   if (Subtarget->hasSMulHi()) {
5460     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5461     return SDValue();
5462   }
5463   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5464   // calculate the high part, so we might as well do the whole thing with
5465   // V_MAD_[IU]64_[IU]32.
5466   return Op;
5467 }
5468 
5469 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5470   if (!Subtarget->isTrapHandlerEnabled() ||
5471       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5472     return lowerTrapEndpgm(Op, DAG);
5473 
5474   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5475     switch (*HsaAbiVer) {
5476     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5477     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5478       return lowerTrapHsaQueuePtr(Op, DAG);
5479     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5480     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5481       return Subtarget->supportsGetDoorbellID() ?
5482           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5483     }
5484   }
5485 
5486   llvm_unreachable("Unknown trap handler");
5487 }
5488 
5489 SDValue SITargetLowering::lowerTrapEndpgm(
5490     SDValue Op, SelectionDAG &DAG) const {
5491   SDLoc SL(Op);
5492   SDValue Chain = Op.getOperand(0);
5493   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5494 }
5495 
5496 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5497     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5498   MachineFunction &MF = DAG.getMachineFunction();
5499   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5500   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5501   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5502   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5503                      MachineMemOperand::MODereferenceable |
5504                          MachineMemOperand::MOInvariant);
5505 }
5506 
5507 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5508     SDValue Op, SelectionDAG &DAG) const {
5509   SDLoc SL(Op);
5510   SDValue Chain = Op.getOperand(0);
5511 
5512   SDValue QueuePtr;
5513   // For code object version 5, QueuePtr is passed through implicit kernarg.
5514   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5515     QueuePtr =
5516         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5517   } else {
5518     MachineFunction &MF = DAG.getMachineFunction();
5519     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5520     Register UserSGPR = Info->getQueuePtrUserSGPR();
5521 
5522     if (UserSGPR == AMDGPU::NoRegister) {
5523       // We probably are in a function incorrectly marked with
5524       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5525       // trap, so just use a null pointer.
5526       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5527     } else {
5528       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5529                                       MVT::i64);
5530     }
5531   }
5532 
5533   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5534   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5535                                    QueuePtr, SDValue());
5536 
5537   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5538   SDValue Ops[] = {
5539     ToReg,
5540     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5541     SGPR01,
5542     ToReg.getValue(1)
5543   };
5544   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5545 }
5546 
5547 SDValue SITargetLowering::lowerTrapHsa(
5548     SDValue Op, SelectionDAG &DAG) const {
5549   SDLoc SL(Op);
5550   SDValue Chain = Op.getOperand(0);
5551 
5552   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5553   SDValue Ops[] = {
5554     Chain,
5555     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5556   };
5557   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5558 }
5559 
5560 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5561   SDLoc SL(Op);
5562   SDValue Chain = Op.getOperand(0);
5563   MachineFunction &MF = DAG.getMachineFunction();
5564 
5565   if (!Subtarget->isTrapHandlerEnabled() ||
5566       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5567     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5568                                      "debugtrap handler not supported",
5569                                      Op.getDebugLoc(),
5570                                      DS_Warning);
5571     LLVMContext &Ctx = MF.getFunction().getContext();
5572     Ctx.diagnose(NoTrap);
5573     return Chain;
5574   }
5575 
5576   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5577   SDValue Ops[] = {
5578     Chain,
5579     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5580   };
5581   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5582 }
5583 
5584 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5585                                              SelectionDAG &DAG) const {
5586   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5587   if (Subtarget->hasApertureRegs()) {
5588     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5589         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5590         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5591     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5592         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5593         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5594     unsigned Encoding =
5595         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5596         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5597         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5598 
5599     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5600     SDValue ApertureReg = SDValue(
5601         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5602     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5603     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5604   }
5605 
5606   // For code object version 5, private_base and shared_base are passed through
5607   // implicit kernargs.
5608   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5609     ImplicitParameter Param =
5610         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5611     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5612   }
5613 
5614   MachineFunction &MF = DAG.getMachineFunction();
5615   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5616   Register UserSGPR = Info->getQueuePtrUserSGPR();
5617   if (UserSGPR == AMDGPU::NoRegister) {
5618     // We probably are in a function incorrectly marked with
5619     // amdgpu-no-queue-ptr. This is undefined.
5620     return DAG.getUNDEF(MVT::i32);
5621   }
5622 
5623   SDValue QueuePtr = CreateLiveInRegister(
5624     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5625 
5626   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5627   // private_segment_aperture_base_hi.
5628   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5629 
5630   SDValue Ptr =
5631       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5632 
5633   // TODO: Use custom target PseudoSourceValue.
5634   // TODO: We should use the value from the IR intrinsic call, but it might not
5635   // be available and how do we get it?
5636   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5637   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5638                      commonAlignment(Align(64), StructOffset),
5639                      MachineMemOperand::MODereferenceable |
5640                          MachineMemOperand::MOInvariant);
5641 }
5642 
5643 /// Return true if the value is a known valid address, such that a null check is
5644 /// not necessary.
5645 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5646                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5647   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5648       isa<BasicBlockSDNode>(Val))
5649     return true;
5650 
5651   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5652     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5653 
5654   // TODO: Search through arithmetic, handle arguments and loads
5655   // marked nonnull.
5656   return false;
5657 }
5658 
5659 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5660                                              SelectionDAG &DAG) const {
5661   SDLoc SL(Op);
5662   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5663 
5664   SDValue Src = ASC->getOperand(0);
5665   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5666   unsigned SrcAS = ASC->getSrcAddressSpace();
5667 
5668   const AMDGPUTargetMachine &TM =
5669     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5670 
5671   // flat -> local/private
5672   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5673     unsigned DestAS = ASC->getDestAddressSpace();
5674 
5675     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5676         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5677       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5678 
5679       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5680         return Ptr;
5681 
5682       unsigned NullVal = TM.getNullPointerValue(DestAS);
5683       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5684       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5685 
5686       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5687                          SegmentNullPtr);
5688     }
5689   }
5690 
5691   // local/private -> flat
5692   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5693     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5694         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5695 
5696       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5697       SDValue CvtPtr =
5698           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5699       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5700 
5701       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5702         return CvtPtr;
5703 
5704       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5705       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5706 
5707       SDValue NonNull
5708         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5709 
5710       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5711                          FlatNullPtr);
5712     }
5713   }
5714 
5715   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5716       Op.getValueType() == MVT::i64) {
5717     const SIMachineFunctionInfo *Info =
5718         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5719     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5720     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5721     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5722   }
5723 
5724   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5725       Src.getValueType() == MVT::i64)
5726     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5727 
5728   // global <-> flat are no-ops and never emitted.
5729 
5730   const MachineFunction &MF = DAG.getMachineFunction();
5731   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5732     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5733   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5734 
5735   return DAG.getUNDEF(ASC->getValueType(0));
5736 }
5737 
5738 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5739 // the small vector and inserting them into the big vector. That is better than
5740 // the default expansion of doing it via a stack slot. Even though the use of
5741 // the stack slot would be optimized away afterwards, the stack slot itself
5742 // remains.
5743 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5744                                                 SelectionDAG &DAG) const {
5745   SDValue Vec = Op.getOperand(0);
5746   SDValue Ins = Op.getOperand(1);
5747   SDValue Idx = Op.getOperand(2);
5748   EVT VecVT = Vec.getValueType();
5749   EVT InsVT = Ins.getValueType();
5750   EVT EltVT = VecVT.getVectorElementType();
5751   unsigned InsNumElts = InsVT.getVectorNumElements();
5752   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5753   SDLoc SL(Op);
5754 
5755   for (unsigned I = 0; I != InsNumElts; ++I) {
5756     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5757                               DAG.getConstant(I, SL, MVT::i32));
5758     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5759                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5760   }
5761   return Vec;
5762 }
5763 
5764 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5765                                                  SelectionDAG &DAG) const {
5766   SDValue Vec = Op.getOperand(0);
5767   SDValue InsVal = Op.getOperand(1);
5768   SDValue Idx = Op.getOperand(2);
5769   EVT VecVT = Vec.getValueType();
5770   EVT EltVT = VecVT.getVectorElementType();
5771   unsigned VecSize = VecVT.getSizeInBits();
5772   unsigned EltSize = EltVT.getSizeInBits();
5773   SDLoc SL(Op);
5774 
5775   // Specially handle the case of v4i16 with static indexing.
5776   unsigned NumElts = VecVT.getVectorNumElements();
5777   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5778   if (NumElts == 4 && EltSize == 16 && KIdx) {
5779     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5780 
5781     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5782                                  DAG.getConstant(0, SL, MVT::i32));
5783     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5784                                  DAG.getConstant(1, SL, MVT::i32));
5785 
5786     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5787     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5788 
5789     unsigned Idx = KIdx->getZExtValue();
5790     bool InsertLo = Idx < 2;
5791     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5792       InsertLo ? LoVec : HiVec,
5793       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5794       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5795 
5796     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5797 
5798     SDValue Concat = InsertLo ?
5799       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5800       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5801 
5802     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5803   }
5804 
5805   // Static indexing does not lower to stack access, and hence there is no need
5806   // for special custom lowering to avoid stack access.
5807   if (isa<ConstantSDNode>(Idx))
5808     return SDValue();
5809 
5810   // Avoid stack access for dynamic indexing by custom lowering to
5811   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5812 
5813   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5814 
5815   MVT IntVT = MVT::getIntegerVT(VecSize);
5816 
5817   // Convert vector index to bit-index and get the required bit mask.
5818   assert(isPowerOf2_32(EltSize));
5819   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5820   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5821   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5822                             DAG.getConstant(0xffff, SL, IntVT),
5823                             ScaledIdx);
5824 
5825   // 1. Create a congruent vector with the target value in each element.
5826   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5827                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5828 
5829   // 2. Mask off all other indicies except the required index within (1).
5830   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5831 
5832   // 3. Mask off the required index within the target vector.
5833   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5834   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5835                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5836 
5837   // 4. Get (2) and (3) ORed into the target vector.
5838   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5839 
5840   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5841 }
5842 
5843 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5844                                                   SelectionDAG &DAG) const {
5845   SDLoc SL(Op);
5846 
5847   EVT ResultVT = Op.getValueType();
5848   SDValue Vec = Op.getOperand(0);
5849   SDValue Idx = Op.getOperand(1);
5850   EVT VecVT = Vec.getValueType();
5851   unsigned VecSize = VecVT.getSizeInBits();
5852   EVT EltVT = VecVT.getVectorElementType();
5853 
5854   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5855 
5856   // Make sure we do any optimizations that will make it easier to fold
5857   // source modifiers before obscuring it with bit operations.
5858 
5859   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5860   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5861     return Combined;
5862 
5863   if (VecSize == 128) {
5864     SDValue Lo, Hi;
5865     EVT LoVT, HiVT;
5866     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5867     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5868     Lo =
5869         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5870                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5871     Hi =
5872         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5873                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5874     EVT IdxVT = Idx.getValueType();
5875     unsigned NElem = VecVT.getVectorNumElements();
5876     assert(isPowerOf2_32(NElem));
5877     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5878     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5879     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5880     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5881   }
5882 
5883   assert(VecSize <= 64);
5884 
5885   unsigned EltSize = EltVT.getSizeInBits();
5886   assert(isPowerOf2_32(EltSize));
5887 
5888   MVT IntVT = MVT::getIntegerVT(VecSize);
5889   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5890 
5891   // Convert vector index to bit-index (* EltSize)
5892   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5893 
5894   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5895   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5896 
5897   if (ResultVT == MVT::f16) {
5898     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5899     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5900   }
5901 
5902   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5903 }
5904 
5905 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5906   assert(Elt % 2 == 0);
5907   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5908 }
5909 
5910 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5911                                               SelectionDAG &DAG) const {
5912   SDLoc SL(Op);
5913   EVT ResultVT = Op.getValueType();
5914   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5915 
5916   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5917   EVT EltVT = PackVT.getVectorElementType();
5918   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5919 
5920   // vector_shuffle <0,1,6,7> lhs, rhs
5921   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5922   //
5923   // vector_shuffle <6,7,2,3> lhs, rhs
5924   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5925   //
5926   // vector_shuffle <6,7,0,1> lhs, rhs
5927   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5928 
5929   // Avoid scalarizing when both halves are reading from consecutive elements.
5930   SmallVector<SDValue, 4> Pieces;
5931   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5932     if (elementPairIsContiguous(SVN->getMask(), I)) {
5933       const int Idx = SVN->getMaskElt(I);
5934       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5935       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5936       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5937                                     PackVT, SVN->getOperand(VecIdx),
5938                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5939       Pieces.push_back(SubVec);
5940     } else {
5941       const int Idx0 = SVN->getMaskElt(I);
5942       const int Idx1 = SVN->getMaskElt(I + 1);
5943       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5944       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5945       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5946       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5947 
5948       SDValue Vec0 = SVN->getOperand(VecIdx0);
5949       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5950                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5951 
5952       SDValue Vec1 = SVN->getOperand(VecIdx1);
5953       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5954                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5955       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5956     }
5957   }
5958 
5959   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5960 }
5961 
5962 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5963                                                 SelectionDAG &DAG) const {
5964   SDValue SVal = Op.getOperand(0);
5965   EVT ResultVT = Op.getValueType();
5966   EVT SValVT = SVal.getValueType();
5967   SDValue UndefVal = DAG.getUNDEF(SValVT);
5968   SDLoc SL(Op);
5969 
5970   SmallVector<SDValue, 8> VElts;
5971   VElts.push_back(SVal);
5972   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5973     VElts.push_back(UndefVal);
5974 
5975   return DAG.getBuildVector(ResultVT, SL, VElts);
5976 }
5977 
5978 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5979                                             SelectionDAG &DAG) const {
5980   SDLoc SL(Op);
5981   EVT VT = Op.getValueType();
5982 
5983   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5984       VT == MVT::v8i16 || VT == MVT::v8f16) {
5985     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5986                                   VT.getVectorNumElements() / 2);
5987     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5988 
5989     // Turn into pair of packed build_vectors.
5990     // TODO: Special case for constants that can be materialized with s_mov_b64.
5991     SmallVector<SDValue, 4> LoOps, HiOps;
5992     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5993       LoOps.push_back(Op.getOperand(I));
5994       HiOps.push_back(Op.getOperand(I + E));
5995     }
5996     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5997     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5998 
5999     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
6000     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
6001 
6002     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
6003                                        { CastLo, CastHi });
6004     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
6005   }
6006 
6007   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
6008   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
6009 
6010   SDValue Lo = Op.getOperand(0);
6011   SDValue Hi = Op.getOperand(1);
6012 
6013   // Avoid adding defined bits with the zero_extend.
6014   if (Hi.isUndef()) {
6015     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6016     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
6017     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
6018   }
6019 
6020   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
6021   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
6022 
6023   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
6024                               DAG.getConstant(16, SL, MVT::i32));
6025   if (Lo.isUndef())
6026     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
6027 
6028   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6029   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
6030 
6031   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
6032   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
6033 }
6034 
6035 bool
6036 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6037   // We can fold offsets for anything that doesn't require a GOT relocation.
6038   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
6039           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6040           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6041          !shouldEmitGOTReloc(GA->getGlobal());
6042 }
6043 
6044 static SDValue
6045 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6046                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6047                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6048   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6049   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6050   // lowered to the following code sequence:
6051   //
6052   // For constant address space:
6053   //   s_getpc_b64 s[0:1]
6054   //   s_add_u32 s0, s0, $symbol
6055   //   s_addc_u32 s1, s1, 0
6056   //
6057   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6058   //   a fixup or relocation is emitted to replace $symbol with a literal
6059   //   constant, which is a pc-relative offset from the encoding of the $symbol
6060   //   operand to the global variable.
6061   //
6062   // For global address space:
6063   //   s_getpc_b64 s[0:1]
6064   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6065   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6066   //
6067   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6068   //   fixups or relocations are emitted to replace $symbol@*@lo and
6069   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6070   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6071   //   operand to the global variable.
6072   //
6073   // What we want here is an offset from the value returned by s_getpc
6074   // (which is the address of the s_add_u32 instruction) to the global
6075   // variable, but since the encoding of $symbol starts 4 bytes after the start
6076   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6077   // small. This requires us to add 4 to the global variable offset in order to
6078   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6079   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6080   // instruction.
6081   SDValue PtrLo =
6082       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6083   SDValue PtrHi;
6084   if (GAFlags == SIInstrInfo::MO_NONE) {
6085     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6086   } else {
6087     PtrHi =
6088         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6089   }
6090   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6091 }
6092 
6093 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6094                                              SDValue Op,
6095                                              SelectionDAG &DAG) const {
6096   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6097   SDLoc DL(GSD);
6098   EVT PtrVT = Op.getValueType();
6099 
6100   const GlobalValue *GV = GSD->getGlobal();
6101   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6102        shouldUseLDSConstAddress(GV)) ||
6103       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6104       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6105     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6106         GV->hasExternalLinkage()) {
6107       Type *Ty = GV->getValueType();
6108       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6109       // zero-sized type in other languages to declare the dynamic shared
6110       // memory which size is not known at the compile time. They will be
6111       // allocated by the runtime and placed directly after the static
6112       // allocated ones. They all share the same offset.
6113       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6114         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6115         // Adjust alignment for that dynamic shared memory array.
6116         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6117         return SDValue(
6118             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6119       }
6120     }
6121     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6122   }
6123 
6124   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6125     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6126                                             SIInstrInfo::MO_ABS32_LO);
6127     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6128   }
6129 
6130   if (shouldEmitFixup(GV))
6131     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6132   else if (shouldEmitPCReloc(GV))
6133     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6134                                    SIInstrInfo::MO_REL32);
6135 
6136   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6137                                             SIInstrInfo::MO_GOTPCREL32);
6138 
6139   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6140   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6141   const DataLayout &DataLayout = DAG.getDataLayout();
6142   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6143   MachinePointerInfo PtrInfo
6144     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6145 
6146   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6147                      MachineMemOperand::MODereferenceable |
6148                          MachineMemOperand::MOInvariant);
6149 }
6150 
6151 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6152                                    const SDLoc &DL, SDValue V) const {
6153   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6154   // the destination register.
6155   //
6156   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6157   // so we will end up with redundant moves to m0.
6158   //
6159   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6160 
6161   // A Null SDValue creates a glue result.
6162   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6163                                   V, Chain);
6164   return SDValue(M0, 0);
6165 }
6166 
6167 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6168                                                  SDValue Op,
6169                                                  MVT VT,
6170                                                  unsigned Offset) const {
6171   SDLoc SL(Op);
6172   SDValue Param = lowerKernargMemParameter(
6173       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6174   // The local size values will have the hi 16-bits as zero.
6175   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6176                      DAG.getValueType(VT));
6177 }
6178 
6179 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6180                                         EVT VT) {
6181   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6182                                       "non-hsa intrinsic with hsa target",
6183                                       DL.getDebugLoc());
6184   DAG.getContext()->diagnose(BadIntrin);
6185   return DAG.getUNDEF(VT);
6186 }
6187 
6188 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6189                                          EVT VT) {
6190   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6191                                       "intrinsic not supported on subtarget",
6192                                       DL.getDebugLoc());
6193   DAG.getContext()->diagnose(BadIntrin);
6194   return DAG.getUNDEF(VT);
6195 }
6196 
6197 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6198                                     ArrayRef<SDValue> Elts) {
6199   assert(!Elts.empty());
6200   MVT Type;
6201   unsigned NumElts = Elts.size();
6202 
6203   if (NumElts <= 8) {
6204     Type = MVT::getVectorVT(MVT::f32, NumElts);
6205   } else {
6206     assert(Elts.size() <= 16);
6207     Type = MVT::v16f32;
6208     NumElts = 16;
6209   }
6210 
6211   SmallVector<SDValue, 16> VecElts(NumElts);
6212   for (unsigned i = 0; i < Elts.size(); ++i) {
6213     SDValue Elt = Elts[i];
6214     if (Elt.getValueType() != MVT::f32)
6215       Elt = DAG.getBitcast(MVT::f32, Elt);
6216     VecElts[i] = Elt;
6217   }
6218   for (unsigned i = Elts.size(); i < NumElts; ++i)
6219     VecElts[i] = DAG.getUNDEF(MVT::f32);
6220 
6221   if (NumElts == 1)
6222     return VecElts[0];
6223   return DAG.getBuildVector(Type, DL, VecElts);
6224 }
6225 
6226 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6227                               SDValue Src, int ExtraElts) {
6228   EVT SrcVT = Src.getValueType();
6229 
6230   SmallVector<SDValue, 8> Elts;
6231 
6232   if (SrcVT.isVector())
6233     DAG.ExtractVectorElements(Src, Elts);
6234   else
6235     Elts.push_back(Src);
6236 
6237   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6238   while (ExtraElts--)
6239     Elts.push_back(Undef);
6240 
6241   return DAG.getBuildVector(CastVT, DL, Elts);
6242 }
6243 
6244 // Re-construct the required return value for a image load intrinsic.
6245 // This is more complicated due to the optional use TexFailCtrl which means the required
6246 // return type is an aggregate
6247 static SDValue constructRetValue(SelectionDAG &DAG,
6248                                  MachineSDNode *Result,
6249                                  ArrayRef<EVT> ResultTypes,
6250                                  bool IsTexFail, bool Unpacked, bool IsD16,
6251                                  int DMaskPop, int NumVDataDwords,
6252                                  const SDLoc &DL) {
6253   // Determine the required return type. This is the same regardless of IsTexFail flag
6254   EVT ReqRetVT = ResultTypes[0];
6255   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6256   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6257     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6258 
6259   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6260     DMaskPop : (DMaskPop + 1) / 2;
6261 
6262   MVT DataDwordVT = NumDataDwords == 1 ?
6263     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6264 
6265   MVT MaskPopVT = MaskPopDwords == 1 ?
6266     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6267 
6268   SDValue Data(Result, 0);
6269   SDValue TexFail;
6270 
6271   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6272     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6273     if (MaskPopVT.isVector()) {
6274       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6275                          SDValue(Result, 0), ZeroIdx);
6276     } else {
6277       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6278                          SDValue(Result, 0), ZeroIdx);
6279     }
6280   }
6281 
6282   if (DataDwordVT.isVector())
6283     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6284                           NumDataDwords - MaskPopDwords);
6285 
6286   if (IsD16)
6287     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6288 
6289   EVT LegalReqRetVT = ReqRetVT;
6290   if (!ReqRetVT.isVector()) {
6291     if (!Data.getValueType().isInteger())
6292       Data = DAG.getNode(ISD::BITCAST, DL,
6293                          Data.getValueType().changeTypeToInteger(), Data);
6294     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6295   } else {
6296     // We need to widen the return vector to a legal type
6297     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6298         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6299       LegalReqRetVT =
6300           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6301                            ReqRetVT.getVectorNumElements() + 1);
6302     }
6303   }
6304   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6305 
6306   if (IsTexFail) {
6307     TexFail =
6308         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6309                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6310 
6311     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6312   }
6313 
6314   if (Result->getNumValues() == 1)
6315     return Data;
6316 
6317   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6318 }
6319 
6320 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6321                          SDValue *LWE, bool &IsTexFail) {
6322   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6323 
6324   uint64_t Value = TexFailCtrlConst->getZExtValue();
6325   if (Value) {
6326     IsTexFail = true;
6327   }
6328 
6329   SDLoc DL(TexFailCtrlConst);
6330   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6331   Value &= ~(uint64_t)0x1;
6332   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6333   Value &= ~(uint64_t)0x2;
6334 
6335   return Value == 0;
6336 }
6337 
6338 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6339                                       MVT PackVectorVT,
6340                                       SmallVectorImpl<SDValue> &PackedAddrs,
6341                                       unsigned DimIdx, unsigned EndIdx,
6342                                       unsigned NumGradients) {
6343   SDLoc DL(Op);
6344   for (unsigned I = DimIdx; I < EndIdx; I++) {
6345     SDValue Addr = Op.getOperand(I);
6346 
6347     // Gradients are packed with undef for each coordinate.
6348     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6349     // 1D: undef,dx/dh; undef,dx/dv
6350     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6351     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6352     if (((I + 1) >= EndIdx) ||
6353         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6354                                          I == DimIdx + NumGradients - 1))) {
6355       if (Addr.getValueType() != MVT::i16)
6356         Addr = DAG.getBitcast(MVT::i16, Addr);
6357       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6358     } else {
6359       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6360       I++;
6361     }
6362     Addr = DAG.getBitcast(MVT::f32, Addr);
6363     PackedAddrs.push_back(Addr);
6364   }
6365 }
6366 
6367 SDValue SITargetLowering::lowerImage(SDValue Op,
6368                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6369                                      SelectionDAG &DAG, bool WithChain) const {
6370   SDLoc DL(Op);
6371   MachineFunction &MF = DAG.getMachineFunction();
6372   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6373   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6374       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6375   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6376   unsigned IntrOpcode = Intr->BaseOpcode;
6377   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6378 
6379   SmallVector<EVT, 3> ResultTypes(Op->values());
6380   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6381   bool IsD16 = false;
6382   bool IsG16 = false;
6383   bool IsA16 = false;
6384   SDValue VData;
6385   int NumVDataDwords;
6386   bool AdjustRetType = false;
6387 
6388   // Offset of intrinsic arguments
6389   const unsigned ArgOffset = WithChain ? 2 : 1;
6390 
6391   unsigned DMask;
6392   unsigned DMaskLanes = 0;
6393 
6394   if (BaseOpcode->Atomic) {
6395     VData = Op.getOperand(2);
6396 
6397     bool Is64Bit = VData.getValueType() == MVT::i64;
6398     if (BaseOpcode->AtomicX2) {
6399       SDValue VData2 = Op.getOperand(3);
6400       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6401                                  {VData, VData2});
6402       if (Is64Bit)
6403         VData = DAG.getBitcast(MVT::v4i32, VData);
6404 
6405       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6406       DMask = Is64Bit ? 0xf : 0x3;
6407       NumVDataDwords = Is64Bit ? 4 : 2;
6408     } else {
6409       DMask = Is64Bit ? 0x3 : 0x1;
6410       NumVDataDwords = Is64Bit ? 2 : 1;
6411     }
6412   } else {
6413     auto *DMaskConst =
6414         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6415     DMask = DMaskConst->getZExtValue();
6416     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6417 
6418     if (BaseOpcode->Store) {
6419       VData = Op.getOperand(2);
6420 
6421       MVT StoreVT = VData.getSimpleValueType();
6422       if (StoreVT.getScalarType() == MVT::f16) {
6423         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6424           return Op; // D16 is unsupported for this instruction
6425 
6426         IsD16 = true;
6427         VData = handleD16VData(VData, DAG, true);
6428       }
6429 
6430       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6431     } else {
6432       // Work out the num dwords based on the dmask popcount and underlying type
6433       // and whether packing is supported.
6434       MVT LoadVT = ResultTypes[0].getSimpleVT();
6435       if (LoadVT.getScalarType() == MVT::f16) {
6436         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6437           return Op; // D16 is unsupported for this instruction
6438 
6439         IsD16 = true;
6440       }
6441 
6442       // Confirm that the return type is large enough for the dmask specified
6443       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6444           (!LoadVT.isVector() && DMaskLanes > 1))
6445           return Op;
6446 
6447       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6448       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6449       // instructions.
6450       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6451           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6452         NumVDataDwords = (DMaskLanes + 1) / 2;
6453       else
6454         NumVDataDwords = DMaskLanes;
6455 
6456       AdjustRetType = true;
6457     }
6458   }
6459 
6460   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6461   SmallVector<SDValue, 4> VAddrs;
6462 
6463   // Check for 16 bit addresses or derivatives and pack if true.
6464   MVT VAddrVT =
6465       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6466   MVT VAddrScalarVT = VAddrVT.getScalarType();
6467   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6468   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6469 
6470   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6471   VAddrScalarVT = VAddrVT.getScalarType();
6472   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6473   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6474 
6475   // Push back extra arguments.
6476   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6477     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6478       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6479       // Special handling of bias when A16 is on. Bias is of type half but
6480       // occupies full 32-bit.
6481       SDValue Bias = DAG.getBuildVector(
6482           MVT::v2f16, DL,
6483           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6484       VAddrs.push_back(Bias);
6485     } else {
6486       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6487              "Bias needs to be converted to 16 bit in A16 mode");
6488       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6489     }
6490   }
6491 
6492   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6493     // 16 bit gradients are supported, but are tied to the A16 control
6494     // so both gradients and addresses must be 16 bit
6495     LLVM_DEBUG(
6496         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6497                   "require 16 bit args for both gradients and addresses");
6498     return Op;
6499   }
6500 
6501   if (IsA16) {
6502     if (!ST->hasA16()) {
6503       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6504                            "support 16 bit addresses\n");
6505       return Op;
6506     }
6507   }
6508 
6509   // We've dealt with incorrect input so we know that if IsA16, IsG16
6510   // are set then we have to compress/pack operands (either address,
6511   // gradient or both)
6512   // In the case where a16 and gradients are tied (no G16 support) then we
6513   // have already verified that both IsA16 and IsG16 are true
6514   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6515     // Activate g16
6516     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6517         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6518     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6519   }
6520 
6521   // Add gradients (packed or unpacked)
6522   if (IsG16) {
6523     // Pack the gradients
6524     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6525     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6526                               ArgOffset + Intr->GradientStart,
6527                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6528   } else {
6529     for (unsigned I = ArgOffset + Intr->GradientStart;
6530          I < ArgOffset + Intr->CoordStart; I++)
6531       VAddrs.push_back(Op.getOperand(I));
6532   }
6533 
6534   // Add addresses (packed or unpacked)
6535   if (IsA16) {
6536     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6537                               ArgOffset + Intr->CoordStart, VAddrEnd,
6538                               0 /* No gradients */);
6539   } else {
6540     // Add uncompressed address
6541     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6542       VAddrs.push_back(Op.getOperand(I));
6543   }
6544 
6545   // If the register allocator cannot place the address registers contiguously
6546   // without introducing moves, then using the non-sequential address encoding
6547   // is always preferable, since it saves VALU instructions and is usually a
6548   // wash in terms of code size or even better.
6549   //
6550   // However, we currently have no way of hinting to the register allocator that
6551   // MIMG addresses should be placed contiguously when it is possible to do so,
6552   // so force non-NSA for the common 2-address case as a heuristic.
6553   //
6554   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6555   // allocation when possible.
6556   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6557                 VAddrs.size() >= 3 &&
6558                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6559   SDValue VAddr;
6560   if (!UseNSA)
6561     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6562 
6563   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6564   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6565   SDValue Unorm;
6566   if (!BaseOpcode->Sampler) {
6567     Unorm = True;
6568   } else {
6569     auto UnormConst =
6570         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6571 
6572     Unorm = UnormConst->getZExtValue() ? True : False;
6573   }
6574 
6575   SDValue TFE;
6576   SDValue LWE;
6577   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6578   bool IsTexFail = false;
6579   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6580     return Op;
6581 
6582   if (IsTexFail) {
6583     if (!DMaskLanes) {
6584       // Expecting to get an error flag since TFC is on - and dmask is 0
6585       // Force dmask to be at least 1 otherwise the instruction will fail
6586       DMask = 0x1;
6587       DMaskLanes = 1;
6588       NumVDataDwords = 1;
6589     }
6590     NumVDataDwords += 1;
6591     AdjustRetType = true;
6592   }
6593 
6594   // Has something earlier tagged that the return type needs adjusting
6595   // This happens if the instruction is a load or has set TexFailCtrl flags
6596   if (AdjustRetType) {
6597     // NumVDataDwords reflects the true number of dwords required in the return type
6598     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6599       // This is a no-op load. This can be eliminated
6600       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6601       if (isa<MemSDNode>(Op))
6602         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6603       return Undef;
6604     }
6605 
6606     EVT NewVT = NumVDataDwords > 1 ?
6607                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6608                 : MVT::i32;
6609 
6610     ResultTypes[0] = NewVT;
6611     if (ResultTypes.size() == 3) {
6612       // Original result was aggregate type used for TexFailCtrl results
6613       // The actual instruction returns as a vector type which has now been
6614       // created. Remove the aggregate result.
6615       ResultTypes.erase(&ResultTypes[1]);
6616     }
6617   }
6618 
6619   unsigned CPol = cast<ConstantSDNode>(
6620       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6621   if (BaseOpcode->Atomic)
6622     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6623   if (CPol & ~AMDGPU::CPol::ALL)
6624     return Op;
6625 
6626   SmallVector<SDValue, 26> Ops;
6627   if (BaseOpcode->Store || BaseOpcode->Atomic)
6628     Ops.push_back(VData); // vdata
6629   if (UseNSA)
6630     append_range(Ops, VAddrs);
6631   else
6632     Ops.push_back(VAddr);
6633   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6634   if (BaseOpcode->Sampler)
6635     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6636   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6637   if (IsGFX10Plus)
6638     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6639   Ops.push_back(Unorm);
6640   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6641   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6642                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6643   if (IsGFX10Plus)
6644     Ops.push_back(IsA16 ? True : False);
6645   if (!Subtarget->hasGFX90AInsts()) {
6646     Ops.push_back(TFE); //tfe
6647   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6648     report_fatal_error("TFE is not supported on this GPU");
6649   }
6650   Ops.push_back(LWE); // lwe
6651   if (!IsGFX10Plus)
6652     Ops.push_back(DimInfo->DA ? True : False);
6653   if (BaseOpcode->HasD16)
6654     Ops.push_back(IsD16 ? True : False);
6655   if (isa<MemSDNode>(Op))
6656     Ops.push_back(Op.getOperand(0)); // chain
6657 
6658   int NumVAddrDwords =
6659       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6660   int Opcode = -1;
6661 
6662   if (IsGFX10Plus) {
6663     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6664                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6665                                           : AMDGPU::MIMGEncGfx10Default,
6666                                    NumVDataDwords, NumVAddrDwords);
6667   } else {
6668     if (Subtarget->hasGFX90AInsts()) {
6669       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6670                                      NumVDataDwords, NumVAddrDwords);
6671       if (Opcode == -1)
6672         report_fatal_error(
6673             "requested image instruction is not supported on this GPU");
6674     }
6675     if (Opcode == -1 &&
6676         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6677       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6678                                      NumVDataDwords, NumVAddrDwords);
6679     if (Opcode == -1)
6680       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6681                                      NumVDataDwords, NumVAddrDwords);
6682   }
6683   assert(Opcode != -1);
6684 
6685   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6686   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6687     MachineMemOperand *MemRef = MemOp->getMemOperand();
6688     DAG.setNodeMemRefs(NewNode, {MemRef});
6689   }
6690 
6691   if (BaseOpcode->AtomicX2) {
6692     SmallVector<SDValue, 1> Elt;
6693     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6694     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6695   }
6696   if (BaseOpcode->Store)
6697     return SDValue(NewNode, 0);
6698   return constructRetValue(DAG, NewNode,
6699                            OrigResultTypes, IsTexFail,
6700                            Subtarget->hasUnpackedD16VMem(), IsD16,
6701                            DMaskLanes, NumVDataDwords, DL);
6702 }
6703 
6704 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6705                                        SDValue Offset, SDValue CachePolicy,
6706                                        SelectionDAG &DAG) const {
6707   MachineFunction &MF = DAG.getMachineFunction();
6708 
6709   const DataLayout &DataLayout = DAG.getDataLayout();
6710   Align Alignment =
6711       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6712 
6713   MachineMemOperand *MMO = MF.getMachineMemOperand(
6714       MachinePointerInfo(),
6715       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6716           MachineMemOperand::MOInvariant,
6717       VT.getStoreSize(), Alignment);
6718 
6719   if (!Offset->isDivergent()) {
6720     SDValue Ops[] = {
6721         Rsrc,
6722         Offset, // Offset
6723         CachePolicy
6724     };
6725 
6726     // Widen vec3 load to vec4.
6727     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6728       EVT WidenedVT =
6729           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6730       auto WidenedOp = DAG.getMemIntrinsicNode(
6731           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6732           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6733       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6734                                    DAG.getVectorIdxConstant(0, DL));
6735       return Subvector;
6736     }
6737 
6738     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6739                                    DAG.getVTList(VT), Ops, VT, MMO);
6740   }
6741 
6742   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6743   // assume that the buffer is unswizzled.
6744   SmallVector<SDValue, 4> Loads;
6745   unsigned NumLoads = 1;
6746   MVT LoadVT = VT.getSimpleVT();
6747   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6748   assert((LoadVT.getScalarType() == MVT::i32 ||
6749           LoadVT.getScalarType() == MVT::f32));
6750 
6751   if (NumElts == 8 || NumElts == 16) {
6752     NumLoads = NumElts / 4;
6753     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6754   }
6755 
6756   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6757   SDValue Ops[] = {
6758       DAG.getEntryNode(),                               // Chain
6759       Rsrc,                                             // rsrc
6760       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6761       {},                                               // voffset
6762       {},                                               // soffset
6763       {},                                               // offset
6764       CachePolicy,                                      // cachepolicy
6765       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6766   };
6767 
6768   // Use the alignment to ensure that the required offsets will fit into the
6769   // immediate offsets.
6770   setBufferOffsets(Offset, DAG, &Ops[3],
6771                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6772 
6773   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6774   for (unsigned i = 0; i < NumLoads; ++i) {
6775     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6776     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6777                                         LoadVT, MMO, DAG));
6778   }
6779 
6780   if (NumElts == 8 || NumElts == 16)
6781     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6782 
6783   return Loads[0];
6784 }
6785 
6786 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6787                                           unsigned Dim,
6788                                           const ArgDescriptor &Arg) const {
6789   SDLoc SL(Op);
6790   MachineFunction &MF = DAG.getMachineFunction();
6791   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6792   if (MaxID == 0)
6793     return DAG.getConstant(0, SL, MVT::i32);
6794 
6795   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6796                                SDLoc(DAG.getEntryNode()), Arg);
6797 
6798   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6799   // masking operations anyway.
6800   //
6801   // TODO: We could assert the top bit is 0 for the source copy.
6802   if (Arg.isMasked())
6803     return Val;
6804 
6805   // Preserve the known bits after expansion to a copy.
6806   EVT SmallVT =
6807       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6808   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6809                      DAG.getValueType(SmallVT));
6810 }
6811 
6812 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6813                                                   SelectionDAG &DAG) const {
6814   MachineFunction &MF = DAG.getMachineFunction();
6815   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6816 
6817   EVT VT = Op.getValueType();
6818   SDLoc DL(Op);
6819   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6820 
6821   // TODO: Should this propagate fast-math-flags?
6822 
6823   switch (IntrinsicID) {
6824   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6825     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6826       return emitNonHSAIntrinsicError(DAG, DL, VT);
6827     return getPreloadedValue(DAG, *MFI, VT,
6828                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6829   }
6830   case Intrinsic::amdgcn_dispatch_ptr:
6831   case Intrinsic::amdgcn_queue_ptr: {
6832     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6833       DiagnosticInfoUnsupported BadIntrin(
6834           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6835           DL.getDebugLoc());
6836       DAG.getContext()->diagnose(BadIntrin);
6837       return DAG.getUNDEF(VT);
6838     }
6839 
6840     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6841       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6842     return getPreloadedValue(DAG, *MFI, VT, RegID);
6843   }
6844   case Intrinsic::amdgcn_implicitarg_ptr: {
6845     if (MFI->isEntryFunction())
6846       return getImplicitArgPtr(DAG, DL);
6847     return getPreloadedValue(DAG, *MFI, VT,
6848                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6849   }
6850   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6851     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6852       // This only makes sense to call in a kernel, so just lower to null.
6853       return DAG.getConstant(0, DL, VT);
6854     }
6855 
6856     return getPreloadedValue(DAG, *MFI, VT,
6857                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6858   }
6859   case Intrinsic::amdgcn_dispatch_id: {
6860     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6861   }
6862   case Intrinsic::amdgcn_rcp:
6863     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6864   case Intrinsic::amdgcn_rsq:
6865     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6866   case Intrinsic::amdgcn_rsq_legacy:
6867     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6868       return emitRemovedIntrinsicError(DAG, DL, VT);
6869     return SDValue();
6870   case Intrinsic::amdgcn_rcp_legacy:
6871     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6872       return emitRemovedIntrinsicError(DAG, DL, VT);
6873     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6874   case Intrinsic::amdgcn_rsq_clamp: {
6875     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6876       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6877 
6878     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6879     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6880     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6881 
6882     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6883     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6884                               DAG.getConstantFP(Max, DL, VT));
6885     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6886                        DAG.getConstantFP(Min, DL, VT));
6887   }
6888   case Intrinsic::r600_read_ngroups_x:
6889     if (Subtarget->isAmdHsaOS())
6890       return emitNonHSAIntrinsicError(DAG, DL, VT);
6891 
6892     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6893                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6894                                     false);
6895   case Intrinsic::r600_read_ngroups_y:
6896     if (Subtarget->isAmdHsaOS())
6897       return emitNonHSAIntrinsicError(DAG, DL, VT);
6898 
6899     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6900                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6901                                     false);
6902   case Intrinsic::r600_read_ngroups_z:
6903     if (Subtarget->isAmdHsaOS())
6904       return emitNonHSAIntrinsicError(DAG, DL, VT);
6905 
6906     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6907                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6908                                     false);
6909   case Intrinsic::r600_read_global_size_x:
6910     if (Subtarget->isAmdHsaOS())
6911       return emitNonHSAIntrinsicError(DAG, DL, VT);
6912 
6913     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6914                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6915                                     Align(4), false);
6916   case Intrinsic::r600_read_global_size_y:
6917     if (Subtarget->isAmdHsaOS())
6918       return emitNonHSAIntrinsicError(DAG, DL, VT);
6919 
6920     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6921                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6922                                     Align(4), false);
6923   case Intrinsic::r600_read_global_size_z:
6924     if (Subtarget->isAmdHsaOS())
6925       return emitNonHSAIntrinsicError(DAG, DL, VT);
6926 
6927     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6928                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6929                                     Align(4), false);
6930   case Intrinsic::r600_read_local_size_x:
6931     if (Subtarget->isAmdHsaOS())
6932       return emitNonHSAIntrinsicError(DAG, DL, VT);
6933 
6934     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6935                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6936   case Intrinsic::r600_read_local_size_y:
6937     if (Subtarget->isAmdHsaOS())
6938       return emitNonHSAIntrinsicError(DAG, DL, VT);
6939 
6940     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6941                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6942   case Intrinsic::r600_read_local_size_z:
6943     if (Subtarget->isAmdHsaOS())
6944       return emitNonHSAIntrinsicError(DAG, DL, VT);
6945 
6946     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6947                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6948   case Intrinsic::amdgcn_workgroup_id_x:
6949     return getPreloadedValue(DAG, *MFI, VT,
6950                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6951   case Intrinsic::amdgcn_workgroup_id_y:
6952     return getPreloadedValue(DAG, *MFI, VT,
6953                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6954   case Intrinsic::amdgcn_workgroup_id_z:
6955     return getPreloadedValue(DAG, *MFI, VT,
6956                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6957   case Intrinsic::amdgcn_workitem_id_x:
6958     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6959   case Intrinsic::amdgcn_workitem_id_y:
6960     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6961   case Intrinsic::amdgcn_workitem_id_z:
6962     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6963   case Intrinsic::amdgcn_wavefrontsize:
6964     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6965                            SDLoc(Op), MVT::i32);
6966   case Intrinsic::amdgcn_s_buffer_load: {
6967     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6968     if (CPol & ~AMDGPU::CPol::ALL)
6969       return Op;
6970     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6971                         DAG);
6972   }
6973   case Intrinsic::amdgcn_fdiv_fast:
6974     return lowerFDIV_FAST(Op, DAG);
6975   case Intrinsic::amdgcn_sin:
6976     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6977 
6978   case Intrinsic::amdgcn_cos:
6979     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6980 
6981   case Intrinsic::amdgcn_mul_u24:
6982     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6983   case Intrinsic::amdgcn_mul_i24:
6984     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6985 
6986   case Intrinsic::amdgcn_log_clamp: {
6987     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6988       return SDValue();
6989 
6990     return emitRemovedIntrinsicError(DAG, DL, VT);
6991   }
6992   case Intrinsic::amdgcn_ldexp:
6993     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6994                        Op.getOperand(1), Op.getOperand(2));
6995 
6996   case Intrinsic::amdgcn_fract:
6997     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6998 
6999   case Intrinsic::amdgcn_class:
7000     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
7001                        Op.getOperand(1), Op.getOperand(2));
7002   case Intrinsic::amdgcn_div_fmas:
7003     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
7004                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7005                        Op.getOperand(4));
7006 
7007   case Intrinsic::amdgcn_div_fixup:
7008     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
7009                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7010 
7011   case Intrinsic::amdgcn_div_scale: {
7012     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
7013 
7014     // Translate to the operands expected by the machine instruction. The
7015     // first parameter must be the same as the first instruction.
7016     SDValue Numerator = Op.getOperand(1);
7017     SDValue Denominator = Op.getOperand(2);
7018 
7019     // Note this order is opposite of the machine instruction's operations,
7020     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
7021     // intrinsic has the numerator as the first operand to match a normal
7022     // division operation.
7023 
7024     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
7025 
7026     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
7027                        Denominator, Numerator);
7028   }
7029   case Intrinsic::amdgcn_icmp: {
7030     // There is a Pat that handles this variant, so return it as-is.
7031     if (Op.getOperand(1).getValueType() == MVT::i1 &&
7032         Op.getConstantOperandVal(2) == 0 &&
7033         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7034       return Op;
7035     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7036   }
7037   case Intrinsic::amdgcn_fcmp: {
7038     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7039   }
7040   case Intrinsic::amdgcn_ballot:
7041     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7042   case Intrinsic::amdgcn_fmed3:
7043     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7044                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7045   case Intrinsic::amdgcn_fdot2:
7046     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7047                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7048                        Op.getOperand(4));
7049   case Intrinsic::amdgcn_fmul_legacy:
7050     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7051                        Op.getOperand(1), Op.getOperand(2));
7052   case Intrinsic::amdgcn_sffbh:
7053     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7054   case Intrinsic::amdgcn_sbfe:
7055     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7056                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7057   case Intrinsic::amdgcn_ubfe:
7058     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7059                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7060   case Intrinsic::amdgcn_cvt_pkrtz:
7061   case Intrinsic::amdgcn_cvt_pknorm_i16:
7062   case Intrinsic::amdgcn_cvt_pknorm_u16:
7063   case Intrinsic::amdgcn_cvt_pk_i16:
7064   case Intrinsic::amdgcn_cvt_pk_u16: {
7065     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7066     EVT VT = Op.getValueType();
7067     unsigned Opcode;
7068 
7069     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7070       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7071     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7072       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7073     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7074       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7075     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7076       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7077     else
7078       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7079 
7080     if (isTypeLegal(VT))
7081       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7082 
7083     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7084                                Op.getOperand(1), Op.getOperand(2));
7085     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7086   }
7087   case Intrinsic::amdgcn_fmad_ftz:
7088     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7089                        Op.getOperand(2), Op.getOperand(3));
7090 
7091   case Intrinsic::amdgcn_if_break:
7092     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7093                                       Op->getOperand(1), Op->getOperand(2)), 0);
7094 
7095   case Intrinsic::amdgcn_groupstaticsize: {
7096     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7097     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7098       return Op;
7099 
7100     const Module *M = MF.getFunction().getParent();
7101     const GlobalValue *GV =
7102         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7103     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7104                                             SIInstrInfo::MO_ABS32_LO);
7105     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7106   }
7107   case Intrinsic::amdgcn_is_shared:
7108   case Intrinsic::amdgcn_is_private: {
7109     SDLoc SL(Op);
7110     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7111       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7112     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7113     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7114                                  Op.getOperand(1));
7115 
7116     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7117                                 DAG.getConstant(1, SL, MVT::i32));
7118     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7119   }
7120   case Intrinsic::amdgcn_perm:
7121     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7122                        Op.getOperand(2), Op.getOperand(3));
7123   case Intrinsic::amdgcn_reloc_constant: {
7124     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7125     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7126     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7127     auto RelocSymbol = cast<GlobalVariable>(
7128         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7129     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7130                                             SIInstrInfo::MO_ABS32_LO);
7131     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7132   }
7133   default:
7134     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7135             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7136       return lowerImage(Op, ImageDimIntr, DAG, false);
7137 
7138     return Op;
7139   }
7140 }
7141 
7142 /// Update \p MMO based on the offset inputs to an intrinsic.
7143 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7144                             SDValue SOffset, SDValue Offset,
7145                             SDValue VIndex = SDValue()) {
7146   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7147       !isa<ConstantSDNode>(Offset)) {
7148     // The combined offset is not known to be constant, so we cannot represent
7149     // it in the MMO. Give up.
7150     MMO->setValue((Value *)nullptr);
7151     return;
7152   }
7153 
7154   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7155                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7156     // The strided index component of the address is not known to be zero, so we
7157     // cannot represent it in the MMO. Give up.
7158     MMO->setValue((Value *)nullptr);
7159     return;
7160   }
7161 
7162   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7163                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7164                  cast<ConstantSDNode>(Offset)->getSExtValue());
7165 }
7166 
7167 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7168                                                      SelectionDAG &DAG,
7169                                                      unsigned NewOpcode) const {
7170   SDLoc DL(Op);
7171 
7172   SDValue VData = Op.getOperand(2);
7173   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7174   SDValue Ops[] = {
7175     Op.getOperand(0), // Chain
7176     VData,            // vdata
7177     Op.getOperand(3), // rsrc
7178     DAG.getConstant(0, DL, MVT::i32), // vindex
7179     Offsets.first,    // voffset
7180     Op.getOperand(5), // soffset
7181     Offsets.second,   // offset
7182     Op.getOperand(6), // cachepolicy
7183     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7184   };
7185 
7186   auto *M = cast<MemSDNode>(Op);
7187   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7188 
7189   EVT MemVT = VData.getValueType();
7190   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7191                                  M->getMemOperand());
7192 }
7193 
7194 // Return a value to use for the idxen operand by examining the vindex operand.
7195 static unsigned getIdxEn(SDValue VIndex) {
7196   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7197     // No need to set idxen if vindex is known to be zero.
7198     return VIndexC->getZExtValue() != 0;
7199   return 1;
7200 }
7201 
7202 SDValue
7203 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7204                                                 unsigned NewOpcode) const {
7205   SDLoc DL(Op);
7206 
7207   SDValue VData = Op.getOperand(2);
7208   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7209   SDValue Ops[] = {
7210     Op.getOperand(0), // Chain
7211     VData,            // vdata
7212     Op.getOperand(3), // rsrc
7213     Op.getOperand(4), // vindex
7214     Offsets.first,    // voffset
7215     Op.getOperand(6), // soffset
7216     Offsets.second,   // offset
7217     Op.getOperand(7), // cachepolicy
7218     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7219   };
7220 
7221   auto *M = cast<MemSDNode>(Op);
7222   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7223 
7224   EVT MemVT = VData.getValueType();
7225   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7226                                  M->getMemOperand());
7227 }
7228 
7229 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7230                                                  SelectionDAG &DAG) const {
7231   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7232   SDLoc DL(Op);
7233 
7234   switch (IntrID) {
7235   case Intrinsic::amdgcn_ds_ordered_add:
7236   case Intrinsic::amdgcn_ds_ordered_swap: {
7237     MemSDNode *M = cast<MemSDNode>(Op);
7238     SDValue Chain = M->getOperand(0);
7239     SDValue M0 = M->getOperand(2);
7240     SDValue Value = M->getOperand(3);
7241     unsigned IndexOperand = M->getConstantOperandVal(7);
7242     unsigned WaveRelease = M->getConstantOperandVal(8);
7243     unsigned WaveDone = M->getConstantOperandVal(9);
7244 
7245     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7246     IndexOperand &= ~0x3f;
7247     unsigned CountDw = 0;
7248 
7249     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7250       CountDw = (IndexOperand >> 24) & 0xf;
7251       IndexOperand &= ~(0xf << 24);
7252 
7253       if (CountDw < 1 || CountDw > 4) {
7254         report_fatal_error(
7255             "ds_ordered_count: dword count must be between 1 and 4");
7256       }
7257     }
7258 
7259     if (IndexOperand)
7260       report_fatal_error("ds_ordered_count: bad index operand");
7261 
7262     if (WaveDone && !WaveRelease)
7263       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7264 
7265     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7266     unsigned ShaderType =
7267         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7268     unsigned Offset0 = OrderedCountIndex << 2;
7269     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7270                        (Instruction << 4);
7271 
7272     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7273       Offset1 |= (CountDw - 1) << 6;
7274 
7275     unsigned Offset = Offset0 | (Offset1 << 8);
7276 
7277     SDValue Ops[] = {
7278       Chain,
7279       Value,
7280       DAG.getTargetConstant(Offset, DL, MVT::i16),
7281       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7282     };
7283     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7284                                    M->getVTList(), Ops, M->getMemoryVT(),
7285                                    M->getMemOperand());
7286   }
7287   case Intrinsic::amdgcn_ds_fadd: {
7288     MemSDNode *M = cast<MemSDNode>(Op);
7289     unsigned Opc;
7290     switch (IntrID) {
7291     case Intrinsic::amdgcn_ds_fadd:
7292       Opc = ISD::ATOMIC_LOAD_FADD;
7293       break;
7294     }
7295 
7296     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7297                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7298                          M->getMemOperand());
7299   }
7300   case Intrinsic::amdgcn_atomic_inc:
7301   case Intrinsic::amdgcn_atomic_dec:
7302   case Intrinsic::amdgcn_ds_fmin:
7303   case Intrinsic::amdgcn_ds_fmax: {
7304     MemSDNode *M = cast<MemSDNode>(Op);
7305     unsigned Opc;
7306     switch (IntrID) {
7307     case Intrinsic::amdgcn_atomic_inc:
7308       Opc = AMDGPUISD::ATOMIC_INC;
7309       break;
7310     case Intrinsic::amdgcn_atomic_dec:
7311       Opc = AMDGPUISD::ATOMIC_DEC;
7312       break;
7313     case Intrinsic::amdgcn_ds_fmin:
7314       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7315       break;
7316     case Intrinsic::amdgcn_ds_fmax:
7317       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7318       break;
7319     default:
7320       llvm_unreachable("Unknown intrinsic!");
7321     }
7322     SDValue Ops[] = {
7323       M->getOperand(0), // Chain
7324       M->getOperand(2), // Ptr
7325       M->getOperand(3)  // Value
7326     };
7327 
7328     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7329                                    M->getMemoryVT(), M->getMemOperand());
7330   }
7331   case Intrinsic::amdgcn_buffer_load:
7332   case Intrinsic::amdgcn_buffer_load_format: {
7333     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7334     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7335     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7336     SDValue Ops[] = {
7337       Op.getOperand(0), // Chain
7338       Op.getOperand(2), // rsrc
7339       Op.getOperand(3), // vindex
7340       SDValue(),        // voffset -- will be set by setBufferOffsets
7341       SDValue(),        // soffset -- will be set by setBufferOffsets
7342       SDValue(),        // offset -- will be set by setBufferOffsets
7343       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7344       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7345     };
7346     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7347 
7348     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7349         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7350 
7351     EVT VT = Op.getValueType();
7352     EVT IntVT = VT.changeTypeToInteger();
7353     auto *M = cast<MemSDNode>(Op);
7354     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7355     EVT LoadVT = Op.getValueType();
7356 
7357     if (LoadVT.getScalarType() == MVT::f16)
7358       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7359                                  M, DAG, Ops);
7360 
7361     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7362     if (LoadVT.getScalarType() == MVT::i8 ||
7363         LoadVT.getScalarType() == MVT::i16)
7364       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7365 
7366     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7367                                M->getMemOperand(), DAG);
7368   }
7369   case Intrinsic::amdgcn_raw_buffer_load:
7370   case Intrinsic::amdgcn_raw_buffer_load_format: {
7371     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7372 
7373     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7374     SDValue Ops[] = {
7375       Op.getOperand(0), // Chain
7376       Op.getOperand(2), // rsrc
7377       DAG.getConstant(0, DL, MVT::i32), // vindex
7378       Offsets.first,    // voffset
7379       Op.getOperand(4), // soffset
7380       Offsets.second,   // offset
7381       Op.getOperand(5), // cachepolicy, swizzled buffer
7382       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7383     };
7384 
7385     auto *M = cast<MemSDNode>(Op);
7386     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7387     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7388   }
7389   case Intrinsic::amdgcn_struct_buffer_load:
7390   case Intrinsic::amdgcn_struct_buffer_load_format: {
7391     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7392 
7393     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7394     SDValue Ops[] = {
7395       Op.getOperand(0), // Chain
7396       Op.getOperand(2), // rsrc
7397       Op.getOperand(3), // vindex
7398       Offsets.first,    // voffset
7399       Op.getOperand(5), // soffset
7400       Offsets.second,   // offset
7401       Op.getOperand(6), // cachepolicy, swizzled buffer
7402       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7403     };
7404 
7405     auto *M = cast<MemSDNode>(Op);
7406     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7407     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7408   }
7409   case Intrinsic::amdgcn_tbuffer_load: {
7410     MemSDNode *M = cast<MemSDNode>(Op);
7411     EVT LoadVT = Op.getValueType();
7412 
7413     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7414     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7415     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7416     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7417     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7418     SDValue Ops[] = {
7419       Op.getOperand(0),  // Chain
7420       Op.getOperand(2),  // rsrc
7421       Op.getOperand(3),  // vindex
7422       Op.getOperand(4),  // voffset
7423       Op.getOperand(5),  // soffset
7424       Op.getOperand(6),  // offset
7425       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7426       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7427       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7428     };
7429 
7430     if (LoadVT.getScalarType() == MVT::f16)
7431       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7432                                  M, DAG, Ops);
7433     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7434                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7435                                DAG);
7436   }
7437   case Intrinsic::amdgcn_raw_tbuffer_load: {
7438     MemSDNode *M = cast<MemSDNode>(Op);
7439     EVT LoadVT = Op.getValueType();
7440     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7441 
7442     SDValue Ops[] = {
7443       Op.getOperand(0),  // Chain
7444       Op.getOperand(2),  // rsrc
7445       DAG.getConstant(0, DL, MVT::i32), // vindex
7446       Offsets.first,     // voffset
7447       Op.getOperand(4),  // soffset
7448       Offsets.second,    // offset
7449       Op.getOperand(5),  // format
7450       Op.getOperand(6),  // cachepolicy, swizzled buffer
7451       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7452     };
7453 
7454     if (LoadVT.getScalarType() == MVT::f16)
7455       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7456                                  M, DAG, Ops);
7457     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7458                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7459                                DAG);
7460   }
7461   case Intrinsic::amdgcn_struct_tbuffer_load: {
7462     MemSDNode *M = cast<MemSDNode>(Op);
7463     EVT LoadVT = Op.getValueType();
7464     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7465 
7466     SDValue Ops[] = {
7467       Op.getOperand(0),  // Chain
7468       Op.getOperand(2),  // rsrc
7469       Op.getOperand(3),  // vindex
7470       Offsets.first,     // voffset
7471       Op.getOperand(5),  // soffset
7472       Offsets.second,    // offset
7473       Op.getOperand(6),  // format
7474       Op.getOperand(7),  // cachepolicy, swizzled buffer
7475       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7476     };
7477 
7478     if (LoadVT.getScalarType() == MVT::f16)
7479       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7480                                  M, DAG, Ops);
7481     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7482                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7483                                DAG);
7484   }
7485   case Intrinsic::amdgcn_buffer_atomic_swap:
7486   case Intrinsic::amdgcn_buffer_atomic_add:
7487   case Intrinsic::amdgcn_buffer_atomic_sub:
7488   case Intrinsic::amdgcn_buffer_atomic_csub:
7489   case Intrinsic::amdgcn_buffer_atomic_smin:
7490   case Intrinsic::amdgcn_buffer_atomic_umin:
7491   case Intrinsic::amdgcn_buffer_atomic_smax:
7492   case Intrinsic::amdgcn_buffer_atomic_umax:
7493   case Intrinsic::amdgcn_buffer_atomic_and:
7494   case Intrinsic::amdgcn_buffer_atomic_or:
7495   case Intrinsic::amdgcn_buffer_atomic_xor:
7496   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7497     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7498     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7499     SDValue Ops[] = {
7500       Op.getOperand(0), // Chain
7501       Op.getOperand(2), // vdata
7502       Op.getOperand(3), // rsrc
7503       Op.getOperand(4), // vindex
7504       SDValue(),        // voffset -- will be set by setBufferOffsets
7505       SDValue(),        // soffset -- will be set by setBufferOffsets
7506       SDValue(),        // offset -- will be set by setBufferOffsets
7507       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7508       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7509     };
7510     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7511 
7512     EVT VT = Op.getValueType();
7513 
7514     auto *M = cast<MemSDNode>(Op);
7515     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7516     unsigned Opcode = 0;
7517 
7518     switch (IntrID) {
7519     case Intrinsic::amdgcn_buffer_atomic_swap:
7520       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7521       break;
7522     case Intrinsic::amdgcn_buffer_atomic_add:
7523       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7524       break;
7525     case Intrinsic::amdgcn_buffer_atomic_sub:
7526       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7527       break;
7528     case Intrinsic::amdgcn_buffer_atomic_csub:
7529       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7530       break;
7531     case Intrinsic::amdgcn_buffer_atomic_smin:
7532       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7533       break;
7534     case Intrinsic::amdgcn_buffer_atomic_umin:
7535       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7536       break;
7537     case Intrinsic::amdgcn_buffer_atomic_smax:
7538       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7539       break;
7540     case Intrinsic::amdgcn_buffer_atomic_umax:
7541       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7542       break;
7543     case Intrinsic::amdgcn_buffer_atomic_and:
7544       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7545       break;
7546     case Intrinsic::amdgcn_buffer_atomic_or:
7547       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7548       break;
7549     case Intrinsic::amdgcn_buffer_atomic_xor:
7550       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7551       break;
7552     case Intrinsic::amdgcn_buffer_atomic_fadd:
7553       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7554         DiagnosticInfoUnsupported
7555           NoFpRet(DAG.getMachineFunction().getFunction(),
7556                   "return versions of fp atomics not supported",
7557                   DL.getDebugLoc(), DS_Error);
7558         DAG.getContext()->diagnose(NoFpRet);
7559         return SDValue();
7560       }
7561       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7562       break;
7563     default:
7564       llvm_unreachable("unhandled atomic opcode");
7565     }
7566 
7567     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7568                                    M->getMemOperand());
7569   }
7570   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7571     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7572   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7573     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7574   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7575     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7576   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7577     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7578   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7579     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7580   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7581     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7582   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7583     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7584   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7585     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7586   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7587     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7588   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7589     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7590   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7591     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7592   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7593     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7594   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7595     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7596   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7597     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7598   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7599     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7600   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7601     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7602   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7603     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7604   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7605     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7606   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7607     return lowerStructBufferAtomicIntrin(Op, DAG,
7608                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7609   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7610     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7611   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7612     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7613   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7614     return lowerStructBufferAtomicIntrin(Op, DAG,
7615                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7616   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7617     return lowerStructBufferAtomicIntrin(Op, DAG,
7618                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7619   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7620     return lowerStructBufferAtomicIntrin(Op, DAG,
7621                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7622   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7623     return lowerStructBufferAtomicIntrin(Op, DAG,
7624                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7625   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7626     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7627   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7628     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7629   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7630     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7631   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7632     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7633   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7634     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7635 
7636   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7637     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7638     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7639     SDValue Ops[] = {
7640       Op.getOperand(0), // Chain
7641       Op.getOperand(2), // src
7642       Op.getOperand(3), // cmp
7643       Op.getOperand(4), // rsrc
7644       Op.getOperand(5), // vindex
7645       SDValue(),        // voffset -- will be set by setBufferOffsets
7646       SDValue(),        // soffset -- will be set by setBufferOffsets
7647       SDValue(),        // offset -- will be set by setBufferOffsets
7648       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7649       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7650     };
7651     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7652 
7653     EVT VT = Op.getValueType();
7654     auto *M = cast<MemSDNode>(Op);
7655     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7656 
7657     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7658                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7659   }
7660   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7661     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7662     SDValue Ops[] = {
7663       Op.getOperand(0), // Chain
7664       Op.getOperand(2), // src
7665       Op.getOperand(3), // cmp
7666       Op.getOperand(4), // rsrc
7667       DAG.getConstant(0, DL, MVT::i32), // vindex
7668       Offsets.first,    // voffset
7669       Op.getOperand(6), // soffset
7670       Offsets.second,   // offset
7671       Op.getOperand(7), // cachepolicy
7672       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7673     };
7674     EVT VT = Op.getValueType();
7675     auto *M = cast<MemSDNode>(Op);
7676     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7677 
7678     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7679                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7680   }
7681   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7682     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7683     SDValue Ops[] = {
7684       Op.getOperand(0), // Chain
7685       Op.getOperand(2), // src
7686       Op.getOperand(3), // cmp
7687       Op.getOperand(4), // rsrc
7688       Op.getOperand(5), // vindex
7689       Offsets.first,    // voffset
7690       Op.getOperand(7), // soffset
7691       Offsets.second,   // offset
7692       Op.getOperand(8), // cachepolicy
7693       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7694     };
7695     EVT VT = Op.getValueType();
7696     auto *M = cast<MemSDNode>(Op);
7697     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7698 
7699     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7700                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7701   }
7702   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7703     MemSDNode *M = cast<MemSDNode>(Op);
7704     SDValue NodePtr = M->getOperand(2);
7705     SDValue RayExtent = M->getOperand(3);
7706     SDValue RayOrigin = M->getOperand(4);
7707     SDValue RayDir = M->getOperand(5);
7708     SDValue RayInvDir = M->getOperand(6);
7709     SDValue TDescr = M->getOperand(7);
7710 
7711     assert(NodePtr.getValueType() == MVT::i32 ||
7712            NodePtr.getValueType() == MVT::i64);
7713     assert(RayDir.getValueType() == MVT::v3f16 ||
7714            RayDir.getValueType() == MVT::v3f32);
7715 
7716     if (!Subtarget->hasGFX10_AEncoding()) {
7717       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7718       return SDValue();
7719     }
7720 
7721     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7722     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7723     const unsigned NumVDataDwords = 4;
7724     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7725     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7726                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7727     const unsigned BaseOpcodes[2][2] = {
7728         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7729         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7730          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7731     int Opcode;
7732     if (UseNSA) {
7733       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7734                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7735                                      NumVAddrDwords);
7736     } else {
7737       Opcode = AMDGPU::getMIMGOpcode(
7738           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7739           PowerOf2Ceil(NumVAddrDwords));
7740     }
7741     assert(Opcode != -1);
7742 
7743     SmallVector<SDValue, 16> Ops;
7744 
7745     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7746       SmallVector<SDValue, 3> Lanes;
7747       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7748       if (Lanes[0].getValueSizeInBits() == 32) {
7749         for (unsigned I = 0; I < 3; ++I)
7750           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7751       } else {
7752         if (IsAligned) {
7753           Ops.push_back(
7754             DAG.getBitcast(MVT::i32,
7755                            DAG.getBuildVector(MVT::v2f16, DL,
7756                                               { Lanes[0], Lanes[1] })));
7757           Ops.push_back(Lanes[2]);
7758         } else {
7759           SDValue Elt0 = Ops.pop_back_val();
7760           Ops.push_back(
7761             DAG.getBitcast(MVT::i32,
7762                            DAG.getBuildVector(MVT::v2f16, DL,
7763                                               { Elt0, Lanes[0] })));
7764           Ops.push_back(
7765             DAG.getBitcast(MVT::i32,
7766                            DAG.getBuildVector(MVT::v2f16, DL,
7767                                               { Lanes[1], Lanes[2] })));
7768         }
7769       }
7770     };
7771 
7772     if (Is64)
7773       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7774     else
7775       Ops.push_back(NodePtr);
7776 
7777     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7778     packLanes(RayOrigin, true);
7779     packLanes(RayDir, true);
7780     packLanes(RayInvDir, false);
7781 
7782     if (!UseNSA) {
7783       // Build a single vector containing all the operands so far prepared.
7784       if (NumVAddrDwords > 8) {
7785         SDValue Undef = DAG.getUNDEF(MVT::i32);
7786         Ops.append(16 - Ops.size(), Undef);
7787       }
7788       assert(Ops.size() == 8 || Ops.size() == 16);
7789       SDValue MergedOps = DAG.getBuildVector(
7790           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7791       Ops.clear();
7792       Ops.push_back(MergedOps);
7793     }
7794 
7795     Ops.push_back(TDescr);
7796     if (IsA16)
7797       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7798     Ops.push_back(M->getChain());
7799 
7800     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7801     MachineMemOperand *MemRef = M->getMemOperand();
7802     DAG.setNodeMemRefs(NewNode, {MemRef});
7803     return SDValue(NewNode, 0);
7804   }
7805   case Intrinsic::amdgcn_global_atomic_fadd:
7806     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7807       DiagnosticInfoUnsupported
7808         NoFpRet(DAG.getMachineFunction().getFunction(),
7809                 "return versions of fp atomics not supported",
7810                 DL.getDebugLoc(), DS_Error);
7811       DAG.getContext()->diagnose(NoFpRet);
7812       return SDValue();
7813     }
7814     LLVM_FALLTHROUGH;
7815   case Intrinsic::amdgcn_global_atomic_fmin:
7816   case Intrinsic::amdgcn_global_atomic_fmax:
7817   case Intrinsic::amdgcn_flat_atomic_fadd:
7818   case Intrinsic::amdgcn_flat_atomic_fmin:
7819   case Intrinsic::amdgcn_flat_atomic_fmax: {
7820     MemSDNode *M = cast<MemSDNode>(Op);
7821     SDValue Ops[] = {
7822       M->getOperand(0), // Chain
7823       M->getOperand(2), // Ptr
7824       M->getOperand(3)  // Value
7825     };
7826     unsigned Opcode = 0;
7827     switch (IntrID) {
7828     case Intrinsic::amdgcn_global_atomic_fadd:
7829     case Intrinsic::amdgcn_flat_atomic_fadd: {
7830       EVT VT = Op.getOperand(3).getValueType();
7831       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7832                            DAG.getVTList(VT, MVT::Other), Ops,
7833                            M->getMemOperand());
7834     }
7835     case Intrinsic::amdgcn_global_atomic_fmin:
7836     case Intrinsic::amdgcn_flat_atomic_fmin: {
7837       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7838       break;
7839     }
7840     case Intrinsic::amdgcn_global_atomic_fmax:
7841     case Intrinsic::amdgcn_flat_atomic_fmax: {
7842       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7843       break;
7844     }
7845     default:
7846       llvm_unreachable("unhandled atomic opcode");
7847     }
7848     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7849                                    M->getVTList(), Ops, M->getMemoryVT(),
7850                                    M->getMemOperand());
7851   }
7852   default:
7853 
7854     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7855             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7856       return lowerImage(Op, ImageDimIntr, DAG, true);
7857 
7858     return SDValue();
7859   }
7860 }
7861 
7862 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7863 // dwordx4 if on SI.
7864 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7865                                               SDVTList VTList,
7866                                               ArrayRef<SDValue> Ops, EVT MemVT,
7867                                               MachineMemOperand *MMO,
7868                                               SelectionDAG &DAG) const {
7869   EVT VT = VTList.VTs[0];
7870   EVT WidenedVT = VT;
7871   EVT WidenedMemVT = MemVT;
7872   if (!Subtarget->hasDwordx3LoadStores() &&
7873       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7874     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7875                                  WidenedVT.getVectorElementType(), 4);
7876     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7877                                     WidenedMemVT.getVectorElementType(), 4);
7878     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7879   }
7880 
7881   assert(VTList.NumVTs == 2);
7882   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7883 
7884   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7885                                        WidenedMemVT, MMO);
7886   if (WidenedVT != VT) {
7887     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7888                                DAG.getVectorIdxConstant(0, DL));
7889     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7890   }
7891   return NewOp;
7892 }
7893 
7894 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7895                                          bool ImageStore) const {
7896   EVT StoreVT = VData.getValueType();
7897 
7898   // No change for f16 and legal vector D16 types.
7899   if (!StoreVT.isVector())
7900     return VData;
7901 
7902   SDLoc DL(VData);
7903   unsigned NumElements = StoreVT.getVectorNumElements();
7904 
7905   if (Subtarget->hasUnpackedD16VMem()) {
7906     // We need to unpack the packed data to store.
7907     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7908     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7909 
7910     EVT EquivStoreVT =
7911         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7912     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7913     return DAG.UnrollVectorOp(ZExt.getNode());
7914   }
7915 
7916   // The sq block of gfx8.1 does not estimate register use correctly for d16
7917   // image store instructions. The data operand is computed as if it were not a
7918   // d16 image instruction.
7919   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7920     // Bitcast to i16
7921     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7922     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7923 
7924     // Decompose into scalars
7925     SmallVector<SDValue, 4> Elts;
7926     DAG.ExtractVectorElements(IntVData, Elts);
7927 
7928     // Group pairs of i16 into v2i16 and bitcast to i32
7929     SmallVector<SDValue, 4> PackedElts;
7930     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7931       SDValue Pair =
7932           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7933       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7934       PackedElts.push_back(IntPair);
7935     }
7936     if ((NumElements % 2) == 1) {
7937       // Handle v3i16
7938       unsigned I = Elts.size() / 2;
7939       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7940                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7941       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7942       PackedElts.push_back(IntPair);
7943     }
7944 
7945     // Pad using UNDEF
7946     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7947 
7948     // Build final vector
7949     EVT VecVT =
7950         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7951     return DAG.getBuildVector(VecVT, DL, PackedElts);
7952   }
7953 
7954   if (NumElements == 3) {
7955     EVT IntStoreVT =
7956         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7957     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7958 
7959     EVT WidenedStoreVT = EVT::getVectorVT(
7960         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7961     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7962                                          WidenedStoreVT.getStoreSizeInBits());
7963     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7964     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7965   }
7966 
7967   assert(isTypeLegal(StoreVT));
7968   return VData;
7969 }
7970 
7971 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7972                                               SelectionDAG &DAG) const {
7973   SDLoc DL(Op);
7974   SDValue Chain = Op.getOperand(0);
7975   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7976   MachineFunction &MF = DAG.getMachineFunction();
7977 
7978   switch (IntrinsicID) {
7979   case Intrinsic::amdgcn_exp_compr: {
7980     SDValue Src0 = Op.getOperand(4);
7981     SDValue Src1 = Op.getOperand(5);
7982     // Hack around illegal type on SI by directly selecting it.
7983     if (isTypeLegal(Src0.getValueType()))
7984       return SDValue();
7985 
7986     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7987     SDValue Undef = DAG.getUNDEF(MVT::f32);
7988     const SDValue Ops[] = {
7989       Op.getOperand(2), // tgt
7990       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7991       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7992       Undef, // src2
7993       Undef, // src3
7994       Op.getOperand(7), // vm
7995       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7996       Op.getOperand(3), // en
7997       Op.getOperand(0) // Chain
7998     };
7999 
8000     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
8001     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
8002   }
8003   case Intrinsic::amdgcn_s_barrier: {
8004     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
8005       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
8006       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
8007       if (WGSize <= ST.getWavefrontSize())
8008         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
8009                                           Op.getOperand(0)), 0);
8010     }
8011     return SDValue();
8012   };
8013   case Intrinsic::amdgcn_tbuffer_store: {
8014     SDValue VData = Op.getOperand(2);
8015     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8016     if (IsD16)
8017       VData = handleD16VData(VData, DAG);
8018     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
8019     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
8020     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
8021     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
8022     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8023     SDValue Ops[] = {
8024       Chain,
8025       VData,             // vdata
8026       Op.getOperand(3),  // rsrc
8027       Op.getOperand(4),  // vindex
8028       Op.getOperand(5),  // voffset
8029       Op.getOperand(6),  // soffset
8030       Op.getOperand(7),  // offset
8031       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8032       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8033       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8034     };
8035     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8036                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8037     MemSDNode *M = cast<MemSDNode>(Op);
8038     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8039                                    M->getMemoryVT(), M->getMemOperand());
8040   }
8041 
8042   case Intrinsic::amdgcn_struct_tbuffer_store: {
8043     SDValue VData = Op.getOperand(2);
8044     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8045     if (IsD16)
8046       VData = handleD16VData(VData, DAG);
8047     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8048     SDValue Ops[] = {
8049       Chain,
8050       VData,             // vdata
8051       Op.getOperand(3),  // rsrc
8052       Op.getOperand(4),  // vindex
8053       Offsets.first,     // voffset
8054       Op.getOperand(6),  // soffset
8055       Offsets.second,    // offset
8056       Op.getOperand(7),  // format
8057       Op.getOperand(8),  // cachepolicy, swizzled buffer
8058       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8059     };
8060     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8061                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8062     MemSDNode *M = cast<MemSDNode>(Op);
8063     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8064                                    M->getMemoryVT(), M->getMemOperand());
8065   }
8066 
8067   case Intrinsic::amdgcn_raw_tbuffer_store: {
8068     SDValue VData = Op.getOperand(2);
8069     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8070     if (IsD16)
8071       VData = handleD16VData(VData, DAG);
8072     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8073     SDValue Ops[] = {
8074       Chain,
8075       VData,             // vdata
8076       Op.getOperand(3),  // rsrc
8077       DAG.getConstant(0, DL, MVT::i32), // vindex
8078       Offsets.first,     // voffset
8079       Op.getOperand(5),  // soffset
8080       Offsets.second,    // offset
8081       Op.getOperand(6),  // format
8082       Op.getOperand(7),  // cachepolicy, swizzled buffer
8083       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8084     };
8085     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8086                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8087     MemSDNode *M = cast<MemSDNode>(Op);
8088     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8089                                    M->getMemoryVT(), M->getMemOperand());
8090   }
8091 
8092   case Intrinsic::amdgcn_buffer_store:
8093   case Intrinsic::amdgcn_buffer_store_format: {
8094     SDValue VData = Op.getOperand(2);
8095     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8096     if (IsD16)
8097       VData = handleD16VData(VData, DAG);
8098     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8099     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8100     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8101     SDValue Ops[] = {
8102       Chain,
8103       VData,
8104       Op.getOperand(3), // rsrc
8105       Op.getOperand(4), // vindex
8106       SDValue(), // voffset -- will be set by setBufferOffsets
8107       SDValue(), // soffset -- will be set by setBufferOffsets
8108       SDValue(), // offset -- will be set by setBufferOffsets
8109       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8110       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8111     };
8112     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8113 
8114     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8115                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8116     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8117     MemSDNode *M = cast<MemSDNode>(Op);
8118     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8119 
8120     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8121     EVT VDataType = VData.getValueType().getScalarType();
8122     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8123       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8124 
8125     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8126                                    M->getMemoryVT(), M->getMemOperand());
8127   }
8128 
8129   case Intrinsic::amdgcn_raw_buffer_store:
8130   case Intrinsic::amdgcn_raw_buffer_store_format: {
8131     const bool IsFormat =
8132         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8133 
8134     SDValue VData = Op.getOperand(2);
8135     EVT VDataVT = VData.getValueType();
8136     EVT EltType = VDataVT.getScalarType();
8137     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8138     if (IsD16) {
8139       VData = handleD16VData(VData, DAG);
8140       VDataVT = VData.getValueType();
8141     }
8142 
8143     if (!isTypeLegal(VDataVT)) {
8144       VData =
8145           DAG.getNode(ISD::BITCAST, DL,
8146                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8147     }
8148 
8149     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8150     SDValue Ops[] = {
8151       Chain,
8152       VData,
8153       Op.getOperand(3), // rsrc
8154       DAG.getConstant(0, DL, MVT::i32), // vindex
8155       Offsets.first,    // voffset
8156       Op.getOperand(5), // soffset
8157       Offsets.second,   // offset
8158       Op.getOperand(6), // cachepolicy, swizzled buffer
8159       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8160     };
8161     unsigned Opc =
8162         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8163     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8164     MemSDNode *M = cast<MemSDNode>(Op);
8165     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8166 
8167     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8168     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8169       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8170 
8171     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8172                                    M->getMemoryVT(), M->getMemOperand());
8173   }
8174 
8175   case Intrinsic::amdgcn_struct_buffer_store:
8176   case Intrinsic::amdgcn_struct_buffer_store_format: {
8177     const bool IsFormat =
8178         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8179 
8180     SDValue VData = Op.getOperand(2);
8181     EVT VDataVT = VData.getValueType();
8182     EVT EltType = VDataVT.getScalarType();
8183     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8184 
8185     if (IsD16) {
8186       VData = handleD16VData(VData, DAG);
8187       VDataVT = VData.getValueType();
8188     }
8189 
8190     if (!isTypeLegal(VDataVT)) {
8191       VData =
8192           DAG.getNode(ISD::BITCAST, DL,
8193                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8194     }
8195 
8196     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8197     SDValue Ops[] = {
8198       Chain,
8199       VData,
8200       Op.getOperand(3), // rsrc
8201       Op.getOperand(4), // vindex
8202       Offsets.first,    // voffset
8203       Op.getOperand(6), // soffset
8204       Offsets.second,   // offset
8205       Op.getOperand(7), // cachepolicy, swizzled buffer
8206       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8207     };
8208     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8209                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8210     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8211     MemSDNode *M = cast<MemSDNode>(Op);
8212     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8213 
8214     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8215     EVT VDataType = VData.getValueType().getScalarType();
8216     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8217       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8218 
8219     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8220                                    M->getMemoryVT(), M->getMemOperand());
8221   }
8222   case Intrinsic::amdgcn_end_cf:
8223     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8224                                       Op->getOperand(2), Chain), 0);
8225 
8226   default: {
8227     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8228             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8229       return lowerImage(Op, ImageDimIntr, DAG, true);
8230 
8231     return Op;
8232   }
8233   }
8234 }
8235 
8236 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8237 // offset (the offset that is included in bounds checking and swizzling, to be
8238 // split between the instruction's voffset and immoffset fields) and soffset
8239 // (the offset that is excluded from bounds checking and swizzling, to go in
8240 // the instruction's soffset field).  This function takes the first kind of
8241 // offset and figures out how to split it between voffset and immoffset.
8242 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8243     SDValue Offset, SelectionDAG &DAG) const {
8244   SDLoc DL(Offset);
8245   const unsigned MaxImm = 4095;
8246   SDValue N0 = Offset;
8247   ConstantSDNode *C1 = nullptr;
8248 
8249   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8250     N0 = SDValue();
8251   else if (DAG.isBaseWithConstantOffset(N0)) {
8252     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8253     N0 = N0.getOperand(0);
8254   }
8255 
8256   if (C1) {
8257     unsigned ImmOffset = C1->getZExtValue();
8258     // If the immediate value is too big for the immoffset field, put the value
8259     // and -4096 into the immoffset field so that the value that is copied/added
8260     // for the voffset field is a multiple of 4096, and it stands more chance
8261     // of being CSEd with the copy/add for another similar load/store.
8262     // However, do not do that rounding down to a multiple of 4096 if that is a
8263     // negative number, as it appears to be illegal to have a negative offset
8264     // in the vgpr, even if adding the immediate offset makes it positive.
8265     unsigned Overflow = ImmOffset & ~MaxImm;
8266     ImmOffset -= Overflow;
8267     if ((int32_t)Overflow < 0) {
8268       Overflow += ImmOffset;
8269       ImmOffset = 0;
8270     }
8271     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8272     if (Overflow) {
8273       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8274       if (!N0)
8275         N0 = OverflowVal;
8276       else {
8277         SDValue Ops[] = { N0, OverflowVal };
8278         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8279       }
8280     }
8281   }
8282   if (!N0)
8283     N0 = DAG.getConstant(0, DL, MVT::i32);
8284   if (!C1)
8285     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8286   return {N0, SDValue(C1, 0)};
8287 }
8288 
8289 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8290 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8291 // pointed to by Offsets.
8292 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8293                                         SelectionDAG &DAG, SDValue *Offsets,
8294                                         Align Alignment) const {
8295   SDLoc DL(CombinedOffset);
8296   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8297     uint32_t Imm = C->getZExtValue();
8298     uint32_t SOffset, ImmOffset;
8299     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8300                                  Alignment)) {
8301       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8302       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8303       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8304       return;
8305     }
8306   }
8307   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8308     SDValue N0 = CombinedOffset.getOperand(0);
8309     SDValue N1 = CombinedOffset.getOperand(1);
8310     uint32_t SOffset, ImmOffset;
8311     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8312     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8313                                                 Subtarget, Alignment)) {
8314       Offsets[0] = N0;
8315       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8316       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8317       return;
8318     }
8319   }
8320   Offsets[0] = CombinedOffset;
8321   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8322   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8323 }
8324 
8325 // Handle 8 bit and 16 bit buffer loads
8326 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8327                                                      EVT LoadVT, SDLoc DL,
8328                                                      ArrayRef<SDValue> Ops,
8329                                                      MemSDNode *M) const {
8330   EVT IntVT = LoadVT.changeTypeToInteger();
8331   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8332          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8333 
8334   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8335   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8336                                                Ops, IntVT,
8337                                                M->getMemOperand());
8338   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8339   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8340 
8341   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8342 }
8343 
8344 // Handle 8 bit and 16 bit buffer stores
8345 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8346                                                       EVT VDataType, SDLoc DL,
8347                                                       SDValue Ops[],
8348                                                       MemSDNode *M) const {
8349   if (VDataType == MVT::f16)
8350     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8351 
8352   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8353   Ops[1] = BufferStoreExt;
8354   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8355                                  AMDGPUISD::BUFFER_STORE_SHORT;
8356   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8357   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8358                                      M->getMemOperand());
8359 }
8360 
8361 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8362                                  ISD::LoadExtType ExtType, SDValue Op,
8363                                  const SDLoc &SL, EVT VT) {
8364   if (VT.bitsLT(Op.getValueType()))
8365     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8366 
8367   switch (ExtType) {
8368   case ISD::SEXTLOAD:
8369     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8370   case ISD::ZEXTLOAD:
8371     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8372   case ISD::EXTLOAD:
8373     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8374   case ISD::NON_EXTLOAD:
8375     return Op;
8376   }
8377 
8378   llvm_unreachable("invalid ext type");
8379 }
8380 
8381 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8382   SelectionDAG &DAG = DCI.DAG;
8383   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8384     return SDValue();
8385 
8386   // FIXME: Constant loads should all be marked invariant.
8387   unsigned AS = Ld->getAddressSpace();
8388   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8389       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8390       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8391     return SDValue();
8392 
8393   // Don't do this early, since it may interfere with adjacent load merging for
8394   // illegal types. We can avoid losing alignment information for exotic types
8395   // pre-legalize.
8396   EVT MemVT = Ld->getMemoryVT();
8397   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8398       MemVT.getSizeInBits() >= 32)
8399     return SDValue();
8400 
8401   SDLoc SL(Ld);
8402 
8403   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8404          "unexpected vector extload");
8405 
8406   // TODO: Drop only high part of range.
8407   SDValue Ptr = Ld->getBasePtr();
8408   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8409                                 MVT::i32, SL, Ld->getChain(), Ptr,
8410                                 Ld->getOffset(),
8411                                 Ld->getPointerInfo(), MVT::i32,
8412                                 Ld->getAlignment(),
8413                                 Ld->getMemOperand()->getFlags(),
8414                                 Ld->getAAInfo(),
8415                                 nullptr); // Drop ranges
8416 
8417   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8418   if (MemVT.isFloatingPoint()) {
8419     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8420            "unexpected fp extload");
8421     TruncVT = MemVT.changeTypeToInteger();
8422   }
8423 
8424   SDValue Cvt = NewLoad;
8425   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8426     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8427                       DAG.getValueType(TruncVT));
8428   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8429              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8430     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8431   } else {
8432     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8433   }
8434 
8435   EVT VT = Ld->getValueType(0);
8436   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8437 
8438   DCI.AddToWorklist(Cvt.getNode());
8439 
8440   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8441   // the appropriate extension from the 32-bit load.
8442   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8443   DCI.AddToWorklist(Cvt.getNode());
8444 
8445   // Handle conversion back to floating point if necessary.
8446   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8447 
8448   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8449 }
8450 
8451 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8452   SDLoc DL(Op);
8453   LoadSDNode *Load = cast<LoadSDNode>(Op);
8454   ISD::LoadExtType ExtType = Load->getExtensionType();
8455   EVT MemVT = Load->getMemoryVT();
8456 
8457   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8458     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8459       return SDValue();
8460 
8461     // FIXME: Copied from PPC
8462     // First, load into 32 bits, then truncate to 1 bit.
8463 
8464     SDValue Chain = Load->getChain();
8465     SDValue BasePtr = Load->getBasePtr();
8466     MachineMemOperand *MMO = Load->getMemOperand();
8467 
8468     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8469 
8470     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8471                                    BasePtr, RealMemVT, MMO);
8472 
8473     if (!MemVT.isVector()) {
8474       SDValue Ops[] = {
8475         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8476         NewLD.getValue(1)
8477       };
8478 
8479       return DAG.getMergeValues(Ops, DL);
8480     }
8481 
8482     SmallVector<SDValue, 3> Elts;
8483     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8484       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8485                                 DAG.getConstant(I, DL, MVT::i32));
8486 
8487       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8488     }
8489 
8490     SDValue Ops[] = {
8491       DAG.getBuildVector(MemVT, DL, Elts),
8492       NewLD.getValue(1)
8493     };
8494 
8495     return DAG.getMergeValues(Ops, DL);
8496   }
8497 
8498   if (!MemVT.isVector())
8499     return SDValue();
8500 
8501   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8502          "Custom lowering for non-i32 vectors hasn't been implemented.");
8503 
8504   unsigned Alignment = Load->getAlignment();
8505   unsigned AS = Load->getAddressSpace();
8506   if (Subtarget->hasLDSMisalignedBug() &&
8507       AS == AMDGPUAS::FLAT_ADDRESS &&
8508       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8509     return SplitVectorLoad(Op, DAG);
8510   }
8511 
8512   MachineFunction &MF = DAG.getMachineFunction();
8513   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8514   // If there is a possibility that flat instruction access scratch memory
8515   // then we need to use the same legalization rules we use for private.
8516   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8517       !Subtarget->hasMultiDwordFlatScratchAddressing())
8518     AS = MFI->hasFlatScratchInit() ?
8519          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8520 
8521   unsigned NumElements = MemVT.getVectorNumElements();
8522 
8523   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8524       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8525     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8526       if (MemVT.isPow2VectorType())
8527         return SDValue();
8528       return WidenOrSplitVectorLoad(Op, DAG);
8529     }
8530     // Non-uniform loads will be selected to MUBUF instructions, so they
8531     // have the same legalization requirements as global and private
8532     // loads.
8533     //
8534   }
8535 
8536   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8537       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8538       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8539     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8540         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8541         Alignment >= 4 && NumElements < 32) {
8542       if (MemVT.isPow2VectorType())
8543         return SDValue();
8544       return WidenOrSplitVectorLoad(Op, DAG);
8545     }
8546     // Non-uniform loads will be selected to MUBUF instructions, so they
8547     // have the same legalization requirements as global and private
8548     // loads.
8549     //
8550   }
8551   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8552       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8553       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8554       AS == AMDGPUAS::FLAT_ADDRESS) {
8555     if (NumElements > 4)
8556       return SplitVectorLoad(Op, DAG);
8557     // v3 loads not supported on SI.
8558     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8559       return WidenOrSplitVectorLoad(Op, DAG);
8560 
8561     // v3 and v4 loads are supported for private and global memory.
8562     return SDValue();
8563   }
8564   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8565     // Depending on the setting of the private_element_size field in the
8566     // resource descriptor, we can only make private accesses up to a certain
8567     // size.
8568     switch (Subtarget->getMaxPrivateElementSize()) {
8569     case 4: {
8570       SDValue Ops[2];
8571       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8572       return DAG.getMergeValues(Ops, DL);
8573     }
8574     case 8:
8575       if (NumElements > 2)
8576         return SplitVectorLoad(Op, DAG);
8577       return SDValue();
8578     case 16:
8579       // Same as global/flat
8580       if (NumElements > 4)
8581         return SplitVectorLoad(Op, DAG);
8582       // v3 loads not supported on SI.
8583       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8584         return WidenOrSplitVectorLoad(Op, DAG);
8585 
8586       return SDValue();
8587     default:
8588       llvm_unreachable("unsupported private_element_size");
8589     }
8590   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8591     bool Fast = false;
8592     auto Flags = Load->getMemOperand()->getFlags();
8593     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8594                                            Load->getAlign(), Flags, &Fast) &&
8595         Fast)
8596       return SDValue();
8597 
8598     if (MemVT.isVector())
8599       return SplitVectorLoad(Op, DAG);
8600   }
8601 
8602   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8603                                       MemVT, *Load->getMemOperand())) {
8604     SDValue Ops[2];
8605     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8606     return DAG.getMergeValues(Ops, DL);
8607   }
8608 
8609   return SDValue();
8610 }
8611 
8612 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8613   EVT VT = Op.getValueType();
8614   if (VT.getSizeInBits() == 128)
8615     return splitTernaryVectorOp(Op, DAG);
8616 
8617   assert(VT.getSizeInBits() == 64);
8618 
8619   SDLoc DL(Op);
8620   SDValue Cond = Op.getOperand(0);
8621 
8622   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8623   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8624 
8625   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8626   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8627 
8628   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8629   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8630 
8631   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8632 
8633   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8634   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8635 
8636   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8637 
8638   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8639   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8640 }
8641 
8642 // Catch division cases where we can use shortcuts with rcp and rsq
8643 // instructions.
8644 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8645                                               SelectionDAG &DAG) const {
8646   SDLoc SL(Op);
8647   SDValue LHS = Op.getOperand(0);
8648   SDValue RHS = Op.getOperand(1);
8649   EVT VT = Op.getValueType();
8650   const SDNodeFlags Flags = Op->getFlags();
8651 
8652   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8653 
8654   // Without !fpmath accuracy information, we can't do more because we don't
8655   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8656   if (!AllowInaccurateRcp)
8657     return SDValue();
8658 
8659   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8660     if (CLHS->isExactlyValue(1.0)) {
8661       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8662       // the CI documentation has a worst case error of 1 ulp.
8663       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8664       // use it as long as we aren't trying to use denormals.
8665       //
8666       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8667 
8668       // 1.0 / sqrt(x) -> rsq(x)
8669 
8670       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8671       // error seems really high at 2^29 ULP.
8672       if (RHS.getOpcode() == ISD::FSQRT)
8673         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8674 
8675       // 1.0 / x -> rcp(x)
8676       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8677     }
8678 
8679     // Same as for 1.0, but expand the sign out of the constant.
8680     if (CLHS->isExactlyValue(-1.0)) {
8681       // -1.0 / x -> rcp (fneg x)
8682       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8683       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8684     }
8685   }
8686 
8687   // Turn into multiply by the reciprocal.
8688   // x / y -> x * (1.0 / y)
8689   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8690   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8691 }
8692 
8693 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8694                                                 SelectionDAG &DAG) const {
8695   SDLoc SL(Op);
8696   SDValue X = Op.getOperand(0);
8697   SDValue Y = Op.getOperand(1);
8698   EVT VT = Op.getValueType();
8699   const SDNodeFlags Flags = Op->getFlags();
8700 
8701   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8702                             DAG.getTarget().Options.UnsafeFPMath;
8703   if (!AllowInaccurateDiv)
8704     return SDValue();
8705 
8706   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8707   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8708 
8709   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8710   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8711 
8712   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8713   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8714   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8715   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8716   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8717   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8718 }
8719 
8720 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8721                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8722                           SDNodeFlags Flags) {
8723   if (GlueChain->getNumValues() <= 1) {
8724     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8725   }
8726 
8727   assert(GlueChain->getNumValues() == 3);
8728 
8729   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8730   switch (Opcode) {
8731   default: llvm_unreachable("no chain equivalent for opcode");
8732   case ISD::FMUL:
8733     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8734     break;
8735   }
8736 
8737   return DAG.getNode(Opcode, SL, VTList,
8738                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8739                      Flags);
8740 }
8741 
8742 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8743                            EVT VT, SDValue A, SDValue B, SDValue C,
8744                            SDValue GlueChain, SDNodeFlags Flags) {
8745   if (GlueChain->getNumValues() <= 1) {
8746     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8747   }
8748 
8749   assert(GlueChain->getNumValues() == 3);
8750 
8751   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8752   switch (Opcode) {
8753   default: llvm_unreachable("no chain equivalent for opcode");
8754   case ISD::FMA:
8755     Opcode = AMDGPUISD::FMA_W_CHAIN;
8756     break;
8757   }
8758 
8759   return DAG.getNode(Opcode, SL, VTList,
8760                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8761                      Flags);
8762 }
8763 
8764 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8765   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8766     return FastLowered;
8767 
8768   SDLoc SL(Op);
8769   SDValue Src0 = Op.getOperand(0);
8770   SDValue Src1 = Op.getOperand(1);
8771 
8772   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8773   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8774 
8775   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8776   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8777 
8778   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8779   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8780 
8781   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8782 }
8783 
8784 // Faster 2.5 ULP division that does not support denormals.
8785 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8786   SDLoc SL(Op);
8787   SDValue LHS = Op.getOperand(1);
8788   SDValue RHS = Op.getOperand(2);
8789 
8790   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8791 
8792   const APFloat K0Val(BitsToFloat(0x6f800000));
8793   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8794 
8795   const APFloat K1Val(BitsToFloat(0x2f800000));
8796   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8797 
8798   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8799 
8800   EVT SetCCVT =
8801     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8802 
8803   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8804 
8805   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8806 
8807   // TODO: Should this propagate fast-math-flags?
8808   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8809 
8810   // rcp does not support denormals.
8811   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8812 
8813   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8814 
8815   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8816 }
8817 
8818 // Returns immediate value for setting the F32 denorm mode when using the
8819 // S_DENORM_MODE instruction.
8820 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8821                                     const SDLoc &SL, const GCNSubtarget *ST) {
8822   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8823   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8824                                 ? FP_DENORM_FLUSH_NONE
8825                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8826 
8827   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8828   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8829 }
8830 
8831 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8832   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8833     return FastLowered;
8834 
8835   // The selection matcher assumes anything with a chain selecting to a
8836   // mayRaiseFPException machine instruction. Since we're introducing a chain
8837   // here, we need to explicitly report nofpexcept for the regular fdiv
8838   // lowering.
8839   SDNodeFlags Flags = Op->getFlags();
8840   Flags.setNoFPExcept(true);
8841 
8842   SDLoc SL(Op);
8843   SDValue LHS = Op.getOperand(0);
8844   SDValue RHS = Op.getOperand(1);
8845 
8846   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8847 
8848   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8849 
8850   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8851                                           {RHS, RHS, LHS}, Flags);
8852   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8853                                         {LHS, RHS, LHS}, Flags);
8854 
8855   // Denominator is scaled to not be denormal, so using rcp is ok.
8856   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8857                                   DenominatorScaled, Flags);
8858   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8859                                      DenominatorScaled, Flags);
8860 
8861   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8862                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8863                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8864   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8865 
8866   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8867 
8868   if (!HasFP32Denormals) {
8869     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8870     // lowering. The chain dependence is insufficient, and we need glue. We do
8871     // not need the glue variants in a strictfp function.
8872 
8873     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8874 
8875     SDNode *EnableDenorm;
8876     if (Subtarget->hasDenormModeInst()) {
8877       const SDValue EnableDenormValue =
8878           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8879 
8880       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8881                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8882     } else {
8883       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8884                                                         SL, MVT::i32);
8885       EnableDenorm =
8886           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8887                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8888     }
8889 
8890     SDValue Ops[3] = {
8891       NegDivScale0,
8892       SDValue(EnableDenorm, 0),
8893       SDValue(EnableDenorm, 1)
8894     };
8895 
8896     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8897   }
8898 
8899   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8900                              ApproxRcp, One, NegDivScale0, Flags);
8901 
8902   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8903                              ApproxRcp, Fma0, Flags);
8904 
8905   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8906                            Fma1, Fma1, Flags);
8907 
8908   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8909                              NumeratorScaled, Mul, Flags);
8910 
8911   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8912                              Fma2, Fma1, Mul, Fma2, Flags);
8913 
8914   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8915                              NumeratorScaled, Fma3, Flags);
8916 
8917   if (!HasFP32Denormals) {
8918     SDNode *DisableDenorm;
8919     if (Subtarget->hasDenormModeInst()) {
8920       const SDValue DisableDenormValue =
8921           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8922 
8923       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8924                                   Fma4.getValue(1), DisableDenormValue,
8925                                   Fma4.getValue(2)).getNode();
8926     } else {
8927       const SDValue DisableDenormValue =
8928           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8929 
8930       DisableDenorm = DAG.getMachineNode(
8931           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8932           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8933     }
8934 
8935     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8936                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8937     DAG.setRoot(OutputChain);
8938   }
8939 
8940   SDValue Scale = NumeratorScaled.getValue(1);
8941   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8942                              {Fma4, Fma1, Fma3, Scale}, Flags);
8943 
8944   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8945 }
8946 
8947 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8948   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8949     return FastLowered;
8950 
8951   SDLoc SL(Op);
8952   SDValue X = Op.getOperand(0);
8953   SDValue Y = Op.getOperand(1);
8954 
8955   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8956 
8957   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8958 
8959   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8960 
8961   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8962 
8963   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8964 
8965   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8966 
8967   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8968 
8969   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8970 
8971   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8972 
8973   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8974   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8975 
8976   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8977                              NegDivScale0, Mul, DivScale1);
8978 
8979   SDValue Scale;
8980 
8981   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8982     // Workaround a hardware bug on SI where the condition output from div_scale
8983     // is not usable.
8984 
8985     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8986 
8987     // Figure out if the scale to use for div_fmas.
8988     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8989     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8990     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8991     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8992 
8993     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8994     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8995 
8996     SDValue Scale0Hi
8997       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8998     SDValue Scale1Hi
8999       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
9000 
9001     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
9002     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
9003     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9004   } else {
9005     Scale = DivScale1.getValue(1);
9006   }
9007 
9008   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9009                              Fma4, Fma3, Mul, Scale);
9010 
9011   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9012 }
9013 
9014 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9015   EVT VT = Op.getValueType();
9016 
9017   if (VT == MVT::f32)
9018     return LowerFDIV32(Op, DAG);
9019 
9020   if (VT == MVT::f64)
9021     return LowerFDIV64(Op, DAG);
9022 
9023   if (VT == MVT::f16)
9024     return LowerFDIV16(Op, DAG);
9025 
9026   llvm_unreachable("Unexpected type for fdiv");
9027 }
9028 
9029 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9030   SDLoc DL(Op);
9031   StoreSDNode *Store = cast<StoreSDNode>(Op);
9032   EVT VT = Store->getMemoryVT();
9033 
9034   if (VT == MVT::i1) {
9035     return DAG.getTruncStore(Store->getChain(), DL,
9036        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9037        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9038   }
9039 
9040   assert(VT.isVector() &&
9041          Store->getValue().getValueType().getScalarType() == MVT::i32);
9042 
9043   unsigned AS = Store->getAddressSpace();
9044   if (Subtarget->hasLDSMisalignedBug() &&
9045       AS == AMDGPUAS::FLAT_ADDRESS &&
9046       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9047     return SplitVectorStore(Op, DAG);
9048   }
9049 
9050   MachineFunction &MF = DAG.getMachineFunction();
9051   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9052   // If there is a possibility that flat instruction access scratch memory
9053   // then we need to use the same legalization rules we use for private.
9054   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9055       !Subtarget->hasMultiDwordFlatScratchAddressing())
9056     AS = MFI->hasFlatScratchInit() ?
9057          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9058 
9059   unsigned NumElements = VT.getVectorNumElements();
9060   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9061       AS == AMDGPUAS::FLAT_ADDRESS) {
9062     if (NumElements > 4)
9063       return SplitVectorStore(Op, DAG);
9064     // v3 stores not supported on SI.
9065     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9066       return SplitVectorStore(Op, DAG);
9067 
9068     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9069                                         VT, *Store->getMemOperand()))
9070       return expandUnalignedStore(Store, DAG);
9071 
9072     return SDValue();
9073   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9074     switch (Subtarget->getMaxPrivateElementSize()) {
9075     case 4:
9076       return scalarizeVectorStore(Store, DAG);
9077     case 8:
9078       if (NumElements > 2)
9079         return SplitVectorStore(Op, DAG);
9080       return SDValue();
9081     case 16:
9082       if (NumElements > 4 ||
9083           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9084         return SplitVectorStore(Op, DAG);
9085       return SDValue();
9086     default:
9087       llvm_unreachable("unsupported private_element_size");
9088     }
9089   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9090     bool Fast = false;
9091     auto Flags = Store->getMemOperand()->getFlags();
9092     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9093                                            Store->getAlign(), Flags, &Fast) &&
9094         Fast)
9095       return SDValue();
9096 
9097     if (VT.isVector())
9098       return SplitVectorStore(Op, DAG);
9099 
9100     return expandUnalignedStore(Store, DAG);
9101   }
9102 
9103   // Probably an invalid store. If so we'll end up emitting a selection error.
9104   return SDValue();
9105 }
9106 
9107 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9108   SDLoc DL(Op);
9109   EVT VT = Op.getValueType();
9110   SDValue Arg = Op.getOperand(0);
9111   SDValue TrigVal;
9112 
9113   // Propagate fast-math flags so that the multiply we introduce can be folded
9114   // if Arg is already the result of a multiply by constant.
9115   auto Flags = Op->getFlags();
9116 
9117   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9118 
9119   if (Subtarget->hasTrigReducedRange()) {
9120     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9121     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9122   } else {
9123     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9124   }
9125 
9126   switch (Op.getOpcode()) {
9127   case ISD::FCOS:
9128     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9129   case ISD::FSIN:
9130     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9131   default:
9132     llvm_unreachable("Wrong trig opcode");
9133   }
9134 }
9135 
9136 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9137   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9138   assert(AtomicNode->isCompareAndSwap());
9139   unsigned AS = AtomicNode->getAddressSpace();
9140 
9141   // No custom lowering required for local address space
9142   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9143     return Op;
9144 
9145   // Non-local address space requires custom lowering for atomic compare
9146   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9147   SDLoc DL(Op);
9148   SDValue ChainIn = Op.getOperand(0);
9149   SDValue Addr = Op.getOperand(1);
9150   SDValue Old = Op.getOperand(2);
9151   SDValue New = Op.getOperand(3);
9152   EVT VT = Op.getValueType();
9153   MVT SimpleVT = VT.getSimpleVT();
9154   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9155 
9156   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9157   SDValue Ops[] = { ChainIn, Addr, NewOld };
9158 
9159   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9160                                  Ops, VT, AtomicNode->getMemOperand());
9161 }
9162 
9163 //===----------------------------------------------------------------------===//
9164 // Custom DAG optimizations
9165 //===----------------------------------------------------------------------===//
9166 
9167 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9168                                                      DAGCombinerInfo &DCI) const {
9169   EVT VT = N->getValueType(0);
9170   EVT ScalarVT = VT.getScalarType();
9171   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9172     return SDValue();
9173 
9174   SelectionDAG &DAG = DCI.DAG;
9175   SDLoc DL(N);
9176 
9177   SDValue Src = N->getOperand(0);
9178   EVT SrcVT = Src.getValueType();
9179 
9180   // TODO: We could try to match extracting the higher bytes, which would be
9181   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9182   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9183   // about in practice.
9184   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9185     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9186       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9187       DCI.AddToWorklist(Cvt.getNode());
9188 
9189       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9190       if (ScalarVT != MVT::f32) {
9191         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9192                           DAG.getTargetConstant(0, DL, MVT::i32));
9193       }
9194       return Cvt;
9195     }
9196   }
9197 
9198   return SDValue();
9199 }
9200 
9201 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9202 
9203 // This is a variant of
9204 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9205 //
9206 // The normal DAG combiner will do this, but only if the add has one use since
9207 // that would increase the number of instructions.
9208 //
9209 // This prevents us from seeing a constant offset that can be folded into a
9210 // memory instruction's addressing mode. If we know the resulting add offset of
9211 // a pointer can be folded into an addressing offset, we can replace the pointer
9212 // operand with the add of new constant offset. This eliminates one of the uses,
9213 // and may allow the remaining use to also be simplified.
9214 //
9215 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9216                                                unsigned AddrSpace,
9217                                                EVT MemVT,
9218                                                DAGCombinerInfo &DCI) const {
9219   SDValue N0 = N->getOperand(0);
9220   SDValue N1 = N->getOperand(1);
9221 
9222   // We only do this to handle cases where it's profitable when there are
9223   // multiple uses of the add, so defer to the standard combine.
9224   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9225       N0->hasOneUse())
9226     return SDValue();
9227 
9228   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9229   if (!CN1)
9230     return SDValue();
9231 
9232   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9233   if (!CAdd)
9234     return SDValue();
9235 
9236   // If the resulting offset is too large, we can't fold it into the addressing
9237   // mode offset.
9238   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9239   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9240 
9241   AddrMode AM;
9242   AM.HasBaseReg = true;
9243   AM.BaseOffs = Offset.getSExtValue();
9244   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9245     return SDValue();
9246 
9247   SelectionDAG &DAG = DCI.DAG;
9248   SDLoc SL(N);
9249   EVT VT = N->getValueType(0);
9250 
9251   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9252   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9253 
9254   SDNodeFlags Flags;
9255   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9256                           (N0.getOpcode() == ISD::OR ||
9257                            N0->getFlags().hasNoUnsignedWrap()));
9258 
9259   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9260 }
9261 
9262 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9263 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9264 /// specific intrinsic, but they all place the pointer operand first.
9265 static unsigned getBasePtrIndex(const MemSDNode *N) {
9266   switch (N->getOpcode()) {
9267   case ISD::STORE:
9268   case ISD::INTRINSIC_W_CHAIN:
9269   case ISD::INTRINSIC_VOID:
9270     return 2;
9271   default:
9272     return 1;
9273   }
9274 }
9275 
9276 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9277                                                   DAGCombinerInfo &DCI) const {
9278   SelectionDAG &DAG = DCI.DAG;
9279   SDLoc SL(N);
9280 
9281   unsigned PtrIdx = getBasePtrIndex(N);
9282   SDValue Ptr = N->getOperand(PtrIdx);
9283 
9284   // TODO: We could also do this for multiplies.
9285   if (Ptr.getOpcode() == ISD::SHL) {
9286     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9287                                           N->getMemoryVT(), DCI);
9288     if (NewPtr) {
9289       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9290 
9291       NewOps[PtrIdx] = NewPtr;
9292       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9293     }
9294   }
9295 
9296   return SDValue();
9297 }
9298 
9299 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9300   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9301          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9302          (Opc == ISD::XOR && Val == 0);
9303 }
9304 
9305 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9306 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9307 // integer combine opportunities since most 64-bit operations are decomposed
9308 // this way.  TODO: We won't want this for SALU especially if it is an inline
9309 // immediate.
9310 SDValue SITargetLowering::splitBinaryBitConstantOp(
9311   DAGCombinerInfo &DCI,
9312   const SDLoc &SL,
9313   unsigned Opc, SDValue LHS,
9314   const ConstantSDNode *CRHS) const {
9315   uint64_t Val = CRHS->getZExtValue();
9316   uint32_t ValLo = Lo_32(Val);
9317   uint32_t ValHi = Hi_32(Val);
9318   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9319 
9320     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9321          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9322         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9323     // If we need to materialize a 64-bit immediate, it will be split up later
9324     // anyway. Avoid creating the harder to understand 64-bit immediate
9325     // materialization.
9326     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9327   }
9328 
9329   return SDValue();
9330 }
9331 
9332 // Returns true if argument is a boolean value which is not serialized into
9333 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9334 static bool isBoolSGPR(SDValue V) {
9335   if (V.getValueType() != MVT::i1)
9336     return false;
9337   switch (V.getOpcode()) {
9338   default:
9339     break;
9340   case ISD::SETCC:
9341   case AMDGPUISD::FP_CLASS:
9342     return true;
9343   case ISD::AND:
9344   case ISD::OR:
9345   case ISD::XOR:
9346     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9347   }
9348   return false;
9349 }
9350 
9351 // If a constant has all zeroes or all ones within each byte return it.
9352 // Otherwise return 0.
9353 static uint32_t getConstantPermuteMask(uint32_t C) {
9354   // 0xff for any zero byte in the mask
9355   uint32_t ZeroByteMask = 0;
9356   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9357   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9358   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9359   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9360   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9361   if ((NonZeroByteMask & C) != NonZeroByteMask)
9362     return 0; // Partial bytes selected.
9363   return C;
9364 }
9365 
9366 // Check if a node selects whole bytes from its operand 0 starting at a byte
9367 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9368 // or -1 if not succeeded.
9369 // Note byte select encoding:
9370 // value 0-3 selects corresponding source byte;
9371 // value 0xc selects zero;
9372 // value 0xff selects 0xff.
9373 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9374   assert(V.getValueSizeInBits() == 32);
9375 
9376   if (V.getNumOperands() != 2)
9377     return ~0;
9378 
9379   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9380   if (!N1)
9381     return ~0;
9382 
9383   uint32_t C = N1->getZExtValue();
9384 
9385   switch (V.getOpcode()) {
9386   default:
9387     break;
9388   case ISD::AND:
9389     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9390       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9391     }
9392     break;
9393 
9394   case ISD::OR:
9395     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9396       return (0x03020100 & ~ConstMask) | ConstMask;
9397     }
9398     break;
9399 
9400   case ISD::SHL:
9401     if (C % 8)
9402       return ~0;
9403 
9404     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9405 
9406   case ISD::SRL:
9407     if (C % 8)
9408       return ~0;
9409 
9410     return uint32_t(0x0c0c0c0c03020100ull >> C);
9411   }
9412 
9413   return ~0;
9414 }
9415 
9416 SDValue SITargetLowering::performAndCombine(SDNode *N,
9417                                             DAGCombinerInfo &DCI) const {
9418   if (DCI.isBeforeLegalize())
9419     return SDValue();
9420 
9421   SelectionDAG &DAG = DCI.DAG;
9422   EVT VT = N->getValueType(0);
9423   SDValue LHS = N->getOperand(0);
9424   SDValue RHS = N->getOperand(1);
9425 
9426 
9427   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9428   if (VT == MVT::i64 && CRHS) {
9429     if (SDValue Split
9430         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9431       return Split;
9432   }
9433 
9434   if (CRHS && VT == MVT::i32) {
9435     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9436     // nb = number of trailing zeroes in mask
9437     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9438     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9439     uint64_t Mask = CRHS->getZExtValue();
9440     unsigned Bits = countPopulation(Mask);
9441     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9442         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9443       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9444         unsigned Shift = CShift->getZExtValue();
9445         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9446         unsigned Offset = NB + Shift;
9447         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9448           SDLoc SL(N);
9449           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9450                                     LHS->getOperand(0),
9451                                     DAG.getConstant(Offset, SL, MVT::i32),
9452                                     DAG.getConstant(Bits, SL, MVT::i32));
9453           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9454           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9455                                     DAG.getValueType(NarrowVT));
9456           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9457                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9458           return Shl;
9459         }
9460       }
9461     }
9462 
9463     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9464     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9465         isa<ConstantSDNode>(LHS.getOperand(2))) {
9466       uint32_t Sel = getConstantPermuteMask(Mask);
9467       if (!Sel)
9468         return SDValue();
9469 
9470       // Select 0xc for all zero bytes
9471       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9472       SDLoc DL(N);
9473       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9474                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9475     }
9476   }
9477 
9478   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9479   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9480   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9481     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9482     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9483 
9484     SDValue X = LHS.getOperand(0);
9485     SDValue Y = RHS.getOperand(0);
9486     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9487       return SDValue();
9488 
9489     if (LCC == ISD::SETO) {
9490       if (X != LHS.getOperand(1))
9491         return SDValue();
9492 
9493       if (RCC == ISD::SETUNE) {
9494         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9495         if (!C1 || !C1->isInfinity() || C1->isNegative())
9496           return SDValue();
9497 
9498         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9499                               SIInstrFlags::N_SUBNORMAL |
9500                               SIInstrFlags::N_ZERO |
9501                               SIInstrFlags::P_ZERO |
9502                               SIInstrFlags::P_SUBNORMAL |
9503                               SIInstrFlags::P_NORMAL;
9504 
9505         static_assert(((~(SIInstrFlags::S_NAN |
9506                           SIInstrFlags::Q_NAN |
9507                           SIInstrFlags::N_INFINITY |
9508                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9509                       "mask not equal");
9510 
9511         SDLoc DL(N);
9512         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9513                            X, DAG.getConstant(Mask, DL, MVT::i32));
9514       }
9515     }
9516   }
9517 
9518   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9519     std::swap(LHS, RHS);
9520 
9521   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9522       RHS.hasOneUse()) {
9523     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9524     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9525     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9526     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9527     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9528         (RHS.getOperand(0) == LHS.getOperand(0) &&
9529          LHS.getOperand(0) == LHS.getOperand(1))) {
9530       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9531       unsigned NewMask = LCC == ISD::SETO ?
9532         Mask->getZExtValue() & ~OrdMask :
9533         Mask->getZExtValue() & OrdMask;
9534 
9535       SDLoc DL(N);
9536       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9537                          DAG.getConstant(NewMask, DL, MVT::i32));
9538     }
9539   }
9540 
9541   if (VT == MVT::i32 &&
9542       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9543     // and x, (sext cc from i1) => select cc, x, 0
9544     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9545       std::swap(LHS, RHS);
9546     if (isBoolSGPR(RHS.getOperand(0)))
9547       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9548                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9549   }
9550 
9551   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9552   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9553   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9554       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9555     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9556     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9557     if (LHSMask != ~0u && RHSMask != ~0u) {
9558       // Canonicalize the expression in an attempt to have fewer unique masks
9559       // and therefore fewer registers used to hold the masks.
9560       if (LHSMask > RHSMask) {
9561         std::swap(LHSMask, RHSMask);
9562         std::swap(LHS, RHS);
9563       }
9564 
9565       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9566       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9567       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9568       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9569 
9570       // Check of we need to combine values from two sources within a byte.
9571       if (!(LHSUsedLanes & RHSUsedLanes) &&
9572           // If we select high and lower word keep it for SDWA.
9573           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9574           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9575         // Each byte in each mask is either selector mask 0-3, or has higher
9576         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9577         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9578         // mask which is not 0xff wins. By anding both masks we have a correct
9579         // result except that 0x0c shall be corrected to give 0x0c only.
9580         uint32_t Mask = LHSMask & RHSMask;
9581         for (unsigned I = 0; I < 32; I += 8) {
9582           uint32_t ByteSel = 0xff << I;
9583           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9584             Mask &= (0x0c << I) & 0xffffffff;
9585         }
9586 
9587         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9588         // or 0x0c.
9589         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
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   return SDValue();
9600 }
9601 
9602 SDValue SITargetLowering::performOrCombine(SDNode *N,
9603                                            DAGCombinerInfo &DCI) const {
9604   SelectionDAG &DAG = DCI.DAG;
9605   SDValue LHS = N->getOperand(0);
9606   SDValue RHS = N->getOperand(1);
9607 
9608   EVT VT = N->getValueType(0);
9609   if (VT == MVT::i1) {
9610     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9611     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9612         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9613       SDValue Src = LHS.getOperand(0);
9614       if (Src != RHS.getOperand(0))
9615         return SDValue();
9616 
9617       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9618       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9619       if (!CLHS || !CRHS)
9620         return SDValue();
9621 
9622       // Only 10 bits are used.
9623       static const uint32_t MaxMask = 0x3ff;
9624 
9625       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9626       SDLoc DL(N);
9627       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9628                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9629     }
9630 
9631     return SDValue();
9632   }
9633 
9634   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9635   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9636       LHS.getOpcode() == AMDGPUISD::PERM &&
9637       isa<ConstantSDNode>(LHS.getOperand(2))) {
9638     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9639     if (!Sel)
9640       return SDValue();
9641 
9642     Sel |= LHS.getConstantOperandVal(2);
9643     SDLoc DL(N);
9644     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9645                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9646   }
9647 
9648   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9649   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9650   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9651       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9652     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9653     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9654     if (LHSMask != ~0u && RHSMask != ~0u) {
9655       // Canonicalize the expression in an attempt to have fewer unique masks
9656       // and therefore fewer registers used to hold the masks.
9657       if (LHSMask > RHSMask) {
9658         std::swap(LHSMask, RHSMask);
9659         std::swap(LHS, RHS);
9660       }
9661 
9662       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9663       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9664       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9665       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9666 
9667       // Check of we need to combine values from two sources within a byte.
9668       if (!(LHSUsedLanes & RHSUsedLanes) &&
9669           // If we select high and lower word keep it for SDWA.
9670           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9671           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9672         // Kill zero bytes selected by other mask. Zero value is 0xc.
9673         LHSMask &= ~RHSUsedLanes;
9674         RHSMask &= ~LHSUsedLanes;
9675         // Add 4 to each active LHS lane
9676         LHSMask |= LHSUsedLanes & 0x04040404;
9677         // Combine masks
9678         uint32_t Sel = LHSMask | RHSMask;
9679         SDLoc DL(N);
9680 
9681         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9682                            LHS.getOperand(0), RHS.getOperand(0),
9683                            DAG.getConstant(Sel, DL, MVT::i32));
9684       }
9685     }
9686   }
9687 
9688   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9689     return SDValue();
9690 
9691   // TODO: This could be a generic combine with a predicate for extracting the
9692   // high half of an integer being free.
9693 
9694   // (or i64:x, (zero_extend i32:y)) ->
9695   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9696   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9697       RHS.getOpcode() != ISD::ZERO_EXTEND)
9698     std::swap(LHS, RHS);
9699 
9700   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9701     SDValue ExtSrc = RHS.getOperand(0);
9702     EVT SrcVT = ExtSrc.getValueType();
9703     if (SrcVT == MVT::i32) {
9704       SDLoc SL(N);
9705       SDValue LowLHS, HiBits;
9706       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9707       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9708 
9709       DCI.AddToWorklist(LowOr.getNode());
9710       DCI.AddToWorklist(HiBits.getNode());
9711 
9712       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9713                                 LowOr, HiBits);
9714       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9715     }
9716   }
9717 
9718   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9719   if (CRHS) {
9720     if (SDValue Split
9721           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9722                                      N->getOperand(0), CRHS))
9723       return Split;
9724   }
9725 
9726   return SDValue();
9727 }
9728 
9729 SDValue SITargetLowering::performXorCombine(SDNode *N,
9730                                             DAGCombinerInfo &DCI) const {
9731   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9732     return RV;
9733 
9734   EVT VT = N->getValueType(0);
9735   if (VT != MVT::i64)
9736     return SDValue();
9737 
9738   SDValue LHS = N->getOperand(0);
9739   SDValue RHS = N->getOperand(1);
9740 
9741   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9742   if (CRHS) {
9743     if (SDValue Split
9744           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9745       return Split;
9746   }
9747 
9748   return SDValue();
9749 }
9750 
9751 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9752                                                    DAGCombinerInfo &DCI) const {
9753   if (!Subtarget->has16BitInsts() ||
9754       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9755     return SDValue();
9756 
9757   EVT VT = N->getValueType(0);
9758   if (VT != MVT::i32)
9759     return SDValue();
9760 
9761   SDValue Src = N->getOperand(0);
9762   if (Src.getValueType() != MVT::i16)
9763     return SDValue();
9764 
9765   return SDValue();
9766 }
9767 
9768 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9769                                                         DAGCombinerInfo &DCI)
9770                                                         const {
9771   SDValue Src = N->getOperand(0);
9772   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9773 
9774   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9775       VTSign->getVT() == MVT::i8) ||
9776       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9777       VTSign->getVT() == MVT::i16)) &&
9778       Src.hasOneUse()) {
9779     auto *M = cast<MemSDNode>(Src);
9780     SDValue Ops[] = {
9781       Src.getOperand(0), // Chain
9782       Src.getOperand(1), // rsrc
9783       Src.getOperand(2), // vindex
9784       Src.getOperand(3), // voffset
9785       Src.getOperand(4), // soffset
9786       Src.getOperand(5), // offset
9787       Src.getOperand(6),
9788       Src.getOperand(7)
9789     };
9790     // replace with BUFFER_LOAD_BYTE/SHORT
9791     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9792                                          Src.getOperand(0).getValueType());
9793     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9794                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9795     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9796                                                           ResList,
9797                                                           Ops, M->getMemoryVT(),
9798                                                           M->getMemOperand());
9799     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9800                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9801   }
9802   return SDValue();
9803 }
9804 
9805 SDValue SITargetLowering::performClassCombine(SDNode *N,
9806                                               DAGCombinerInfo &DCI) const {
9807   SelectionDAG &DAG = DCI.DAG;
9808   SDValue Mask = N->getOperand(1);
9809 
9810   // fp_class x, 0 -> false
9811   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9812     if (CMask->isZero())
9813       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9814   }
9815 
9816   if (N->getOperand(0).isUndef())
9817     return DAG.getUNDEF(MVT::i1);
9818 
9819   return SDValue();
9820 }
9821 
9822 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9823                                             DAGCombinerInfo &DCI) const {
9824   EVT VT = N->getValueType(0);
9825   SDValue N0 = N->getOperand(0);
9826 
9827   if (N0.isUndef())
9828     return N0;
9829 
9830   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9831                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9832     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9833                            N->getFlags());
9834   }
9835 
9836   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9837     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9838                            N0.getOperand(0), N->getFlags());
9839   }
9840 
9841   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9842 }
9843 
9844 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9845                                        unsigned MaxDepth) const {
9846   unsigned Opcode = Op.getOpcode();
9847   if (Opcode == ISD::FCANONICALIZE)
9848     return true;
9849 
9850   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9851     auto F = CFP->getValueAPF();
9852     if (F.isNaN() && F.isSignaling())
9853       return false;
9854     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9855   }
9856 
9857   // If source is a result of another standard FP operation it is already in
9858   // canonical form.
9859   if (MaxDepth == 0)
9860     return false;
9861 
9862   switch (Opcode) {
9863   // These will flush denorms if required.
9864   case ISD::FADD:
9865   case ISD::FSUB:
9866   case ISD::FMUL:
9867   case ISD::FCEIL:
9868   case ISD::FFLOOR:
9869   case ISD::FMA:
9870   case ISD::FMAD:
9871   case ISD::FSQRT:
9872   case ISD::FDIV:
9873   case ISD::FREM:
9874   case ISD::FP_ROUND:
9875   case ISD::FP_EXTEND:
9876   case AMDGPUISD::FMUL_LEGACY:
9877   case AMDGPUISD::FMAD_FTZ:
9878   case AMDGPUISD::RCP:
9879   case AMDGPUISD::RSQ:
9880   case AMDGPUISD::RSQ_CLAMP:
9881   case AMDGPUISD::RCP_LEGACY:
9882   case AMDGPUISD::RCP_IFLAG:
9883   case AMDGPUISD::DIV_SCALE:
9884   case AMDGPUISD::DIV_FMAS:
9885   case AMDGPUISD::DIV_FIXUP:
9886   case AMDGPUISD::FRACT:
9887   case AMDGPUISD::LDEXP:
9888   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9889   case AMDGPUISD::CVT_F32_UBYTE0:
9890   case AMDGPUISD::CVT_F32_UBYTE1:
9891   case AMDGPUISD::CVT_F32_UBYTE2:
9892   case AMDGPUISD::CVT_F32_UBYTE3:
9893     return true;
9894 
9895   // It can/will be lowered or combined as a bit operation.
9896   // Need to check their input recursively to handle.
9897   case ISD::FNEG:
9898   case ISD::FABS:
9899   case ISD::FCOPYSIGN:
9900     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9901 
9902   case ISD::FSIN:
9903   case ISD::FCOS:
9904   case ISD::FSINCOS:
9905     return Op.getValueType().getScalarType() != MVT::f16;
9906 
9907   case ISD::FMINNUM:
9908   case ISD::FMAXNUM:
9909   case ISD::FMINNUM_IEEE:
9910   case ISD::FMAXNUM_IEEE:
9911   case AMDGPUISD::CLAMP:
9912   case AMDGPUISD::FMED3:
9913   case AMDGPUISD::FMAX3:
9914   case AMDGPUISD::FMIN3: {
9915     // FIXME: Shouldn't treat the generic operations different based these.
9916     // However, we aren't really required to flush the result from
9917     // minnum/maxnum..
9918 
9919     // snans will be quieted, so we only need to worry about denormals.
9920     if (Subtarget->supportsMinMaxDenormModes() ||
9921         denormalsEnabledForType(DAG, Op.getValueType()))
9922       return true;
9923 
9924     // Flushing may be required.
9925     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9926     // targets need to check their input recursively.
9927 
9928     // FIXME: Does this apply with clamp? It's implemented with max.
9929     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9930       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9931         return false;
9932     }
9933 
9934     return true;
9935   }
9936   case ISD::SELECT: {
9937     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9938            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9939   }
9940   case ISD::BUILD_VECTOR: {
9941     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9942       SDValue SrcOp = Op.getOperand(i);
9943       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9944         return false;
9945     }
9946 
9947     return true;
9948   }
9949   case ISD::EXTRACT_VECTOR_ELT:
9950   case ISD::EXTRACT_SUBVECTOR: {
9951     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9952   }
9953   case ISD::INSERT_VECTOR_ELT: {
9954     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9955            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9956   }
9957   case ISD::UNDEF:
9958     // Could be anything.
9959     return false;
9960 
9961   case ISD::BITCAST:
9962     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9963   case ISD::TRUNCATE: {
9964     // Hack round the mess we make when legalizing extract_vector_elt
9965     if (Op.getValueType() == MVT::i16) {
9966       SDValue TruncSrc = Op.getOperand(0);
9967       if (TruncSrc.getValueType() == MVT::i32 &&
9968           TruncSrc.getOpcode() == ISD::BITCAST &&
9969           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9970         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9971       }
9972     }
9973     return false;
9974   }
9975   case ISD::INTRINSIC_WO_CHAIN: {
9976     unsigned IntrinsicID
9977       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9978     // TODO: Handle more intrinsics
9979     switch (IntrinsicID) {
9980     case Intrinsic::amdgcn_cvt_pkrtz:
9981     case Intrinsic::amdgcn_cubeid:
9982     case Intrinsic::amdgcn_frexp_mant:
9983     case Intrinsic::amdgcn_fdot2:
9984     case Intrinsic::amdgcn_rcp:
9985     case Intrinsic::amdgcn_rsq:
9986     case Intrinsic::amdgcn_rsq_clamp:
9987     case Intrinsic::amdgcn_rcp_legacy:
9988     case Intrinsic::amdgcn_rsq_legacy:
9989     case Intrinsic::amdgcn_trig_preop:
9990       return true;
9991     default:
9992       break;
9993     }
9994 
9995     LLVM_FALLTHROUGH;
9996   }
9997   default:
9998     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9999            DAG.isKnownNeverSNaN(Op);
10000   }
10001 
10002   llvm_unreachable("invalid operation");
10003 }
10004 
10005 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10006                                        unsigned MaxDepth) const {
10007   MachineRegisterInfo &MRI = MF.getRegInfo();
10008   MachineInstr *MI = MRI.getVRegDef(Reg);
10009   unsigned Opcode = MI->getOpcode();
10010 
10011   if (Opcode == AMDGPU::G_FCANONICALIZE)
10012     return true;
10013 
10014   Optional<FPValueAndVReg> FCR;
10015   // Constant splat (can be padded with undef) or scalar constant.
10016   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10017     if (FCR->Value.isSignaling())
10018       return false;
10019     return !FCR->Value.isDenormal() ||
10020            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10021   }
10022 
10023   if (MaxDepth == 0)
10024     return false;
10025 
10026   switch (Opcode) {
10027   case AMDGPU::G_FMINNUM_IEEE:
10028   case AMDGPU::G_FMAXNUM_IEEE: {
10029     if (Subtarget->supportsMinMaxDenormModes() ||
10030         denormalsEnabledForType(MRI.getType(Reg), MF))
10031       return true;
10032     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10033       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10034         return false;
10035     return true;
10036   }
10037   default:
10038     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10039            isKnownNeverSNaN(Reg, MRI);
10040   }
10041 
10042   llvm_unreachable("invalid operation");
10043 }
10044 
10045 // Constant fold canonicalize.
10046 SDValue SITargetLowering::getCanonicalConstantFP(
10047   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10048   // Flush denormals to 0 if not enabled.
10049   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10050     return DAG.getConstantFP(0.0, SL, VT);
10051 
10052   if (C.isNaN()) {
10053     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10054     if (C.isSignaling()) {
10055       // Quiet a signaling NaN.
10056       // FIXME: Is this supposed to preserve payload bits?
10057       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10058     }
10059 
10060     // Make sure it is the canonical NaN bitpattern.
10061     //
10062     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10063     // immediate?
10064     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10065       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10066   }
10067 
10068   // Already canonical.
10069   return DAG.getConstantFP(C, SL, VT);
10070 }
10071 
10072 static bool vectorEltWillFoldAway(SDValue Op) {
10073   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10074 }
10075 
10076 SDValue SITargetLowering::performFCanonicalizeCombine(
10077   SDNode *N,
10078   DAGCombinerInfo &DCI) const {
10079   SelectionDAG &DAG = DCI.DAG;
10080   SDValue N0 = N->getOperand(0);
10081   EVT VT = N->getValueType(0);
10082 
10083   // fcanonicalize undef -> qnan
10084   if (N0.isUndef()) {
10085     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10086     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10087   }
10088 
10089   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10090     EVT VT = N->getValueType(0);
10091     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10092   }
10093 
10094   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10095   //                                                   (fcanonicalize k)
10096   //
10097   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10098 
10099   // TODO: This could be better with wider vectors that will be split to v2f16,
10100   // and to consider uses since there aren't that many packed operations.
10101   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10102       isTypeLegal(MVT::v2f16)) {
10103     SDLoc SL(N);
10104     SDValue NewElts[2];
10105     SDValue Lo = N0.getOperand(0);
10106     SDValue Hi = N0.getOperand(1);
10107     EVT EltVT = Lo.getValueType();
10108 
10109     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10110       for (unsigned I = 0; I != 2; ++I) {
10111         SDValue Op = N0.getOperand(I);
10112         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10113           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10114                                               CFP->getValueAPF());
10115         } else if (Op.isUndef()) {
10116           // Handled below based on what the other operand is.
10117           NewElts[I] = Op;
10118         } else {
10119           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10120         }
10121       }
10122 
10123       // If one half is undef, and one is constant, prefer a splat vector rather
10124       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10125       // cheaper to use and may be free with a packed operation.
10126       if (NewElts[0].isUndef()) {
10127         if (isa<ConstantFPSDNode>(NewElts[1]))
10128           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10129             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10130       }
10131 
10132       if (NewElts[1].isUndef()) {
10133         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10134           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10135       }
10136 
10137       return DAG.getBuildVector(VT, SL, NewElts);
10138     }
10139   }
10140 
10141   unsigned SrcOpc = N0.getOpcode();
10142 
10143   // If it's free to do so, push canonicalizes further up the source, which may
10144   // find a canonical source.
10145   //
10146   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10147   // sNaNs.
10148   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10149     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10150     if (CRHS && N0.hasOneUse()) {
10151       SDLoc SL(N);
10152       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10153                                    N0.getOperand(0));
10154       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10155       DCI.AddToWorklist(Canon0.getNode());
10156 
10157       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10158     }
10159   }
10160 
10161   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10162 }
10163 
10164 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10165   switch (Opc) {
10166   case ISD::FMAXNUM:
10167   case ISD::FMAXNUM_IEEE:
10168     return AMDGPUISD::FMAX3;
10169   case ISD::SMAX:
10170     return AMDGPUISD::SMAX3;
10171   case ISD::UMAX:
10172     return AMDGPUISD::UMAX3;
10173   case ISD::FMINNUM:
10174   case ISD::FMINNUM_IEEE:
10175     return AMDGPUISD::FMIN3;
10176   case ISD::SMIN:
10177     return AMDGPUISD::SMIN3;
10178   case ISD::UMIN:
10179     return AMDGPUISD::UMIN3;
10180   default:
10181     llvm_unreachable("Not a min/max opcode");
10182   }
10183 }
10184 
10185 SDValue SITargetLowering::performIntMed3ImmCombine(
10186   SelectionDAG &DAG, const SDLoc &SL,
10187   SDValue Op0, SDValue Op1, bool Signed) const {
10188   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10189   if (!K1)
10190     return SDValue();
10191 
10192   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10193   if (!K0)
10194     return SDValue();
10195 
10196   if (Signed) {
10197     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10198       return SDValue();
10199   } else {
10200     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10201       return SDValue();
10202   }
10203 
10204   EVT VT = K0->getValueType(0);
10205   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10206   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10207     return DAG.getNode(Med3Opc, SL, VT,
10208                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10209   }
10210 
10211   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10212   if (VT == MVT::i16) {
10213     MVT NVT = MVT::i32;
10214     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10215 
10216     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10217     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10218     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10219 
10220     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10221     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10222   }
10223 
10224   return SDValue();
10225 }
10226 
10227 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10228   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10229     return C;
10230 
10231   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10232     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10233       return C;
10234   }
10235 
10236   return nullptr;
10237 }
10238 
10239 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10240                                                   const SDLoc &SL,
10241                                                   SDValue Op0,
10242                                                   SDValue Op1) const {
10243   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10244   if (!K1)
10245     return SDValue();
10246 
10247   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10248   if (!K0)
10249     return SDValue();
10250 
10251   // Ordered >= (although NaN inputs should have folded away by now).
10252   if (K0->getValueAPF() > K1->getValueAPF())
10253     return SDValue();
10254 
10255   const MachineFunction &MF = DAG.getMachineFunction();
10256   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10257 
10258   // TODO: Check IEEE bit enabled?
10259   EVT VT = Op0.getValueType();
10260   if (Info->getMode().DX10Clamp) {
10261     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10262     // hardware fmed3 behavior converting to a min.
10263     // FIXME: Should this be allowing -0.0?
10264     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10265       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10266   }
10267 
10268   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10269   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10270     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10271     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10272     // then give the other result, which is different from med3 with a NaN
10273     // input.
10274     SDValue Var = Op0.getOperand(0);
10275     if (!DAG.isKnownNeverSNaN(Var))
10276       return SDValue();
10277 
10278     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10279 
10280     if ((!K0->hasOneUse() ||
10281          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10282         (!K1->hasOneUse() ||
10283          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10284       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10285                          Var, SDValue(K0, 0), SDValue(K1, 0));
10286     }
10287   }
10288 
10289   return SDValue();
10290 }
10291 
10292 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10293                                                DAGCombinerInfo &DCI) const {
10294   SelectionDAG &DAG = DCI.DAG;
10295 
10296   EVT VT = N->getValueType(0);
10297   unsigned Opc = N->getOpcode();
10298   SDValue Op0 = N->getOperand(0);
10299   SDValue Op1 = N->getOperand(1);
10300 
10301   // Only do this if the inner op has one use since this will just increases
10302   // register pressure for no benefit.
10303 
10304   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10305       !VT.isVector() &&
10306       (VT == MVT::i32 || VT == MVT::f32 ||
10307        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10308     // max(max(a, b), c) -> max3(a, b, c)
10309     // min(min(a, b), c) -> min3(a, b, c)
10310     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10311       SDLoc DL(N);
10312       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10313                          DL,
10314                          N->getValueType(0),
10315                          Op0.getOperand(0),
10316                          Op0.getOperand(1),
10317                          Op1);
10318     }
10319 
10320     // Try commuted.
10321     // max(a, max(b, c)) -> max3(a, b, c)
10322     // min(a, min(b, c)) -> min3(a, b, c)
10323     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10324       SDLoc DL(N);
10325       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10326                          DL,
10327                          N->getValueType(0),
10328                          Op0,
10329                          Op1.getOperand(0),
10330                          Op1.getOperand(1));
10331     }
10332   }
10333 
10334   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10335   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10336     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10337       return Med3;
10338   }
10339 
10340   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10341     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10342       return Med3;
10343   }
10344 
10345   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10346   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10347        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10348        (Opc == AMDGPUISD::FMIN_LEGACY &&
10349         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10350       (VT == MVT::f32 || VT == MVT::f64 ||
10351        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10352        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10353       Op0.hasOneUse()) {
10354     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10355       return Res;
10356   }
10357 
10358   return SDValue();
10359 }
10360 
10361 static bool isClampZeroToOne(SDValue A, SDValue B) {
10362   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10363     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10364       // FIXME: Should this be allowing -0.0?
10365       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10366              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10367     }
10368   }
10369 
10370   return false;
10371 }
10372 
10373 // FIXME: Should only worry about snans for version with chain.
10374 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10375                                               DAGCombinerInfo &DCI) const {
10376   EVT VT = N->getValueType(0);
10377   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10378   // NaNs. With a NaN input, the order of the operands may change the result.
10379 
10380   SelectionDAG &DAG = DCI.DAG;
10381   SDLoc SL(N);
10382 
10383   SDValue Src0 = N->getOperand(0);
10384   SDValue Src1 = N->getOperand(1);
10385   SDValue Src2 = N->getOperand(2);
10386 
10387   if (isClampZeroToOne(Src0, Src1)) {
10388     // const_a, const_b, x -> clamp is safe in all cases including signaling
10389     // nans.
10390     // FIXME: Should this be allowing -0.0?
10391     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10392   }
10393 
10394   const MachineFunction &MF = DAG.getMachineFunction();
10395   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10396 
10397   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10398   // handling no dx10-clamp?
10399   if (Info->getMode().DX10Clamp) {
10400     // If NaNs is clamped to 0, we are free to reorder the inputs.
10401 
10402     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10403       std::swap(Src0, Src1);
10404 
10405     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10406       std::swap(Src1, Src2);
10407 
10408     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10409       std::swap(Src0, Src1);
10410 
10411     if (isClampZeroToOne(Src1, Src2))
10412       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10413   }
10414 
10415   return SDValue();
10416 }
10417 
10418 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10419                                                  DAGCombinerInfo &DCI) const {
10420   SDValue Src0 = N->getOperand(0);
10421   SDValue Src1 = N->getOperand(1);
10422   if (Src0.isUndef() && Src1.isUndef())
10423     return DCI.DAG.getUNDEF(N->getValueType(0));
10424   return SDValue();
10425 }
10426 
10427 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10428 // expanded into a set of cmp/select instructions.
10429 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10430                                                 unsigned NumElem,
10431                                                 bool IsDivergentIdx) {
10432   if (UseDivergentRegisterIndexing)
10433     return false;
10434 
10435   unsigned VecSize = EltSize * NumElem;
10436 
10437   // Sub-dword vectors of size 2 dword or less have better implementation.
10438   if (VecSize <= 64 && EltSize < 32)
10439     return false;
10440 
10441   // Always expand the rest of sub-dword instructions, otherwise it will be
10442   // lowered via memory.
10443   if (EltSize < 32)
10444     return true;
10445 
10446   // Always do this if var-idx is divergent, otherwise it will become a loop.
10447   if (IsDivergentIdx)
10448     return true;
10449 
10450   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10451   unsigned NumInsts = NumElem /* Number of compares */ +
10452                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10453   return NumInsts <= 16;
10454 }
10455 
10456 static bool shouldExpandVectorDynExt(SDNode *N) {
10457   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10458   if (isa<ConstantSDNode>(Idx))
10459     return false;
10460 
10461   SDValue Vec = N->getOperand(0);
10462   EVT VecVT = Vec.getValueType();
10463   EVT EltVT = VecVT.getVectorElementType();
10464   unsigned EltSize = EltVT.getSizeInBits();
10465   unsigned NumElem = VecVT.getVectorNumElements();
10466 
10467   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10468                                                     Idx->isDivergent());
10469 }
10470 
10471 SDValue SITargetLowering::performExtractVectorEltCombine(
10472   SDNode *N, DAGCombinerInfo &DCI) const {
10473   SDValue Vec = N->getOperand(0);
10474   SelectionDAG &DAG = DCI.DAG;
10475 
10476   EVT VecVT = Vec.getValueType();
10477   EVT EltVT = VecVT.getVectorElementType();
10478 
10479   if ((Vec.getOpcode() == ISD::FNEG ||
10480        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10481     SDLoc SL(N);
10482     EVT EltVT = N->getValueType(0);
10483     SDValue Idx = N->getOperand(1);
10484     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10485                               Vec.getOperand(0), Idx);
10486     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10487   }
10488 
10489   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10490   //    =>
10491   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10492   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10493   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10494   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10495     SDLoc SL(N);
10496     EVT EltVT = N->getValueType(0);
10497     SDValue Idx = N->getOperand(1);
10498     unsigned Opc = Vec.getOpcode();
10499 
10500     switch(Opc) {
10501     default:
10502       break;
10503       // TODO: Support other binary operations.
10504     case ISD::FADD:
10505     case ISD::FSUB:
10506     case ISD::FMUL:
10507     case ISD::ADD:
10508     case ISD::UMIN:
10509     case ISD::UMAX:
10510     case ISD::SMIN:
10511     case ISD::SMAX:
10512     case ISD::FMAXNUM:
10513     case ISD::FMINNUM:
10514     case ISD::FMAXNUM_IEEE:
10515     case ISD::FMINNUM_IEEE: {
10516       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10517                                  Vec.getOperand(0), Idx);
10518       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10519                                  Vec.getOperand(1), Idx);
10520 
10521       DCI.AddToWorklist(Elt0.getNode());
10522       DCI.AddToWorklist(Elt1.getNode());
10523       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10524     }
10525     }
10526   }
10527 
10528   unsigned VecSize = VecVT.getSizeInBits();
10529   unsigned EltSize = EltVT.getSizeInBits();
10530 
10531   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10532   if (::shouldExpandVectorDynExt(N)) {
10533     SDLoc SL(N);
10534     SDValue Idx = N->getOperand(1);
10535     SDValue V;
10536     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10537       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10538       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10539       if (I == 0)
10540         V = Elt;
10541       else
10542         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10543     }
10544     return V;
10545   }
10546 
10547   if (!DCI.isBeforeLegalize())
10548     return SDValue();
10549 
10550   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10551   // elements. This exposes more load reduction opportunities by replacing
10552   // multiple small extract_vector_elements with a single 32-bit extract.
10553   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10554   if (isa<MemSDNode>(Vec) &&
10555       EltSize <= 16 &&
10556       EltVT.isByteSized() &&
10557       VecSize > 32 &&
10558       VecSize % 32 == 0 &&
10559       Idx) {
10560     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10561 
10562     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10563     unsigned EltIdx = BitIndex / 32;
10564     unsigned LeftoverBitIdx = BitIndex % 32;
10565     SDLoc SL(N);
10566 
10567     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10568     DCI.AddToWorklist(Cast.getNode());
10569 
10570     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10571                               DAG.getConstant(EltIdx, SL, MVT::i32));
10572     DCI.AddToWorklist(Elt.getNode());
10573     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10574                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10575     DCI.AddToWorklist(Srl.getNode());
10576 
10577     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10578     DCI.AddToWorklist(Trunc.getNode());
10579     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10580   }
10581 
10582   return SDValue();
10583 }
10584 
10585 SDValue
10586 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10587                                                 DAGCombinerInfo &DCI) const {
10588   SDValue Vec = N->getOperand(0);
10589   SDValue Idx = N->getOperand(2);
10590   EVT VecVT = Vec.getValueType();
10591   EVT EltVT = VecVT.getVectorElementType();
10592 
10593   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10594   // => BUILD_VECTOR n x select (e, const-idx)
10595   if (!::shouldExpandVectorDynExt(N))
10596     return SDValue();
10597 
10598   SelectionDAG &DAG = DCI.DAG;
10599   SDLoc SL(N);
10600   SDValue Ins = N->getOperand(1);
10601   EVT IdxVT = Idx.getValueType();
10602 
10603   SmallVector<SDValue, 16> Ops;
10604   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10605     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10606     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10607     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10608     Ops.push_back(V);
10609   }
10610 
10611   return DAG.getBuildVector(VecVT, SL, Ops);
10612 }
10613 
10614 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10615                                           const SDNode *N0,
10616                                           const SDNode *N1) const {
10617   EVT VT = N0->getValueType(0);
10618 
10619   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10620   // support denormals ever.
10621   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10622        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10623         getSubtarget()->hasMadF16())) &&
10624        isOperationLegal(ISD::FMAD, VT))
10625     return ISD::FMAD;
10626 
10627   const TargetOptions &Options = DAG.getTarget().Options;
10628   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10629        (N0->getFlags().hasAllowContract() &&
10630         N1->getFlags().hasAllowContract())) &&
10631       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10632     return ISD::FMA;
10633   }
10634 
10635   return 0;
10636 }
10637 
10638 // For a reassociatable opcode perform:
10639 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10640 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10641                                                SelectionDAG &DAG) const {
10642   EVT VT = N->getValueType(0);
10643   if (VT != MVT::i32 && VT != MVT::i64)
10644     return SDValue();
10645 
10646   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10647     return SDValue();
10648 
10649   unsigned Opc = N->getOpcode();
10650   SDValue Op0 = N->getOperand(0);
10651   SDValue Op1 = N->getOperand(1);
10652 
10653   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10654     return SDValue();
10655 
10656   if (Op0->isDivergent())
10657     std::swap(Op0, Op1);
10658 
10659   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10660     return SDValue();
10661 
10662   SDValue Op2 = Op1.getOperand(1);
10663   Op1 = Op1.getOperand(0);
10664   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10665     return SDValue();
10666 
10667   if (Op1->isDivergent())
10668     std::swap(Op1, Op2);
10669 
10670   SDLoc SL(N);
10671   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10672   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10673 }
10674 
10675 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10676                            EVT VT,
10677                            SDValue N0, SDValue N1, SDValue N2,
10678                            bool Signed) {
10679   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10680   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10681   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10682   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10683 }
10684 
10685 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z).
10686 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10687                                             DAGCombinerInfo &DCI) const {
10688   assert(N->getOpcode() == ISD::ADD);
10689 
10690   SelectionDAG &DAG = DCI.DAG;
10691   EVT VT = N->getValueType(0);
10692   SDLoc SL(N);
10693   SDValue LHS = N->getOperand(0);
10694   SDValue RHS = N->getOperand(1);
10695 
10696   if (VT.isVector())
10697     return SDValue();
10698 
10699   unsigned NumBits = VT.getScalarSizeInBits();
10700   if (NumBits <= 32 || NumBits > 64)
10701     return SDValue();
10702 
10703   if (LHS.getOpcode() != ISD::MUL) {
10704     assert(RHS.getOpcode() == ISD::MUL);
10705     std::swap(LHS, RHS);
10706   }
10707 
10708   SDValue MulLHS = LHS.getOperand(0);
10709   SDValue MulRHS = LHS.getOperand(1);
10710   SDValue AddRHS = RHS;
10711 
10712   // TODO: Maybe restrict if SGPR inputs.
10713   if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10714       numBitsUnsigned(MulRHS, DAG) <= 32) {
10715     MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10716     MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10717     AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10718     return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10719   }
10720 
10721   if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10722     MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10723     MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10724     AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10725     return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10726   }
10727 
10728   return SDValue();
10729 }
10730 
10731 SDValue SITargetLowering::performAddCombine(SDNode *N,
10732                                             DAGCombinerInfo &DCI) const {
10733   SelectionDAG &DAG = DCI.DAG;
10734   EVT VT = N->getValueType(0);
10735   SDLoc SL(N);
10736   SDValue LHS = N->getOperand(0);
10737   SDValue RHS = N->getOperand(1);
10738 
10739   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10740     if (Subtarget->hasMad64_32()) {
10741       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10742         return Folded;
10743     }
10744 
10745     return SDValue();
10746   }
10747 
10748   if (SDValue V = reassociateScalarOps(N, DAG)) {
10749     return V;
10750   }
10751 
10752   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10753     return SDValue();
10754 
10755   // add x, zext (setcc) => addcarry x, 0, setcc
10756   // add x, sext (setcc) => subcarry x, 0, setcc
10757   unsigned Opc = LHS.getOpcode();
10758   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10759       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10760     std::swap(RHS, LHS);
10761 
10762   Opc = RHS.getOpcode();
10763   switch (Opc) {
10764   default: break;
10765   case ISD::ZERO_EXTEND:
10766   case ISD::SIGN_EXTEND:
10767   case ISD::ANY_EXTEND: {
10768     auto Cond = RHS.getOperand(0);
10769     // If this won't be a real VOPC output, we would still need to insert an
10770     // extra instruction anyway.
10771     if (!isBoolSGPR(Cond))
10772       break;
10773     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10774     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10775     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10776     return DAG.getNode(Opc, SL, VTList, Args);
10777   }
10778   case ISD::ADDCARRY: {
10779     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10780     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10781     if (!C || C->getZExtValue() != 0) break;
10782     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10783     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10784   }
10785   }
10786   return SDValue();
10787 }
10788 
10789 SDValue SITargetLowering::performSubCombine(SDNode *N,
10790                                             DAGCombinerInfo &DCI) const {
10791   SelectionDAG &DAG = DCI.DAG;
10792   EVT VT = N->getValueType(0);
10793 
10794   if (VT != MVT::i32)
10795     return SDValue();
10796 
10797   SDLoc SL(N);
10798   SDValue LHS = N->getOperand(0);
10799   SDValue RHS = N->getOperand(1);
10800 
10801   // sub x, zext (setcc) => subcarry x, 0, setcc
10802   // sub x, sext (setcc) => addcarry x, 0, setcc
10803   unsigned Opc = RHS.getOpcode();
10804   switch (Opc) {
10805   default: break;
10806   case ISD::ZERO_EXTEND:
10807   case ISD::SIGN_EXTEND:
10808   case ISD::ANY_EXTEND: {
10809     auto Cond = RHS.getOperand(0);
10810     // If this won't be a real VOPC output, we would still need to insert an
10811     // extra instruction anyway.
10812     if (!isBoolSGPR(Cond))
10813       break;
10814     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10815     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10816     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10817     return DAG.getNode(Opc, SL, VTList, Args);
10818   }
10819   }
10820 
10821   if (LHS.getOpcode() == ISD::SUBCARRY) {
10822     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10823     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10824     if (!C || !C->isZero())
10825       return SDValue();
10826     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10827     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10828   }
10829   return SDValue();
10830 }
10831 
10832 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10833   DAGCombinerInfo &DCI) const {
10834 
10835   if (N->getValueType(0) != MVT::i32)
10836     return SDValue();
10837 
10838   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10839   if (!C || C->getZExtValue() != 0)
10840     return SDValue();
10841 
10842   SelectionDAG &DAG = DCI.DAG;
10843   SDValue LHS = N->getOperand(0);
10844 
10845   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10846   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10847   unsigned LHSOpc = LHS.getOpcode();
10848   unsigned Opc = N->getOpcode();
10849   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10850       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10851     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10852     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10853   }
10854   return SDValue();
10855 }
10856 
10857 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10858                                              DAGCombinerInfo &DCI) const {
10859   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10860     return SDValue();
10861 
10862   SelectionDAG &DAG = DCI.DAG;
10863   EVT VT = N->getValueType(0);
10864 
10865   SDLoc SL(N);
10866   SDValue LHS = N->getOperand(0);
10867   SDValue RHS = N->getOperand(1);
10868 
10869   // These should really be instruction patterns, but writing patterns with
10870   // source modifiers is a pain.
10871 
10872   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10873   if (LHS.getOpcode() == ISD::FADD) {
10874     SDValue A = LHS.getOperand(0);
10875     if (A == LHS.getOperand(1)) {
10876       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10877       if (FusedOp != 0) {
10878         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10879         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10880       }
10881     }
10882   }
10883 
10884   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10885   if (RHS.getOpcode() == ISD::FADD) {
10886     SDValue A = RHS.getOperand(0);
10887     if (A == RHS.getOperand(1)) {
10888       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10889       if (FusedOp != 0) {
10890         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10891         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10892       }
10893     }
10894   }
10895 
10896   return SDValue();
10897 }
10898 
10899 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10900                                              DAGCombinerInfo &DCI) const {
10901   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10902     return SDValue();
10903 
10904   SelectionDAG &DAG = DCI.DAG;
10905   SDLoc SL(N);
10906   EVT VT = N->getValueType(0);
10907   assert(!VT.isVector());
10908 
10909   // Try to get the fneg to fold into the source modifier. This undoes generic
10910   // DAG combines and folds them into the mad.
10911   //
10912   // Only do this if we are not trying to support denormals. v_mad_f32 does
10913   // not support denormals ever.
10914   SDValue LHS = N->getOperand(0);
10915   SDValue RHS = N->getOperand(1);
10916   if (LHS.getOpcode() == ISD::FADD) {
10917     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10918     SDValue A = LHS.getOperand(0);
10919     if (A == LHS.getOperand(1)) {
10920       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10921       if (FusedOp != 0){
10922         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10923         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10924 
10925         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10926       }
10927     }
10928   }
10929 
10930   if (RHS.getOpcode() == ISD::FADD) {
10931     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10932 
10933     SDValue A = RHS.getOperand(0);
10934     if (A == RHS.getOperand(1)) {
10935       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10936       if (FusedOp != 0){
10937         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10938         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10939       }
10940     }
10941   }
10942 
10943   return SDValue();
10944 }
10945 
10946 SDValue SITargetLowering::performFMACombine(SDNode *N,
10947                                             DAGCombinerInfo &DCI) const {
10948   SelectionDAG &DAG = DCI.DAG;
10949   EVT VT = N->getValueType(0);
10950   SDLoc SL(N);
10951 
10952   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10953     return SDValue();
10954 
10955   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10956   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10957   SDValue Op1 = N->getOperand(0);
10958   SDValue Op2 = N->getOperand(1);
10959   SDValue FMA = N->getOperand(2);
10960 
10961   if (FMA.getOpcode() != ISD::FMA ||
10962       Op1.getOpcode() != ISD::FP_EXTEND ||
10963       Op2.getOpcode() != ISD::FP_EXTEND)
10964     return SDValue();
10965 
10966   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10967   // regardless of the denorm mode setting. Therefore,
10968   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10969   const TargetOptions &Options = DAG.getTarget().Options;
10970   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10971       (N->getFlags().hasAllowContract() &&
10972        FMA->getFlags().hasAllowContract())) {
10973     Op1 = Op1.getOperand(0);
10974     Op2 = Op2.getOperand(0);
10975     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10976         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10977       return SDValue();
10978 
10979     SDValue Vec1 = Op1.getOperand(0);
10980     SDValue Idx1 = Op1.getOperand(1);
10981     SDValue Vec2 = Op2.getOperand(0);
10982 
10983     SDValue FMAOp1 = FMA.getOperand(0);
10984     SDValue FMAOp2 = FMA.getOperand(1);
10985     SDValue FMAAcc = FMA.getOperand(2);
10986 
10987     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10988         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10989       return SDValue();
10990 
10991     FMAOp1 = FMAOp1.getOperand(0);
10992     FMAOp2 = FMAOp2.getOperand(0);
10993     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10994         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10995       return SDValue();
10996 
10997     SDValue Vec3 = FMAOp1.getOperand(0);
10998     SDValue Vec4 = FMAOp2.getOperand(0);
10999     SDValue Idx2 = FMAOp1.getOperand(1);
11000 
11001     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11002         // Idx1 and Idx2 cannot be the same.
11003         Idx1 == Idx2)
11004       return SDValue();
11005 
11006     if (Vec1 == Vec2 || Vec3 == Vec4)
11007       return SDValue();
11008 
11009     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11010       return SDValue();
11011 
11012     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11013         (Vec1 == Vec4 && Vec2 == Vec3)) {
11014       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11015                          DAG.getTargetConstant(0, SL, MVT::i1));
11016     }
11017   }
11018   return SDValue();
11019 }
11020 
11021 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11022                                               DAGCombinerInfo &DCI) const {
11023   SelectionDAG &DAG = DCI.DAG;
11024   SDLoc SL(N);
11025 
11026   SDValue LHS = N->getOperand(0);
11027   SDValue RHS = N->getOperand(1);
11028   EVT VT = LHS.getValueType();
11029   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11030 
11031   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11032   if (!CRHS) {
11033     CRHS = dyn_cast<ConstantSDNode>(LHS);
11034     if (CRHS) {
11035       std::swap(LHS, RHS);
11036       CC = getSetCCSwappedOperands(CC);
11037     }
11038   }
11039 
11040   if (CRHS) {
11041     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11042         isBoolSGPR(LHS.getOperand(0))) {
11043       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11044       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11045       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11046       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11047       if ((CRHS->isAllOnes() &&
11048            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11049           (CRHS->isZero() &&
11050            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11051         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11052                            DAG.getConstant(-1, SL, MVT::i1));
11053       if ((CRHS->isAllOnes() &&
11054            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11055           (CRHS->isZero() &&
11056            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11057         return LHS.getOperand(0);
11058     }
11059 
11060     const APInt &CRHSVal = CRHS->getAPIntValue();
11061     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11062         LHS.getOpcode() == ISD::SELECT &&
11063         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11064         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11065         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11066         isBoolSGPR(LHS.getOperand(0))) {
11067       // Given CT != FT:
11068       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11069       // setcc (select cc, CT, CF), CF, ne => cc
11070       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11071       // setcc (select cc, CT, CF), CT, eq => cc
11072       const APInt &CT = LHS.getConstantOperandAPInt(1);
11073       const APInt &CF = LHS.getConstantOperandAPInt(2);
11074 
11075       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11076           (CT == CRHSVal && CC == ISD::SETNE))
11077         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11078                            DAG.getConstant(-1, SL, MVT::i1));
11079       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11080           (CT == CRHSVal && CC == ISD::SETEQ))
11081         return LHS.getOperand(0);
11082     }
11083   }
11084 
11085   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11086                                            VT != MVT::f16))
11087     return SDValue();
11088 
11089   // Match isinf/isfinite pattern
11090   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11091   // (fcmp one (fabs x), inf) -> (fp_class x,
11092   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11093   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11094     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11095     if (!CRHS)
11096       return SDValue();
11097 
11098     const APFloat &APF = CRHS->getValueAPF();
11099     if (APF.isInfinity() && !APF.isNegative()) {
11100       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11101                                  SIInstrFlags::N_INFINITY;
11102       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11103                                     SIInstrFlags::P_ZERO |
11104                                     SIInstrFlags::N_NORMAL |
11105                                     SIInstrFlags::P_NORMAL |
11106                                     SIInstrFlags::N_SUBNORMAL |
11107                                     SIInstrFlags::P_SUBNORMAL;
11108       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11109       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11110                          DAG.getConstant(Mask, SL, MVT::i32));
11111     }
11112   }
11113 
11114   return SDValue();
11115 }
11116 
11117 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11118                                                      DAGCombinerInfo &DCI) const {
11119   SelectionDAG &DAG = DCI.DAG;
11120   SDLoc SL(N);
11121   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11122 
11123   SDValue Src = N->getOperand(0);
11124   SDValue Shift = N->getOperand(0);
11125 
11126   // TODO: Extend type shouldn't matter (assuming legal types).
11127   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11128     Shift = Shift.getOperand(0);
11129 
11130   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11131     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11132     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11133     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11134     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11135     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11136     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11137       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11138                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11139 
11140       unsigned ShiftOffset = 8 * Offset;
11141       if (Shift.getOpcode() == ISD::SHL)
11142         ShiftOffset -= C->getZExtValue();
11143       else
11144         ShiftOffset += C->getZExtValue();
11145 
11146       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11147         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11148                            MVT::f32, Shifted);
11149       }
11150     }
11151   }
11152 
11153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11154   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11155   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11156     // We simplified Src. If this node is not dead, visit it again so it is
11157     // folded properly.
11158     if (N->getOpcode() != ISD::DELETED_NODE)
11159       DCI.AddToWorklist(N);
11160     return SDValue(N, 0);
11161   }
11162 
11163   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11164   if (SDValue DemandedSrc =
11165           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11166     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11167 
11168   return SDValue();
11169 }
11170 
11171 SDValue SITargetLowering::performClampCombine(SDNode *N,
11172                                               DAGCombinerInfo &DCI) const {
11173   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11174   if (!CSrc)
11175     return SDValue();
11176 
11177   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11178   const APFloat &F = CSrc->getValueAPF();
11179   APFloat Zero = APFloat::getZero(F.getSemantics());
11180   if (F < Zero ||
11181       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11182     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11183   }
11184 
11185   APFloat One(F.getSemantics(), "1.0");
11186   if (F > One)
11187     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11188 
11189   return SDValue(CSrc, 0);
11190 }
11191 
11192 
11193 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11194                                             DAGCombinerInfo &DCI) const {
11195   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11196     return SDValue();
11197   switch (N->getOpcode()) {
11198   case ISD::ADD:
11199     return performAddCombine(N, DCI);
11200   case ISD::SUB:
11201     return performSubCombine(N, DCI);
11202   case ISD::ADDCARRY:
11203   case ISD::SUBCARRY:
11204     return performAddCarrySubCarryCombine(N, DCI);
11205   case ISD::FADD:
11206     return performFAddCombine(N, DCI);
11207   case ISD::FSUB:
11208     return performFSubCombine(N, DCI);
11209   case ISD::SETCC:
11210     return performSetCCCombine(N, DCI);
11211   case ISD::FMAXNUM:
11212   case ISD::FMINNUM:
11213   case ISD::FMAXNUM_IEEE:
11214   case ISD::FMINNUM_IEEE:
11215   case ISD::SMAX:
11216   case ISD::SMIN:
11217   case ISD::UMAX:
11218   case ISD::UMIN:
11219   case AMDGPUISD::FMIN_LEGACY:
11220   case AMDGPUISD::FMAX_LEGACY:
11221     return performMinMaxCombine(N, DCI);
11222   case ISD::FMA:
11223     return performFMACombine(N, DCI);
11224   case ISD::AND:
11225     return performAndCombine(N, DCI);
11226   case ISD::OR:
11227     return performOrCombine(N, DCI);
11228   case ISD::XOR:
11229     return performXorCombine(N, DCI);
11230   case ISD::ZERO_EXTEND:
11231     return performZeroExtendCombine(N, DCI);
11232   case ISD::SIGN_EXTEND_INREG:
11233     return performSignExtendInRegCombine(N , DCI);
11234   case AMDGPUISD::FP_CLASS:
11235     return performClassCombine(N, DCI);
11236   case ISD::FCANONICALIZE:
11237     return performFCanonicalizeCombine(N, DCI);
11238   case AMDGPUISD::RCP:
11239     return performRcpCombine(N, DCI);
11240   case AMDGPUISD::FRACT:
11241   case AMDGPUISD::RSQ:
11242   case AMDGPUISD::RCP_LEGACY:
11243   case AMDGPUISD::RCP_IFLAG:
11244   case AMDGPUISD::RSQ_CLAMP:
11245   case AMDGPUISD::LDEXP: {
11246     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11247     SDValue Src = N->getOperand(0);
11248     if (Src.isUndef())
11249       return Src;
11250     break;
11251   }
11252   case ISD::SINT_TO_FP:
11253   case ISD::UINT_TO_FP:
11254     return performUCharToFloatCombine(N, DCI);
11255   case AMDGPUISD::CVT_F32_UBYTE0:
11256   case AMDGPUISD::CVT_F32_UBYTE1:
11257   case AMDGPUISD::CVT_F32_UBYTE2:
11258   case AMDGPUISD::CVT_F32_UBYTE3:
11259     return performCvtF32UByteNCombine(N, DCI);
11260   case AMDGPUISD::FMED3:
11261     return performFMed3Combine(N, DCI);
11262   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11263     return performCvtPkRTZCombine(N, DCI);
11264   case AMDGPUISD::CLAMP:
11265     return performClampCombine(N, DCI);
11266   case ISD::SCALAR_TO_VECTOR: {
11267     SelectionDAG &DAG = DCI.DAG;
11268     EVT VT = N->getValueType(0);
11269 
11270     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11271     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11272       SDLoc SL(N);
11273       SDValue Src = N->getOperand(0);
11274       EVT EltVT = Src.getValueType();
11275       if (EltVT == MVT::f16)
11276         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11277 
11278       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11279       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11280     }
11281 
11282     break;
11283   }
11284   case ISD::EXTRACT_VECTOR_ELT:
11285     return performExtractVectorEltCombine(N, DCI);
11286   case ISD::INSERT_VECTOR_ELT:
11287     return performInsertVectorEltCombine(N, DCI);
11288   case ISD::LOAD: {
11289     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11290       return Widended;
11291     LLVM_FALLTHROUGH;
11292   }
11293   default: {
11294     if (!DCI.isBeforeLegalize()) {
11295       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11296         return performMemSDNodeCombine(MemNode, DCI);
11297     }
11298 
11299     break;
11300   }
11301   }
11302 
11303   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11304 }
11305 
11306 /// Helper function for adjustWritemask
11307 static unsigned SubIdx2Lane(unsigned Idx) {
11308   switch (Idx) {
11309   default: return ~0u;
11310   case AMDGPU::sub0: return 0;
11311   case AMDGPU::sub1: return 1;
11312   case AMDGPU::sub2: return 2;
11313   case AMDGPU::sub3: return 3;
11314   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11315   }
11316 }
11317 
11318 /// Adjust the writemask of MIMG instructions
11319 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11320                                           SelectionDAG &DAG) const {
11321   unsigned Opcode = Node->getMachineOpcode();
11322 
11323   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11324   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11325   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11326     return Node; // not implemented for D16
11327 
11328   SDNode *Users[5] = { nullptr };
11329   unsigned Lane = 0;
11330   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11331   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11332   unsigned NewDmask = 0;
11333   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11334   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11335   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11336                   Node->getConstantOperandVal(LWEIdx))
11337                      ? true
11338                      : false;
11339   unsigned TFCLane = 0;
11340   bool HasChain = Node->getNumValues() > 1;
11341 
11342   if (OldDmask == 0) {
11343     // These are folded out, but on the chance it happens don't assert.
11344     return Node;
11345   }
11346 
11347   unsigned OldBitsSet = countPopulation(OldDmask);
11348   // Work out which is the TFE/LWE lane if that is enabled.
11349   if (UsesTFC) {
11350     TFCLane = OldBitsSet;
11351   }
11352 
11353   // Try to figure out the used register components
11354   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11355        I != E; ++I) {
11356 
11357     // Don't look at users of the chain.
11358     if (I.getUse().getResNo() != 0)
11359       continue;
11360 
11361     // Abort if we can't understand the usage
11362     if (!I->isMachineOpcode() ||
11363         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11364       return Node;
11365 
11366     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11367     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11368     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11369     // set, etc.
11370     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11371     if (Lane == ~0u)
11372       return Node;
11373 
11374     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11375     if (UsesTFC && Lane == TFCLane) {
11376       Users[Lane] = *I;
11377     } else {
11378       // Set which texture component corresponds to the lane.
11379       unsigned Comp;
11380       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11381         Comp = countTrailingZeros(Dmask);
11382         Dmask &= ~(1 << Comp);
11383       }
11384 
11385       // Abort if we have more than one user per component.
11386       if (Users[Lane])
11387         return Node;
11388 
11389       Users[Lane] = *I;
11390       NewDmask |= 1 << Comp;
11391     }
11392   }
11393 
11394   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11395   bool NoChannels = !NewDmask;
11396   if (NoChannels) {
11397     if (!UsesTFC) {
11398       // No uses of the result and not using TFC. Then do nothing.
11399       return Node;
11400     }
11401     // If the original dmask has one channel - then nothing to do
11402     if (OldBitsSet == 1)
11403       return Node;
11404     // Use an arbitrary dmask - required for the instruction to work
11405     NewDmask = 1;
11406   }
11407   // Abort if there's no change
11408   if (NewDmask == OldDmask)
11409     return Node;
11410 
11411   unsigned BitsSet = countPopulation(NewDmask);
11412 
11413   // Check for TFE or LWE - increase the number of channels by one to account
11414   // for the extra return value
11415   // This will need adjustment for D16 if this is also included in
11416   // adjustWriteMask (this function) but at present D16 are excluded.
11417   unsigned NewChannels = BitsSet + UsesTFC;
11418 
11419   int NewOpcode =
11420       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11421   assert(NewOpcode != -1 &&
11422          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11423          "failed to find equivalent MIMG op");
11424 
11425   // Adjust the writemask in the node
11426   SmallVector<SDValue, 12> Ops;
11427   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11428   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11429   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11430 
11431   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11432 
11433   MVT ResultVT = NewChannels == 1 ?
11434     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11435                            NewChannels == 5 ? 8 : NewChannels);
11436   SDVTList NewVTList = HasChain ?
11437     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11438 
11439 
11440   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11441                                               NewVTList, Ops);
11442 
11443   if (HasChain) {
11444     // Update chain.
11445     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11446     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11447   }
11448 
11449   if (NewChannels == 1) {
11450     assert(Node->hasNUsesOfValue(1, 0));
11451     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11452                                       SDLoc(Node), Users[Lane]->getValueType(0),
11453                                       SDValue(NewNode, 0));
11454     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11455     return nullptr;
11456   }
11457 
11458   // Update the users of the node with the new indices
11459   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11460     SDNode *User = Users[i];
11461     if (!User) {
11462       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11463       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11464       if (i || !NoChannels)
11465         continue;
11466     } else {
11467       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11468       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11469     }
11470 
11471     switch (Idx) {
11472     default: break;
11473     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11474     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11475     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11476     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11477     }
11478   }
11479 
11480   DAG.RemoveDeadNode(Node);
11481   return nullptr;
11482 }
11483 
11484 static bool isFrameIndexOp(SDValue Op) {
11485   if (Op.getOpcode() == ISD::AssertZext)
11486     Op = Op.getOperand(0);
11487 
11488   return isa<FrameIndexSDNode>(Op);
11489 }
11490 
11491 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11492 /// with frame index operands.
11493 /// LLVM assumes that inputs are to these instructions are registers.
11494 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11495                                                         SelectionDAG &DAG) const {
11496   if (Node->getOpcode() == ISD::CopyToReg) {
11497     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11498     SDValue SrcVal = Node->getOperand(2);
11499 
11500     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11501     // to try understanding copies to physical registers.
11502     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11503       SDLoc SL(Node);
11504       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11505       SDValue VReg = DAG.getRegister(
11506         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11507 
11508       SDNode *Glued = Node->getGluedNode();
11509       SDValue ToVReg
11510         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11511                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11512       SDValue ToResultReg
11513         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11514                            VReg, ToVReg.getValue(1));
11515       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11516       DAG.RemoveDeadNode(Node);
11517       return ToResultReg.getNode();
11518     }
11519   }
11520 
11521   SmallVector<SDValue, 8> Ops;
11522   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11523     if (!isFrameIndexOp(Node->getOperand(i))) {
11524       Ops.push_back(Node->getOperand(i));
11525       continue;
11526     }
11527 
11528     SDLoc DL(Node);
11529     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11530                                      Node->getOperand(i).getValueType(),
11531                                      Node->getOperand(i)), 0));
11532   }
11533 
11534   return DAG.UpdateNodeOperands(Node, Ops);
11535 }
11536 
11537 /// Fold the instructions after selecting them.
11538 /// Returns null if users were already updated.
11539 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11540                                           SelectionDAG &DAG) const {
11541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11542   unsigned Opcode = Node->getMachineOpcode();
11543 
11544   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11545       !TII->isGather4(Opcode) &&
11546       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11547     return adjustWritemask(Node, DAG);
11548   }
11549 
11550   if (Opcode == AMDGPU::INSERT_SUBREG ||
11551       Opcode == AMDGPU::REG_SEQUENCE) {
11552     legalizeTargetIndependentNode(Node, DAG);
11553     return Node;
11554   }
11555 
11556   switch (Opcode) {
11557   case AMDGPU::V_DIV_SCALE_F32_e64:
11558   case AMDGPU::V_DIV_SCALE_F64_e64: {
11559     // Satisfy the operand register constraint when one of the inputs is
11560     // undefined. Ordinarily each undef value will have its own implicit_def of
11561     // a vreg, so force these to use a single register.
11562     SDValue Src0 = Node->getOperand(1);
11563     SDValue Src1 = Node->getOperand(3);
11564     SDValue Src2 = Node->getOperand(5);
11565 
11566     if ((Src0.isMachineOpcode() &&
11567          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11568         (Src0 == Src1 || Src0 == Src2))
11569       break;
11570 
11571     MVT VT = Src0.getValueType().getSimpleVT();
11572     const TargetRegisterClass *RC =
11573         getRegClassFor(VT, Src0.getNode()->isDivergent());
11574 
11575     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11576     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11577 
11578     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11579                                       UndefReg, Src0, SDValue());
11580 
11581     // src0 must be the same register as src1 or src2, even if the value is
11582     // undefined, so make sure we don't violate this constraint.
11583     if (Src0.isMachineOpcode() &&
11584         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11585       if (Src1.isMachineOpcode() &&
11586           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11587         Src0 = Src1;
11588       else if (Src2.isMachineOpcode() &&
11589                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11590         Src0 = Src2;
11591       else {
11592         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11593         Src0 = UndefReg;
11594         Src1 = UndefReg;
11595       }
11596     } else
11597       break;
11598 
11599     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11600     Ops[1] = Src0;
11601     Ops[3] = Src1;
11602     Ops[5] = Src2;
11603     Ops.push_back(ImpDef.getValue(1));
11604     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11605   }
11606   default:
11607     break;
11608   }
11609 
11610   return Node;
11611 }
11612 
11613 // Any MIMG instructions that use tfe or lwe require an initialization of the
11614 // result register that will be written in the case of a memory access failure.
11615 // The required code is also added to tie this init code to the result of the
11616 // img instruction.
11617 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11618   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11619   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11620   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11621   MachineBasicBlock &MBB = *MI.getParent();
11622 
11623   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11624   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11625   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11626 
11627   if (!TFE && !LWE) // intersect_ray
11628     return;
11629 
11630   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11631   unsigned LWEVal = LWE->getImm();
11632   unsigned D16Val = D16 ? D16->getImm() : 0;
11633 
11634   if (!TFEVal && !LWEVal)
11635     return;
11636 
11637   // At least one of TFE or LWE are non-zero
11638   // We have to insert a suitable initialization of the result value and
11639   // tie this to the dest of the image instruction.
11640 
11641   const DebugLoc &DL = MI.getDebugLoc();
11642 
11643   int DstIdx =
11644       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11645 
11646   // Calculate which dword we have to initialize to 0.
11647   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11648 
11649   // check that dmask operand is found.
11650   assert(MO_Dmask && "Expected dmask operand in instruction");
11651 
11652   unsigned dmask = MO_Dmask->getImm();
11653   // Determine the number of active lanes taking into account the
11654   // Gather4 special case
11655   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11656 
11657   bool Packed = !Subtarget->hasUnpackedD16VMem();
11658 
11659   unsigned InitIdx =
11660       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11661 
11662   // Abandon attempt if the dst size isn't large enough
11663   // - this is in fact an error but this is picked up elsewhere and
11664   // reported correctly.
11665   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11666   if (DstSize < InitIdx)
11667     return;
11668 
11669   // Create a register for the initialization value.
11670   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11671   unsigned NewDst = 0; // Final initialized value will be in here
11672 
11673   // If PRTStrictNull feature is enabled (the default) then initialize
11674   // all the result registers to 0, otherwise just the error indication
11675   // register (VGPRn+1)
11676   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11677   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11678 
11679   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11680   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11681     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11682     // Initialize dword
11683     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11684     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11685       .addImm(0);
11686     // Insert into the super-reg
11687     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11688       .addReg(PrevDst)
11689       .addReg(SubReg)
11690       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11691 
11692     PrevDst = NewDst;
11693   }
11694 
11695   // Add as an implicit operand
11696   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11697 
11698   // Tie the just added implicit operand to the dst
11699   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11700 }
11701 
11702 /// Assign the register class depending on the number of
11703 /// bits set in the writemask
11704 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11705                                                      SDNode *Node) const {
11706   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11707 
11708   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11709 
11710   if (TII->isVOP3(MI.getOpcode())) {
11711     // Make sure constant bus requirements are respected.
11712     TII->legalizeOperandsVOP3(MRI, MI);
11713 
11714     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11715     // This saves a chain-copy of registers and better balance register
11716     // use between vgpr and agpr as agpr tuples tend to be big.
11717     if (MI.getDesc().OpInfo) {
11718       unsigned Opc = MI.getOpcode();
11719       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11720       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11721                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11722         if (I == -1)
11723           break;
11724         MachineOperand &Op = MI.getOperand(I);
11725         if (!Op.isReg() || !Op.getReg().isVirtual())
11726           continue;
11727         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11728         if (!TRI->hasAGPRs(RC))
11729           continue;
11730         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11731         if (!Src || !Src->isCopy() ||
11732             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11733           continue;
11734         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11735         // All uses of agpr64 and agpr32 can also accept vgpr except for
11736         // v_accvgpr_read, but we do not produce agpr reads during selection,
11737         // so no use checks are needed.
11738         MRI.setRegClass(Op.getReg(), NewRC);
11739       }
11740 
11741       // Resolve the rest of AV operands to AGPRs.
11742       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11743         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11744           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11745           if (TRI->isVectorSuperClass(RC)) {
11746             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11747             MRI.setRegClass(Src2->getReg(), NewRC);
11748             if (Src2->isTied())
11749               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11750           }
11751         }
11752       }
11753     }
11754 
11755     return;
11756   }
11757 
11758   if (TII->isMIMG(MI) && !MI.mayStore())
11759     AddIMGInit(MI);
11760 }
11761 
11762 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11763                               uint64_t Val) {
11764   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11765   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11766 }
11767 
11768 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11769                                                 const SDLoc &DL,
11770                                                 SDValue Ptr) const {
11771   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11772 
11773   // Build the half of the subregister with the constants before building the
11774   // full 128-bit register. If we are building multiple resource descriptors,
11775   // this will allow CSEing of the 2-component register.
11776   const SDValue Ops0[] = {
11777     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11778     buildSMovImm32(DAG, DL, 0),
11779     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11780     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11781     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11782   };
11783 
11784   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11785                                                 MVT::v2i32, Ops0), 0);
11786 
11787   // Combine the constants and the pointer.
11788   const SDValue Ops1[] = {
11789     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11790     Ptr,
11791     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11792     SubRegHi,
11793     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11794   };
11795 
11796   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11797 }
11798 
11799 /// Return a resource descriptor with the 'Add TID' bit enabled
11800 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11801 ///        of the resource descriptor) to create an offset, which is added to
11802 ///        the resource pointer.
11803 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11804                                            SDValue Ptr, uint32_t RsrcDword1,
11805                                            uint64_t RsrcDword2And3) const {
11806   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11807   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11808   if (RsrcDword1) {
11809     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11810                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11811                     0);
11812   }
11813 
11814   SDValue DataLo = buildSMovImm32(DAG, DL,
11815                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11816   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11817 
11818   const SDValue Ops[] = {
11819     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11820     PtrLo,
11821     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11822     PtrHi,
11823     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11824     DataLo,
11825     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11826     DataHi,
11827     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11828   };
11829 
11830   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11831 }
11832 
11833 //===----------------------------------------------------------------------===//
11834 //                         SI Inline Assembly Support
11835 //===----------------------------------------------------------------------===//
11836 
11837 std::pair<unsigned, const TargetRegisterClass *>
11838 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11839                                                StringRef Constraint,
11840                                                MVT VT) const {
11841   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11842 
11843   const TargetRegisterClass *RC = nullptr;
11844   if (Constraint.size() == 1) {
11845     const unsigned BitWidth = VT.getSizeInBits();
11846     switch (Constraint[0]) {
11847     default:
11848       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11849     case 's':
11850     case 'r':
11851       switch (BitWidth) {
11852       case 16:
11853         RC = &AMDGPU::SReg_32RegClass;
11854         break;
11855       case 64:
11856         RC = &AMDGPU::SGPR_64RegClass;
11857         break;
11858       default:
11859         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11860         if (!RC)
11861           return std::make_pair(0U, nullptr);
11862         break;
11863       }
11864       break;
11865     case 'v':
11866       switch (BitWidth) {
11867       case 16:
11868         RC = &AMDGPU::VGPR_32RegClass;
11869         break;
11870       default:
11871         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11872         if (!RC)
11873           return std::make_pair(0U, nullptr);
11874         break;
11875       }
11876       break;
11877     case 'a':
11878       if (!Subtarget->hasMAIInsts())
11879         break;
11880       switch (BitWidth) {
11881       case 16:
11882         RC = &AMDGPU::AGPR_32RegClass;
11883         break;
11884       default:
11885         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11886         if (!RC)
11887           return std::make_pair(0U, nullptr);
11888         break;
11889       }
11890       break;
11891     }
11892     // We actually support i128, i16 and f16 as inline parameters
11893     // even if they are not reported as legal
11894     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11895                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11896       return std::make_pair(0U, RC);
11897   }
11898 
11899   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11900     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11901     if (RegName.consume_front("v")) {
11902       RC = &AMDGPU::VGPR_32RegClass;
11903     } else if (RegName.consume_front("s")) {
11904       RC = &AMDGPU::SGPR_32RegClass;
11905     } else if (RegName.consume_front("a")) {
11906       RC = &AMDGPU::AGPR_32RegClass;
11907     }
11908 
11909     if (RC) {
11910       uint32_t Idx;
11911       if (RegName.consume_front("[")) {
11912         uint32_t End;
11913         bool Failed = RegName.consumeInteger(10, Idx);
11914         Failed |= !RegName.consume_front(":");
11915         Failed |= RegName.consumeInteger(10, End);
11916         Failed |= !RegName.consume_back("]");
11917         if (!Failed) {
11918           uint32_t Width = (End - Idx + 1) * 32;
11919           MCRegister Reg = RC->getRegister(Idx);
11920           if (SIRegisterInfo::isVGPRClass(RC))
11921             RC = TRI->getVGPRClassForBitWidth(Width);
11922           else if (SIRegisterInfo::isSGPRClass(RC))
11923             RC = TRI->getSGPRClassForBitWidth(Width);
11924           else if (SIRegisterInfo::isAGPRClass(RC))
11925             RC = TRI->getAGPRClassForBitWidth(Width);
11926           if (RC) {
11927             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11928             return std::make_pair(Reg, RC);
11929           }
11930         }
11931       } else {
11932         bool Failed = RegName.getAsInteger(10, Idx);
11933         if (!Failed && Idx < RC->getNumRegs())
11934           return std::make_pair(RC->getRegister(Idx), RC);
11935       }
11936     }
11937   }
11938 
11939   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11940   if (Ret.first)
11941     Ret.second = TRI->getPhysRegClass(Ret.first);
11942 
11943   return Ret;
11944 }
11945 
11946 static bool isImmConstraint(StringRef Constraint) {
11947   if (Constraint.size() == 1) {
11948     switch (Constraint[0]) {
11949     default: break;
11950     case 'I':
11951     case 'J':
11952     case 'A':
11953     case 'B':
11954     case 'C':
11955       return true;
11956     }
11957   } else if (Constraint == "DA" ||
11958              Constraint == "DB") {
11959     return true;
11960   }
11961   return false;
11962 }
11963 
11964 SITargetLowering::ConstraintType
11965 SITargetLowering::getConstraintType(StringRef Constraint) const {
11966   if (Constraint.size() == 1) {
11967     switch (Constraint[0]) {
11968     default: break;
11969     case 's':
11970     case 'v':
11971     case 'a':
11972       return C_RegisterClass;
11973     }
11974   }
11975   if (isImmConstraint(Constraint)) {
11976     return C_Other;
11977   }
11978   return TargetLowering::getConstraintType(Constraint);
11979 }
11980 
11981 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11982   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11983     Val = Val & maskTrailingOnes<uint64_t>(Size);
11984   }
11985   return Val;
11986 }
11987 
11988 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11989                                                     std::string &Constraint,
11990                                                     std::vector<SDValue> &Ops,
11991                                                     SelectionDAG &DAG) const {
11992   if (isImmConstraint(Constraint)) {
11993     uint64_t Val;
11994     if (getAsmOperandConstVal(Op, Val) &&
11995         checkAsmConstraintVal(Op, Constraint, Val)) {
11996       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11997       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11998     }
11999   } else {
12000     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12001   }
12002 }
12003 
12004 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12005   unsigned Size = Op.getScalarValueSizeInBits();
12006   if (Size > 64)
12007     return false;
12008 
12009   if (Size == 16 && !Subtarget->has16BitInsts())
12010     return false;
12011 
12012   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12013     Val = C->getSExtValue();
12014     return true;
12015   }
12016   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12017     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12018     return true;
12019   }
12020   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12021     if (Size != 16 || Op.getNumOperands() != 2)
12022       return false;
12023     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12024       return false;
12025     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12026       Val = C->getSExtValue();
12027       return true;
12028     }
12029     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12030       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12031       return true;
12032     }
12033   }
12034 
12035   return false;
12036 }
12037 
12038 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12039                                              const std::string &Constraint,
12040                                              uint64_t Val) const {
12041   if (Constraint.size() == 1) {
12042     switch (Constraint[0]) {
12043     case 'I':
12044       return AMDGPU::isInlinableIntLiteral(Val);
12045     case 'J':
12046       return isInt<16>(Val);
12047     case 'A':
12048       return checkAsmConstraintValA(Op, Val);
12049     case 'B':
12050       return isInt<32>(Val);
12051     case 'C':
12052       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12053              AMDGPU::isInlinableIntLiteral(Val);
12054     default:
12055       break;
12056     }
12057   } else if (Constraint.size() == 2) {
12058     if (Constraint == "DA") {
12059       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12060       int64_t LoBits = static_cast<int32_t>(Val);
12061       return checkAsmConstraintValA(Op, HiBits, 32) &&
12062              checkAsmConstraintValA(Op, LoBits, 32);
12063     }
12064     if (Constraint == "DB") {
12065       return true;
12066     }
12067   }
12068   llvm_unreachable("Invalid asm constraint");
12069 }
12070 
12071 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12072                                               uint64_t Val,
12073                                               unsigned MaxSize) const {
12074   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12075   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12076   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12077       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12078       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12079     return true;
12080   }
12081   return false;
12082 }
12083 
12084 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12085   switch (UnalignedClassID) {
12086   case AMDGPU::VReg_64RegClassID:
12087     return AMDGPU::VReg_64_Align2RegClassID;
12088   case AMDGPU::VReg_96RegClassID:
12089     return AMDGPU::VReg_96_Align2RegClassID;
12090   case AMDGPU::VReg_128RegClassID:
12091     return AMDGPU::VReg_128_Align2RegClassID;
12092   case AMDGPU::VReg_160RegClassID:
12093     return AMDGPU::VReg_160_Align2RegClassID;
12094   case AMDGPU::VReg_192RegClassID:
12095     return AMDGPU::VReg_192_Align2RegClassID;
12096   case AMDGPU::VReg_224RegClassID:
12097     return AMDGPU::VReg_224_Align2RegClassID;
12098   case AMDGPU::VReg_256RegClassID:
12099     return AMDGPU::VReg_256_Align2RegClassID;
12100   case AMDGPU::VReg_512RegClassID:
12101     return AMDGPU::VReg_512_Align2RegClassID;
12102   case AMDGPU::VReg_1024RegClassID:
12103     return AMDGPU::VReg_1024_Align2RegClassID;
12104   case AMDGPU::AReg_64RegClassID:
12105     return AMDGPU::AReg_64_Align2RegClassID;
12106   case AMDGPU::AReg_96RegClassID:
12107     return AMDGPU::AReg_96_Align2RegClassID;
12108   case AMDGPU::AReg_128RegClassID:
12109     return AMDGPU::AReg_128_Align2RegClassID;
12110   case AMDGPU::AReg_160RegClassID:
12111     return AMDGPU::AReg_160_Align2RegClassID;
12112   case AMDGPU::AReg_192RegClassID:
12113     return AMDGPU::AReg_192_Align2RegClassID;
12114   case AMDGPU::AReg_256RegClassID:
12115     return AMDGPU::AReg_256_Align2RegClassID;
12116   case AMDGPU::AReg_512RegClassID:
12117     return AMDGPU::AReg_512_Align2RegClassID;
12118   case AMDGPU::AReg_1024RegClassID:
12119     return AMDGPU::AReg_1024_Align2RegClassID;
12120   default:
12121     return -1;
12122   }
12123 }
12124 
12125 // Figure out which registers should be reserved for stack access. Only after
12126 // the function is legalized do we know all of the non-spill stack objects or if
12127 // calls are present.
12128 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12129   MachineRegisterInfo &MRI = MF.getRegInfo();
12130   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12131   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12132   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12133   const SIInstrInfo *TII = ST.getInstrInfo();
12134 
12135   if (Info->isEntryFunction()) {
12136     // Callable functions have fixed registers used for stack access.
12137     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12138   }
12139 
12140   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12141                              Info->getStackPtrOffsetReg()));
12142   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12143     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12144 
12145   // We need to worry about replacing the default register with itself in case
12146   // of MIR testcases missing the MFI.
12147   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12148     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12149 
12150   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12151     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12152 
12153   Info->limitOccupancy(MF);
12154 
12155   if (ST.isWave32() && !MF.empty()) {
12156     for (auto &MBB : MF) {
12157       for (auto &MI : MBB) {
12158         TII->fixImplicitOperands(MI);
12159       }
12160     }
12161   }
12162 
12163   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12164   // classes if required. Ideally the register class constraints would differ
12165   // per-subtarget, but there's no easy way to achieve that right now. This is
12166   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12167   // from using them as the register class for legal types.
12168   if (ST.needsAlignedVGPRs()) {
12169     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12170       const Register Reg = Register::index2VirtReg(I);
12171       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12172       if (!RC)
12173         continue;
12174       int NewClassID = getAlignedAGPRClassID(RC->getID());
12175       if (NewClassID != -1)
12176         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12177     }
12178   }
12179 
12180   TargetLoweringBase::finalizeLowering(MF);
12181 }
12182 
12183 void SITargetLowering::computeKnownBitsForFrameIndex(
12184   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12185   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12186 
12187   // Set the high bits to zero based on the maximum allowed scratch size per
12188   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12189   // calculation won't overflow, so assume the sign bit is never set.
12190   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12191 }
12192 
12193 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12194                                    KnownBits &Known, unsigned Dim) {
12195   unsigned MaxValue =
12196       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12197   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12198 }
12199 
12200 void SITargetLowering::computeKnownBitsForTargetInstr(
12201     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12202     const MachineRegisterInfo &MRI, unsigned Depth) const {
12203   const MachineInstr *MI = MRI.getVRegDef(R);
12204   switch (MI->getOpcode()) {
12205   case AMDGPU::G_INTRINSIC: {
12206     switch (MI->getIntrinsicID()) {
12207     case Intrinsic::amdgcn_workitem_id_x:
12208       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12209       break;
12210     case Intrinsic::amdgcn_workitem_id_y:
12211       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12212       break;
12213     case Intrinsic::amdgcn_workitem_id_z:
12214       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12215       break;
12216     case Intrinsic::amdgcn_mbcnt_lo:
12217     case Intrinsic::amdgcn_mbcnt_hi: {
12218       // These return at most the wavefront size - 1.
12219       unsigned Size = MRI.getType(R).getSizeInBits();
12220       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12221       break;
12222     }
12223     case Intrinsic::amdgcn_groupstaticsize: {
12224       // We can report everything over the maximum size as 0. We can't report
12225       // based on the actual size because we don't know if it's accurate or not
12226       // at any given point.
12227       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12228       break;
12229     }
12230     }
12231     break;
12232   }
12233   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12234     Known.Zero.setHighBits(24);
12235     break;
12236   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12237     Known.Zero.setHighBits(16);
12238     break;
12239   }
12240 }
12241 
12242 Align SITargetLowering::computeKnownAlignForTargetInstr(
12243   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12244   unsigned Depth) const {
12245   const MachineInstr *MI = MRI.getVRegDef(R);
12246   switch (MI->getOpcode()) {
12247   case AMDGPU::G_INTRINSIC:
12248   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12249     // FIXME: Can this move to generic code? What about the case where the call
12250     // site specifies a lower alignment?
12251     Intrinsic::ID IID = MI->getIntrinsicID();
12252     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12253     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12254     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12255       return *RetAlign;
12256     return Align(1);
12257   }
12258   default:
12259     return Align(1);
12260   }
12261 }
12262 
12263 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12264   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12265   const Align CacheLineAlign = Align(64);
12266 
12267   // Pre-GFX10 target did not benefit from loop alignment
12268   if (!ML || DisableLoopAlignment ||
12269       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12270       getSubtarget()->hasInstFwdPrefetchBug())
12271     return PrefAlign;
12272 
12273   // On GFX10 I$ is 4 x 64 bytes cache lines.
12274   // By default prefetcher keeps one cache line behind and reads two ahead.
12275   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12276   // behind and one ahead.
12277   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12278   // If loop fits 64 bytes it always spans no more than two cache lines and
12279   // does not need an alignment.
12280   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12281   // Else if loop is less or equal 192 bytes we need two lines behind.
12282 
12283   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12284   const MachineBasicBlock *Header = ML->getHeader();
12285   if (Header->getAlignment() != PrefAlign)
12286     return Header->getAlignment(); // Already processed.
12287 
12288   unsigned LoopSize = 0;
12289   for (const MachineBasicBlock *MBB : ML->blocks()) {
12290     // If inner loop block is aligned assume in average half of the alignment
12291     // size to be added as nops.
12292     if (MBB != Header)
12293       LoopSize += MBB->getAlignment().value() / 2;
12294 
12295     for (const MachineInstr &MI : *MBB) {
12296       LoopSize += TII->getInstSizeInBytes(MI);
12297       if (LoopSize > 192)
12298         return PrefAlign;
12299     }
12300   }
12301 
12302   if (LoopSize <= 64)
12303     return PrefAlign;
12304 
12305   if (LoopSize <= 128)
12306     return CacheLineAlign;
12307 
12308   // If any of parent loops is surrounded by prefetch instructions do not
12309   // insert new for inner loop, which would reset parent's settings.
12310   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12311     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12312       auto I = Exit->getFirstNonDebugInstr();
12313       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12314         return CacheLineAlign;
12315     }
12316   }
12317 
12318   MachineBasicBlock *Pre = ML->getLoopPreheader();
12319   MachineBasicBlock *Exit = ML->getExitBlock();
12320 
12321   if (Pre && Exit) {
12322     auto PreTerm = Pre->getFirstTerminator();
12323     if (PreTerm == Pre->begin() ||
12324         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12325       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12326           .addImm(1); // prefetch 2 lines behind PC
12327 
12328     auto ExitHead = Exit->getFirstNonDebugInstr();
12329     if (ExitHead == Exit->end() ||
12330         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12331       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12332           .addImm(2); // prefetch 1 line behind PC
12333   }
12334 
12335   return CacheLineAlign;
12336 }
12337 
12338 LLVM_ATTRIBUTE_UNUSED
12339 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12340   assert(N->getOpcode() == ISD::CopyFromReg);
12341   do {
12342     // Follow the chain until we find an INLINEASM node.
12343     N = N->getOperand(0).getNode();
12344     if (N->getOpcode() == ISD::INLINEASM ||
12345         N->getOpcode() == ISD::INLINEASM_BR)
12346       return true;
12347   } while (N->getOpcode() == ISD::CopyFromReg);
12348   return false;
12349 }
12350 
12351 bool SITargetLowering::isSDNodeSourceOfDivergence(
12352     const SDNode *N, FunctionLoweringInfo *FLI,
12353     LegacyDivergenceAnalysis *KDA) const {
12354   switch (N->getOpcode()) {
12355   case ISD::CopyFromReg: {
12356     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12357     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12358     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12359     Register Reg = R->getReg();
12360 
12361     // FIXME: Why does this need to consider isLiveIn?
12362     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12363       return !TRI->isSGPRReg(MRI, Reg);
12364 
12365     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12366       return KDA->isDivergent(V);
12367 
12368     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12369     return !TRI->isSGPRReg(MRI, Reg);
12370   }
12371   case ISD::LOAD: {
12372     const LoadSDNode *L = cast<LoadSDNode>(N);
12373     unsigned AS = L->getAddressSpace();
12374     // A flat load may access private memory.
12375     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12376   }
12377   case ISD::CALLSEQ_END:
12378     return true;
12379   case ISD::INTRINSIC_WO_CHAIN:
12380     return AMDGPU::isIntrinsicSourceOfDivergence(
12381         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12382   case ISD::INTRINSIC_W_CHAIN:
12383     return AMDGPU::isIntrinsicSourceOfDivergence(
12384         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12385   case AMDGPUISD::ATOMIC_CMP_SWAP:
12386   case AMDGPUISD::ATOMIC_INC:
12387   case AMDGPUISD::ATOMIC_DEC:
12388   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12389   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12390   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12391   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12392   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12393   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12394   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12395   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12396   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12397   case AMDGPUISD::BUFFER_ATOMIC_AND:
12398   case AMDGPUISD::BUFFER_ATOMIC_OR:
12399   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12400   case AMDGPUISD::BUFFER_ATOMIC_INC:
12401   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12402   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12403   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12404   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12405   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12406   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12407     // Target-specific read-modify-write atomics are sources of divergence.
12408     return true;
12409   default:
12410     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12411       // Generic read-modify-write atomics are sources of divergence.
12412       return A->readMem() && A->writeMem();
12413     }
12414     return false;
12415   }
12416 }
12417 
12418 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12419                                                EVT VT) const {
12420   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12421   case MVT::f32:
12422     return hasFP32Denormals(DAG.getMachineFunction());
12423   case MVT::f64:
12424   case MVT::f16:
12425     return hasFP64FP16Denormals(DAG.getMachineFunction());
12426   default:
12427     return false;
12428   }
12429 }
12430 
12431 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12432                                                MachineFunction &MF) const {
12433   switch (Ty.getScalarSizeInBits()) {
12434   case 32:
12435     return hasFP32Denormals(MF);
12436   case 64:
12437   case 16:
12438     return hasFP64FP16Denormals(MF);
12439   default:
12440     return false;
12441   }
12442 }
12443 
12444 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12445                                                     const SelectionDAG &DAG,
12446                                                     bool SNaN,
12447                                                     unsigned Depth) const {
12448   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12449     const MachineFunction &MF = DAG.getMachineFunction();
12450     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12451 
12452     if (Info->getMode().DX10Clamp)
12453       return true; // Clamped to 0.
12454     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12455   }
12456 
12457   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12458                                                             SNaN, Depth);
12459 }
12460 
12461 // Global FP atomic instructions have a hardcoded FP mode and do not support
12462 // FP32 denormals, and only support v2f16 denormals.
12463 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12464   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12465   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12466   if (&Flt == &APFloat::IEEEsingle())
12467     return DenormMode == DenormalMode::getPreserveSign();
12468   return DenormMode == DenormalMode::getIEEE();
12469 }
12470 
12471 TargetLowering::AtomicExpansionKind
12472 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12473   unsigned AS = RMW->getPointerAddressSpace();
12474   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12475     return AtomicExpansionKind::NotAtomic;
12476 
12477   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12478     OptimizationRemarkEmitter ORE(RMW->getFunction());
12479     LLVMContext &Ctx = RMW->getFunction()->getContext();
12480     SmallVector<StringRef> SSNs;
12481     Ctx.getSyncScopeNames(SSNs);
12482     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12483                         ? "system"
12484                         : SSNs[RMW->getSyncScopeID()];
12485     ORE.emit([&]() {
12486       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12487              << "Hardware instruction generated for atomic "
12488              << RMW->getOperationName(RMW->getOperation())
12489              << " operation at memory scope " << MemScope
12490              << " due to an unsafe request.";
12491     });
12492     return Kind;
12493   };
12494 
12495   switch (RMW->getOperation()) {
12496   case AtomicRMWInst::FAdd: {
12497     Type *Ty = RMW->getType();
12498 
12499     // We don't have a way to support 16-bit atomics now, so just leave them
12500     // as-is.
12501     if (Ty->isHalfTy())
12502       return AtomicExpansionKind::None;
12503 
12504     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12505       return AtomicExpansionKind::CmpXChg;
12506 
12507     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12508          Subtarget->hasAtomicFaddInsts()) {
12509       if (Subtarget->hasGFX940Insts())
12510         return AtomicExpansionKind::None;
12511 
12512       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12513       // floating point atomic instructions. May generate more efficient code,
12514       // but may not respect rounding and denormal modes, and may give incorrect
12515       // results for certain memory destinations.
12516       if (RMW->getFunction()
12517               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12518               .getValueAsString() != "true")
12519         return AtomicExpansionKind::CmpXChg;
12520 
12521       if (Subtarget->hasGFX90AInsts()) {
12522         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12523           return AtomicExpansionKind::CmpXChg;
12524 
12525         auto SSID = RMW->getSyncScopeID();
12526         if (SSID == SyncScope::System ||
12527             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12528           return AtomicExpansionKind::CmpXChg;
12529 
12530         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12531       }
12532 
12533       if (AS == AMDGPUAS::FLAT_ADDRESS)
12534         return AtomicExpansionKind::CmpXChg;
12535 
12536       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12537                               : AtomicExpansionKind::CmpXChg;
12538     }
12539 
12540     // DS FP atomics do respect the denormal mode, but the rounding mode is
12541     // fixed to round-to-nearest-even.
12542     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12543     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12544       if (!Ty->isDoubleTy())
12545         return AtomicExpansionKind::None;
12546 
12547       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12548         return AtomicExpansionKind::None;
12549 
12550       return RMW->getFunction()
12551                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12552                          .getValueAsString() == "true"
12553                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12554                  : AtomicExpansionKind::CmpXChg;
12555     }
12556 
12557     return AtomicExpansionKind::CmpXChg;
12558   }
12559   default:
12560     break;
12561   }
12562 
12563   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12564 }
12565 
12566 TargetLowering::AtomicExpansionKind
12567 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12568   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12569              ? AtomicExpansionKind::NotAtomic
12570              : AtomicExpansionKind::None;
12571 }
12572 
12573 TargetLowering::AtomicExpansionKind
12574 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12575   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12576              ? AtomicExpansionKind::NotAtomic
12577              : AtomicExpansionKind::None;
12578 }
12579 
12580 TargetLowering::AtomicExpansionKind
12581 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12582   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12583              ? AtomicExpansionKind::NotAtomic
12584              : AtomicExpansionKind::None;
12585 }
12586 
12587 const TargetRegisterClass *
12588 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12589   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12590   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12591   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12592     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12593                                                : &AMDGPU::SReg_32RegClass;
12594   if (!TRI->isSGPRClass(RC) && !isDivergent)
12595     return TRI->getEquivalentSGPRClass(RC);
12596   else if (TRI->isSGPRClass(RC) && isDivergent)
12597     return TRI->getEquivalentVGPRClass(RC);
12598 
12599   return RC;
12600 }
12601 
12602 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12603 // uniform values (as produced by the mask results of control flow intrinsics)
12604 // used outside of divergent blocks. The phi users need to also be treated as
12605 // always uniform.
12606 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12607                       unsigned WaveSize) {
12608   // FIXME: We assume we never cast the mask results of a control flow
12609   // intrinsic.
12610   // Early exit if the type won't be consistent as a compile time hack.
12611   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12612   if (!IT || IT->getBitWidth() != WaveSize)
12613     return false;
12614 
12615   if (!isa<Instruction>(V))
12616     return false;
12617   if (!Visited.insert(V).second)
12618     return false;
12619   bool Result = false;
12620   for (auto U : V->users()) {
12621     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12622       if (V == U->getOperand(1)) {
12623         switch (Intrinsic->getIntrinsicID()) {
12624         default:
12625           Result = false;
12626           break;
12627         case Intrinsic::amdgcn_if_break:
12628         case Intrinsic::amdgcn_if:
12629         case Intrinsic::amdgcn_else:
12630           Result = true;
12631           break;
12632         }
12633       }
12634       if (V == U->getOperand(0)) {
12635         switch (Intrinsic->getIntrinsicID()) {
12636         default:
12637           Result = false;
12638           break;
12639         case Intrinsic::amdgcn_end_cf:
12640         case Intrinsic::amdgcn_loop:
12641           Result = true;
12642           break;
12643         }
12644       }
12645     } else {
12646       Result = hasCFUser(U, Visited, WaveSize);
12647     }
12648     if (Result)
12649       break;
12650   }
12651   return Result;
12652 }
12653 
12654 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12655                                                const Value *V) const {
12656   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12657     if (CI->isInlineAsm()) {
12658       // FIXME: This cannot give a correct answer. This should only trigger in
12659       // the case where inline asm returns mixed SGPR and VGPR results, used
12660       // outside the defining block. We don't have a specific result to
12661       // consider, so this assumes if any value is SGPR, the overall register
12662       // also needs to be SGPR.
12663       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12664       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12665           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12666       for (auto &TC : TargetConstraints) {
12667         if (TC.Type == InlineAsm::isOutput) {
12668           ComputeConstraintToUse(TC, SDValue());
12669           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12670               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12671           if (RC && SIRI->isSGPRClass(RC))
12672             return true;
12673         }
12674       }
12675     }
12676   }
12677   SmallPtrSet<const Value *, 16> Visited;
12678   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12679 }
12680 
12681 std::pair<InstructionCost, MVT>
12682 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12683                                           Type *Ty) const {
12684   std::pair<InstructionCost, MVT> Cost =
12685       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12686   auto Size = DL.getTypeSizeInBits(Ty);
12687   // Maximum load or store can handle 8 dwords for scalar and 4 for
12688   // vector ALU. Let's assume anything above 8 dwords is expensive
12689   // even if legal.
12690   if (Size <= 256)
12691     return Cost;
12692 
12693   Cost.first += (Size + 255) / 256;
12694   return Cost;
12695 }
12696 
12697 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12698   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12699   for (; I != E; ++I) {
12700     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12701       if (getBasePtrIndex(M) == I.getOperandNo())
12702         return true;
12703     }
12704   }
12705   return false;
12706 }
12707 
12708 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12709                                            SDValue N1) const {
12710   if (!N0.hasOneUse())
12711     return false;
12712   // Take care of the opportunity to keep N0 uniform
12713   if (N0->isDivergent() || !N1->isDivergent())
12714     return true;
12715   // Check if we have a good chance to form the memory access pattern with the
12716   // base and offset
12717   return (DAG.isBaseWithConstantOffset(N0) &&
12718           hasMemSDNodeUser(*N0->use_begin()));
12719 }
12720 
12721 MachineMemOperand::Flags
12722 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12723   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12724   if (I.getMetadata("amdgpu.noclobber"))
12725     return MONoClobber;
12726   return MachineMemOperand::MONone;
12727 }
12728