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, Expand);
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     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1520     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1521         Alignment < RequiredAlignment)
1522       return false;
1523 
1524     // Check if alignment requirements for ds_read/write instructions are
1525     // disabled.
1526     if (Subtarget->hasUnalignedDSAccessEnabled()) {
1527       if (IsFast)
1528         *IsFast = Alignment != Align(2);
1529       return true;
1530     }
1531 
1532     // Either, the alignment requirements are "enabled", or there is an
1533     // unaligned LDS access related hardware bug though alignment requirements
1534     // are "disabled". In either case, we need to check for proper alignment
1535     // requirements.
1536     //
1537     if (Size == 64) {
1538       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1539       // address is negative, then the instruction is incorrectly treated as
1540       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1541       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1542       // load later in the SILoadStoreOptimizer.
1543       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1544         return false;
1545 
1546       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1547       // can do a 4 byte aligned, 8 byte access in a single operation using
1548       // ds_read2/write2_b32 with adjacent offsets.
1549       bool AlignedBy4 = Alignment >= Align(4);
1550       if (IsFast)
1551         *IsFast = AlignedBy4;
1552 
1553       return AlignedBy4;
1554     }
1555     if (Size == 96) {
1556       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1557       // gfx8 and older.
1558       bool AlignedBy16 = Alignment >= Align(16);
1559       if (IsFast)
1560         *IsFast = AlignedBy16;
1561 
1562       return AlignedBy16;
1563     }
1564     if (Size == 128) {
1565       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1566       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1567       // single operation using ds_read2/write2_b64.
1568       bool AlignedBy8 = Alignment >= Align(8);
1569       if (IsFast)
1570         *IsFast = AlignedBy8;
1571 
1572       return AlignedBy8;
1573     }
1574   }
1575 
1576   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1577     bool AlignedBy4 = Alignment >= Align(4);
1578     if (IsFast)
1579       *IsFast = AlignedBy4;
1580 
1581     return AlignedBy4 ||
1582            Subtarget->enableFlatScratch() ||
1583            Subtarget->hasUnalignedScratchAccess();
1584   }
1585 
1586   // FIXME: We have to be conservative here and assume that flat operations
1587   // will access scratch.  If we had access to the IR function, then we
1588   // could determine if any private memory was used in the function.
1589   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1590       !Subtarget->hasUnalignedScratchAccess()) {
1591     bool AlignedBy4 = Alignment >= Align(4);
1592     if (IsFast)
1593       *IsFast = AlignedBy4;
1594 
1595     return AlignedBy4;
1596   }
1597 
1598   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1599       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1600         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1601     // If we have a uniform constant load, it still requires using a slow
1602     // buffer instruction if unaligned.
1603     if (IsFast) {
1604       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1605       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1606       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1607                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1608         Alignment >= Align(4) : Alignment != Align(2);
1609     }
1610 
1611     return true;
1612   }
1613 
1614   // Smaller than dword value must be aligned.
1615   if (Size < 32)
1616     return false;
1617 
1618   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1619   // byte-address are ignored, thus forcing Dword alignment.
1620   // This applies to private, global, and constant memory.
1621   if (IsFast)
1622     *IsFast = true;
1623 
1624   return Size >= 32 && Alignment >= Align(4);
1625 }
1626 
1627 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1628     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1629     bool *IsFast) const {
1630   if (IsFast)
1631     *IsFast = false;
1632 
1633   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1634   // which isn't a simple VT.
1635   // Until MVT is extended to handle this, simply check for the size and
1636   // rely on the condition below: allow accesses if the size is a multiple of 4.
1637   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1638                            VT.getStoreSize() > 16)) {
1639     return false;
1640   }
1641 
1642   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1643                                             Alignment, Flags, IsFast);
1644 }
1645 
1646 EVT SITargetLowering::getOptimalMemOpType(
1647     const MemOp &Op, const AttributeList &FuncAttributes) const {
1648   // FIXME: Should account for address space here.
1649 
1650   // The default fallback uses the private pointer size as a guess for a type to
1651   // use. Make sure we switch these to 64-bit accesses.
1652 
1653   if (Op.size() >= 16 &&
1654       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1655     return MVT::v4i32;
1656 
1657   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1658     return MVT::v2i32;
1659 
1660   // Use the default.
1661   return MVT::Other;
1662 }
1663 
1664 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1665   const MemSDNode *MemNode = cast<MemSDNode>(N);
1666   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1667 }
1668 
1669 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1670   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1671          AS == AMDGPUAS::PRIVATE_ADDRESS;
1672 }
1673 
1674 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1675                                            unsigned DestAS) const {
1676   // Flat -> private/local is a simple truncate.
1677   // Flat -> global is no-op
1678   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1679     return true;
1680 
1681   const GCNTargetMachine &TM =
1682       static_cast<const GCNTargetMachine &>(getTargetMachine());
1683   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1684 }
1685 
1686 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1687   const MemSDNode *MemNode = cast<MemSDNode>(N);
1688 
1689   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1690 }
1691 
1692 TargetLoweringBase::LegalizeTypeAction
1693 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1694   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1695       VT.getScalarType().bitsLE(MVT::i16))
1696     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1697   return TargetLoweringBase::getPreferredVectorAction(VT);
1698 }
1699 
1700 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1701                                                          Type *Ty) const {
1702   // FIXME: Could be smarter if called for vector constants.
1703   return true;
1704 }
1705 
1706 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1707   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1708     switch (Op) {
1709     case ISD::LOAD:
1710     case ISD::STORE:
1711 
1712     // These operations are done with 32-bit instructions anyway.
1713     case ISD::AND:
1714     case ISD::OR:
1715     case ISD::XOR:
1716     case ISD::SELECT:
1717       // TODO: Extensions?
1718       return true;
1719     default:
1720       return false;
1721     }
1722   }
1723 
1724   // SimplifySetCC uses this function to determine whether or not it should
1725   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1726   if (VT == MVT::i1 && Op == ISD::SETCC)
1727     return false;
1728 
1729   return TargetLowering::isTypeDesirableForOp(Op, VT);
1730 }
1731 
1732 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1733                                                    const SDLoc &SL,
1734                                                    SDValue Chain,
1735                                                    uint64_t Offset) const {
1736   const DataLayout &DL = DAG.getDataLayout();
1737   MachineFunction &MF = DAG.getMachineFunction();
1738   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1739 
1740   const ArgDescriptor *InputPtrReg;
1741   const TargetRegisterClass *RC;
1742   LLT ArgTy;
1743   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1744 
1745   std::tie(InputPtrReg, RC, ArgTy) =
1746       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1747 
1748   // We may not have the kernarg segment argument if we have no kernel
1749   // arguments.
1750   if (!InputPtrReg)
1751     return DAG.getConstant(0, SL, PtrVT);
1752 
1753   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1754   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1755     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1756 
1757   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1758 }
1759 
1760 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1761                                             const SDLoc &SL) const {
1762   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1763                                                FIRST_IMPLICIT);
1764   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1765 }
1766 
1767 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1768                                          const SDLoc &SL, SDValue Val,
1769                                          bool Signed,
1770                                          const ISD::InputArg *Arg) const {
1771   // First, if it is a widened vector, narrow it.
1772   if (VT.isVector() &&
1773       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1774     EVT NarrowedVT =
1775         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1776                          VT.getVectorNumElements());
1777     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1778                       DAG.getConstant(0, SL, MVT::i32));
1779   }
1780 
1781   // Then convert the vector elements or scalar value.
1782   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1783       VT.bitsLT(MemVT)) {
1784     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1785     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1786   }
1787 
1788   if (MemVT.isFloatingPoint())
1789     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1790   else if (Signed)
1791     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1792   else
1793     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1794 
1795   return Val;
1796 }
1797 
1798 SDValue SITargetLowering::lowerKernargMemParameter(
1799     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1800     uint64_t Offset, Align Alignment, bool Signed,
1801     const ISD::InputArg *Arg) const {
1802   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1803 
1804   // Try to avoid using an extload by loading earlier than the argument address,
1805   // and extracting the relevant bits. The load should hopefully be merged with
1806   // the previous argument.
1807   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1808     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1809     int64_t AlignDownOffset = alignDown(Offset, 4);
1810     int64_t OffsetDiff = Offset - AlignDownOffset;
1811 
1812     EVT IntVT = MemVT.changeTypeToInteger();
1813 
1814     // TODO: If we passed in the base kernel offset we could have a better
1815     // alignment than 4, but we don't really need it.
1816     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1817     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1818                                MachineMemOperand::MODereferenceable |
1819                                    MachineMemOperand::MOInvariant);
1820 
1821     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1822     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1823 
1824     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1825     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1826     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1827 
1828 
1829     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1830   }
1831 
1832   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1833   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1834                              MachineMemOperand::MODereferenceable |
1835                                  MachineMemOperand::MOInvariant);
1836 
1837   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1838   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1839 }
1840 
1841 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1842                                               const SDLoc &SL, SDValue Chain,
1843                                               const ISD::InputArg &Arg) const {
1844   MachineFunction &MF = DAG.getMachineFunction();
1845   MachineFrameInfo &MFI = MF.getFrameInfo();
1846 
1847   if (Arg.Flags.isByVal()) {
1848     unsigned Size = Arg.Flags.getByValSize();
1849     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1850     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1851   }
1852 
1853   unsigned ArgOffset = VA.getLocMemOffset();
1854   unsigned ArgSize = VA.getValVT().getStoreSize();
1855 
1856   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1857 
1858   // Create load nodes to retrieve arguments from the stack.
1859   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1860   SDValue ArgValue;
1861 
1862   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1863   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1864   MVT MemVT = VA.getValVT();
1865 
1866   switch (VA.getLocInfo()) {
1867   default:
1868     break;
1869   case CCValAssign::BCvt:
1870     MemVT = VA.getLocVT();
1871     break;
1872   case CCValAssign::SExt:
1873     ExtType = ISD::SEXTLOAD;
1874     break;
1875   case CCValAssign::ZExt:
1876     ExtType = ISD::ZEXTLOAD;
1877     break;
1878   case CCValAssign::AExt:
1879     ExtType = ISD::EXTLOAD;
1880     break;
1881   }
1882 
1883   ArgValue = DAG.getExtLoad(
1884     ExtType, SL, VA.getLocVT(), Chain, FIN,
1885     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1886     MemVT);
1887   return ArgValue;
1888 }
1889 
1890 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1891   const SIMachineFunctionInfo &MFI,
1892   EVT VT,
1893   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1894   const ArgDescriptor *Reg;
1895   const TargetRegisterClass *RC;
1896   LLT Ty;
1897 
1898   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1899   if (!Reg) {
1900     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1901       // It's possible for a kernarg intrinsic call to appear in a kernel with
1902       // no allocated segment, in which case we do not add the user sgpr
1903       // argument, so just return null.
1904       return DAG.getConstant(0, SDLoc(), VT);
1905     }
1906 
1907     // It's undefined behavior if a function marked with the amdgpu-no-*
1908     // attributes uses the corresponding intrinsic.
1909     return DAG.getUNDEF(VT);
1910   }
1911 
1912   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1913 }
1914 
1915 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1916                                CallingConv::ID CallConv,
1917                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1918                                FunctionType *FType,
1919                                SIMachineFunctionInfo *Info) {
1920   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1921     const ISD::InputArg *Arg = &Ins[I];
1922 
1923     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1924            "vector type argument should have been split");
1925 
1926     // First check if it's a PS input addr.
1927     if (CallConv == CallingConv::AMDGPU_PS &&
1928         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1929       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1930 
1931       // Inconveniently only the first part of the split is marked as isSplit,
1932       // so skip to the end. We only want to increment PSInputNum once for the
1933       // entire split argument.
1934       if (Arg->Flags.isSplit()) {
1935         while (!Arg->Flags.isSplitEnd()) {
1936           assert((!Arg->VT.isVector() ||
1937                   Arg->VT.getScalarSizeInBits() == 16) &&
1938                  "unexpected vector split in ps argument type");
1939           if (!SkipArg)
1940             Splits.push_back(*Arg);
1941           Arg = &Ins[++I];
1942         }
1943       }
1944 
1945       if (SkipArg) {
1946         // We can safely skip PS inputs.
1947         Skipped.set(Arg->getOrigArgIndex());
1948         ++PSInputNum;
1949         continue;
1950       }
1951 
1952       Info->markPSInputAllocated(PSInputNum);
1953       if (Arg->Used)
1954         Info->markPSInputEnabled(PSInputNum);
1955 
1956       ++PSInputNum;
1957     }
1958 
1959     Splits.push_back(*Arg);
1960   }
1961 }
1962 
1963 // Allocate special inputs passed in VGPRs.
1964 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1965                                                       MachineFunction &MF,
1966                                                       const SIRegisterInfo &TRI,
1967                                                       SIMachineFunctionInfo &Info) const {
1968   const LLT S32 = LLT::scalar(32);
1969   MachineRegisterInfo &MRI = MF.getRegInfo();
1970 
1971   if (Info.hasWorkItemIDX()) {
1972     Register Reg = AMDGPU::VGPR0;
1973     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1974 
1975     CCInfo.AllocateReg(Reg);
1976     unsigned Mask = (Subtarget->hasPackedTID() &&
1977                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1978     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1979   }
1980 
1981   if (Info.hasWorkItemIDY()) {
1982     assert(Info.hasWorkItemIDX());
1983     if (Subtarget->hasPackedTID()) {
1984       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1985                                                         0x3ff << 10));
1986     } else {
1987       unsigned Reg = AMDGPU::VGPR1;
1988       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1989 
1990       CCInfo.AllocateReg(Reg);
1991       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1992     }
1993   }
1994 
1995   if (Info.hasWorkItemIDZ()) {
1996     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1997     if (Subtarget->hasPackedTID()) {
1998       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1999                                                         0x3ff << 20));
2000     } else {
2001       unsigned Reg = AMDGPU::VGPR2;
2002       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2003 
2004       CCInfo.AllocateReg(Reg);
2005       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2006     }
2007   }
2008 }
2009 
2010 // Try to allocate a VGPR at the end of the argument list, or if no argument
2011 // VGPRs are left allocating a stack slot.
2012 // If \p Mask is is given it indicates bitfield position in the register.
2013 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2014 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2015                                          ArgDescriptor Arg = ArgDescriptor()) {
2016   if (Arg.isSet())
2017     return ArgDescriptor::createArg(Arg, Mask);
2018 
2019   ArrayRef<MCPhysReg> ArgVGPRs
2020     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2021   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2022   if (RegIdx == ArgVGPRs.size()) {
2023     // Spill to stack required.
2024     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2025 
2026     return ArgDescriptor::createStack(Offset, Mask);
2027   }
2028 
2029   unsigned Reg = ArgVGPRs[RegIdx];
2030   Reg = CCInfo.AllocateReg(Reg);
2031   assert(Reg != AMDGPU::NoRegister);
2032 
2033   MachineFunction &MF = CCInfo.getMachineFunction();
2034   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2035   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2036   return ArgDescriptor::createRegister(Reg, Mask);
2037 }
2038 
2039 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2040                                              const TargetRegisterClass *RC,
2041                                              unsigned NumArgRegs) {
2042   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2043   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2044   if (RegIdx == ArgSGPRs.size())
2045     report_fatal_error("ran out of SGPRs for arguments");
2046 
2047   unsigned Reg = ArgSGPRs[RegIdx];
2048   Reg = CCInfo.AllocateReg(Reg);
2049   assert(Reg != AMDGPU::NoRegister);
2050 
2051   MachineFunction &MF = CCInfo.getMachineFunction();
2052   MF.addLiveIn(Reg, RC);
2053   return ArgDescriptor::createRegister(Reg);
2054 }
2055 
2056 // If this has a fixed position, we still should allocate the register in the
2057 // CCInfo state. Technically we could get away with this for values passed
2058 // outside of the normal argument range.
2059 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2060                                        const TargetRegisterClass *RC,
2061                                        MCRegister Reg) {
2062   Reg = CCInfo.AllocateReg(Reg);
2063   assert(Reg != AMDGPU::NoRegister);
2064   MachineFunction &MF = CCInfo.getMachineFunction();
2065   MF.addLiveIn(Reg, RC);
2066 }
2067 
2068 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2069   if (Arg) {
2070     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2071                                Arg.getRegister());
2072   } else
2073     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2074 }
2075 
2076 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2077   if (Arg) {
2078     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2079                                Arg.getRegister());
2080   } else
2081     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2082 }
2083 
2084 /// Allocate implicit function VGPR arguments at the end of allocated user
2085 /// arguments.
2086 void SITargetLowering::allocateSpecialInputVGPRs(
2087   CCState &CCInfo, MachineFunction &MF,
2088   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2089   const unsigned Mask = 0x3ff;
2090   ArgDescriptor Arg;
2091 
2092   if (Info.hasWorkItemIDX()) {
2093     Arg = allocateVGPR32Input(CCInfo, Mask);
2094     Info.setWorkItemIDX(Arg);
2095   }
2096 
2097   if (Info.hasWorkItemIDY()) {
2098     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2099     Info.setWorkItemIDY(Arg);
2100   }
2101 
2102   if (Info.hasWorkItemIDZ())
2103     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2104 }
2105 
2106 /// Allocate implicit function VGPR arguments in fixed registers.
2107 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2108   CCState &CCInfo, MachineFunction &MF,
2109   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2110   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2111   if (!Reg)
2112     report_fatal_error("failed to allocated VGPR for implicit arguments");
2113 
2114   const unsigned Mask = 0x3ff;
2115   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2116   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2117   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2118 }
2119 
2120 void SITargetLowering::allocateSpecialInputSGPRs(
2121   CCState &CCInfo,
2122   MachineFunction &MF,
2123   const SIRegisterInfo &TRI,
2124   SIMachineFunctionInfo &Info) const {
2125   auto &ArgInfo = Info.getArgInfo();
2126 
2127   // TODO: Unify handling with private memory pointers.
2128   if (Info.hasDispatchPtr())
2129     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2130 
2131   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2132     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2133 
2134   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2135   // constant offset from the kernarg segment.
2136   if (Info.hasImplicitArgPtr())
2137     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2138 
2139   if (Info.hasDispatchID())
2140     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2141 
2142   // flat_scratch_init is not applicable for non-kernel functions.
2143 
2144   if (Info.hasWorkGroupIDX())
2145     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2146 
2147   if (Info.hasWorkGroupIDY())
2148     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2149 
2150   if (Info.hasWorkGroupIDZ())
2151     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2152 }
2153 
2154 // Allocate special inputs passed in user SGPRs.
2155 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2156                                             MachineFunction &MF,
2157                                             const SIRegisterInfo &TRI,
2158                                             SIMachineFunctionInfo &Info) const {
2159   if (Info.hasImplicitBufferPtr()) {
2160     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2161     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2162     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2163   }
2164 
2165   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2166   if (Info.hasPrivateSegmentBuffer()) {
2167     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2168     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2169     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2170   }
2171 
2172   if (Info.hasDispatchPtr()) {
2173     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2174     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2175     CCInfo.AllocateReg(DispatchPtrReg);
2176   }
2177 
2178   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2179     Register QueuePtrReg = Info.addQueuePtr(TRI);
2180     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2181     CCInfo.AllocateReg(QueuePtrReg);
2182   }
2183 
2184   if (Info.hasKernargSegmentPtr()) {
2185     MachineRegisterInfo &MRI = MF.getRegInfo();
2186     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2187     CCInfo.AllocateReg(InputPtrReg);
2188 
2189     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2190     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2191   }
2192 
2193   if (Info.hasDispatchID()) {
2194     Register DispatchIDReg = Info.addDispatchID(TRI);
2195     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2196     CCInfo.AllocateReg(DispatchIDReg);
2197   }
2198 
2199   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2200     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2201     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2202     CCInfo.AllocateReg(FlatScratchInitReg);
2203   }
2204 
2205   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2206   // these from the dispatch pointer.
2207 }
2208 
2209 // Allocate special input registers that are initialized per-wave.
2210 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2211                                            MachineFunction &MF,
2212                                            SIMachineFunctionInfo &Info,
2213                                            CallingConv::ID CallConv,
2214                                            bool IsShader) const {
2215   if (Info.hasWorkGroupIDX()) {
2216     Register Reg = Info.addWorkGroupIDX();
2217     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2218     CCInfo.AllocateReg(Reg);
2219   }
2220 
2221   if (Info.hasWorkGroupIDY()) {
2222     Register Reg = Info.addWorkGroupIDY();
2223     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2224     CCInfo.AllocateReg(Reg);
2225   }
2226 
2227   if (Info.hasWorkGroupIDZ()) {
2228     Register Reg = Info.addWorkGroupIDZ();
2229     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2230     CCInfo.AllocateReg(Reg);
2231   }
2232 
2233   if (Info.hasWorkGroupInfo()) {
2234     Register Reg = Info.addWorkGroupInfo();
2235     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2236     CCInfo.AllocateReg(Reg);
2237   }
2238 
2239   if (Info.hasPrivateSegmentWaveByteOffset()) {
2240     // Scratch wave offset passed in system SGPR.
2241     unsigned PrivateSegmentWaveByteOffsetReg;
2242 
2243     if (IsShader) {
2244       PrivateSegmentWaveByteOffsetReg =
2245         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2246 
2247       // This is true if the scratch wave byte offset doesn't have a fixed
2248       // location.
2249       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2250         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2251         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2252       }
2253     } else
2254       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2255 
2256     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2257     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2258   }
2259 }
2260 
2261 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2262                                      MachineFunction &MF,
2263                                      const SIRegisterInfo &TRI,
2264                                      SIMachineFunctionInfo &Info) {
2265   // Now that we've figured out where the scratch register inputs are, see if
2266   // should reserve the arguments and use them directly.
2267   MachineFrameInfo &MFI = MF.getFrameInfo();
2268   bool HasStackObjects = MFI.hasStackObjects();
2269   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2270 
2271   // Record that we know we have non-spill stack objects so we don't need to
2272   // check all stack objects later.
2273   if (HasStackObjects)
2274     Info.setHasNonSpillStackObjects(true);
2275 
2276   // Everything live out of a block is spilled with fast regalloc, so it's
2277   // almost certain that spilling will be required.
2278   if (TM.getOptLevel() == CodeGenOpt::None)
2279     HasStackObjects = true;
2280 
2281   // For now assume stack access is needed in any callee functions, so we need
2282   // the scratch registers to pass in.
2283   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2284 
2285   if (!ST.enableFlatScratch()) {
2286     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2287       // If we have stack objects, we unquestionably need the private buffer
2288       // resource. For the Code Object V2 ABI, this will be the first 4 user
2289       // SGPR inputs. We can reserve those and use them directly.
2290 
2291       Register PrivateSegmentBufferReg =
2292           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2293       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2294     } else {
2295       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2296       // We tentatively reserve the last registers (skipping the last registers
2297       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2298       // we'll replace these with the ones immediately after those which were
2299       // really allocated. In the prologue copies will be inserted from the
2300       // argument to these reserved registers.
2301 
2302       // Without HSA, relocations are used for the scratch pointer and the
2303       // buffer resource setup is always inserted in the prologue. Scratch wave
2304       // offset is still in an input SGPR.
2305       Info.setScratchRSrcReg(ReservedBufferReg);
2306     }
2307   }
2308 
2309   MachineRegisterInfo &MRI = MF.getRegInfo();
2310 
2311   // For entry functions we have to set up the stack pointer if we use it,
2312   // whereas non-entry functions get this "for free". This means there is no
2313   // intrinsic advantage to using S32 over S34 in cases where we do not have
2314   // calls but do need a frame pointer (i.e. if we are requested to have one
2315   // because frame pointer elimination is disabled). To keep things simple we
2316   // only ever use S32 as the call ABI stack pointer, and so using it does not
2317   // imply we need a separate frame pointer.
2318   //
2319   // Try to use s32 as the SP, but move it if it would interfere with input
2320   // arguments. This won't work with calls though.
2321   //
2322   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2323   // registers.
2324   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2325     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2326   } else {
2327     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2328 
2329     if (MFI.hasCalls())
2330       report_fatal_error("call in graphics shader with too many input SGPRs");
2331 
2332     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2333       if (!MRI.isLiveIn(Reg)) {
2334         Info.setStackPtrOffsetReg(Reg);
2335         break;
2336       }
2337     }
2338 
2339     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2340       report_fatal_error("failed to find register for SP");
2341   }
2342 
2343   // hasFP should be accurate for entry functions even before the frame is
2344   // finalized, because it does not rely on the known stack size, only
2345   // properties like whether variable sized objects are present.
2346   if (ST.getFrameLowering()->hasFP(MF)) {
2347     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2348   }
2349 }
2350 
2351 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2352   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2353   return !Info->isEntryFunction();
2354 }
2355 
2356 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2357 
2358 }
2359 
2360 void SITargetLowering::insertCopiesSplitCSR(
2361   MachineBasicBlock *Entry,
2362   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2363   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2364 
2365   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2366   if (!IStart)
2367     return;
2368 
2369   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2370   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2371   MachineBasicBlock::iterator MBBI = Entry->begin();
2372   for (const MCPhysReg *I = IStart; *I; ++I) {
2373     const TargetRegisterClass *RC = nullptr;
2374     if (AMDGPU::SReg_64RegClass.contains(*I))
2375       RC = &AMDGPU::SGPR_64RegClass;
2376     else if (AMDGPU::SReg_32RegClass.contains(*I))
2377       RC = &AMDGPU::SGPR_32RegClass;
2378     else
2379       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2380 
2381     Register NewVR = MRI->createVirtualRegister(RC);
2382     // Create copy from CSR to a virtual register.
2383     Entry->addLiveIn(*I);
2384     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2385       .addReg(*I);
2386 
2387     // Insert the copy-back instructions right before the terminator.
2388     for (auto *Exit : Exits)
2389       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2390               TII->get(TargetOpcode::COPY), *I)
2391         .addReg(NewVR);
2392   }
2393 }
2394 
2395 SDValue SITargetLowering::LowerFormalArguments(
2396     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2397     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2398     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2399   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2400 
2401   MachineFunction &MF = DAG.getMachineFunction();
2402   const Function &Fn = MF.getFunction();
2403   FunctionType *FType = MF.getFunction().getFunctionType();
2404   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2405 
2406   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2407     DiagnosticInfoUnsupported NoGraphicsHSA(
2408         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2409     DAG.getContext()->diagnose(NoGraphicsHSA);
2410     return DAG.getEntryNode();
2411   }
2412 
2413   Info->allocateModuleLDSGlobal(Fn.getParent());
2414 
2415   SmallVector<ISD::InputArg, 16> Splits;
2416   SmallVector<CCValAssign, 16> ArgLocs;
2417   BitVector Skipped(Ins.size());
2418   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2419                  *DAG.getContext());
2420 
2421   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2422   bool IsKernel = AMDGPU::isKernel(CallConv);
2423   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2424 
2425   if (IsGraphics) {
2426     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2427            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2428            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2429            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2430            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2431            !Info->hasWorkItemIDZ());
2432   }
2433 
2434   if (CallConv == CallingConv::AMDGPU_PS) {
2435     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2436 
2437     // At least one interpolation mode must be enabled or else the GPU will
2438     // hang.
2439     //
2440     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2441     // set PSInputAddr, the user wants to enable some bits after the compilation
2442     // based on run-time states. Since we can't know what the final PSInputEna
2443     // will look like, so we shouldn't do anything here and the user should take
2444     // responsibility for the correct programming.
2445     //
2446     // Otherwise, the following restrictions apply:
2447     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2448     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2449     //   enabled too.
2450     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2451         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2452       CCInfo.AllocateReg(AMDGPU::VGPR0);
2453       CCInfo.AllocateReg(AMDGPU::VGPR1);
2454       Info->markPSInputAllocated(0);
2455       Info->markPSInputEnabled(0);
2456     }
2457     if (Subtarget->isAmdPalOS()) {
2458       // For isAmdPalOS, the user does not enable some bits after compilation
2459       // based on run-time states; the register values being generated here are
2460       // the final ones set in hardware. Therefore we need to apply the
2461       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2462       // a bit is set in PSInputAddr but not PSInputEnable is where the
2463       // frontend set up an input arg for a particular interpolation mode, but
2464       // nothing uses that input arg. Really we should have an earlier pass
2465       // that removes such an arg.)
2466       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2467       if ((PsInputBits & 0x7F) == 0 ||
2468           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2469         Info->markPSInputEnabled(
2470             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2471     }
2472   } else if (IsKernel) {
2473     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2474   } else {
2475     Splits.append(Ins.begin(), Ins.end());
2476   }
2477 
2478   if (IsEntryFunc) {
2479     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2480     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2481   } else if (!IsGraphics) {
2482     // For the fixed ABI, pass workitem IDs in the last argument register.
2483     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2484   }
2485 
2486   if (IsKernel) {
2487     analyzeFormalArgumentsCompute(CCInfo, Ins);
2488   } else {
2489     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2490     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2491   }
2492 
2493   SmallVector<SDValue, 16> Chains;
2494 
2495   // FIXME: This is the minimum kernel argument alignment. We should improve
2496   // this to the maximum alignment of the arguments.
2497   //
2498   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2499   // kern arg offset.
2500   const Align KernelArgBaseAlign = Align(16);
2501 
2502   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2503     const ISD::InputArg &Arg = Ins[i];
2504     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2505       InVals.push_back(DAG.getUNDEF(Arg.VT));
2506       continue;
2507     }
2508 
2509     CCValAssign &VA = ArgLocs[ArgIdx++];
2510     MVT VT = VA.getLocVT();
2511 
2512     if (IsEntryFunc && VA.isMemLoc()) {
2513       VT = Ins[i].VT;
2514       EVT MemVT = VA.getLocVT();
2515 
2516       const uint64_t Offset = VA.getLocMemOffset();
2517       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2518 
2519       if (Arg.Flags.isByRef()) {
2520         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2521 
2522         const GCNTargetMachine &TM =
2523             static_cast<const GCNTargetMachine &>(getTargetMachine());
2524         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2525                                     Arg.Flags.getPointerAddrSpace())) {
2526           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2527                                      Arg.Flags.getPointerAddrSpace());
2528         }
2529 
2530         InVals.push_back(Ptr);
2531         continue;
2532       }
2533 
2534       SDValue Arg = lowerKernargMemParameter(
2535         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2536       Chains.push_back(Arg.getValue(1));
2537 
2538       auto *ParamTy =
2539         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2540       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2541           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2542                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2543         // On SI local pointers are just offsets into LDS, so they are always
2544         // less than 16-bits.  On CI and newer they could potentially be
2545         // real pointers, so we can't guarantee their size.
2546         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2547                           DAG.getValueType(MVT::i16));
2548       }
2549 
2550       InVals.push_back(Arg);
2551       continue;
2552     } else if (!IsEntryFunc && VA.isMemLoc()) {
2553       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2554       InVals.push_back(Val);
2555       if (!Arg.Flags.isByVal())
2556         Chains.push_back(Val.getValue(1));
2557       continue;
2558     }
2559 
2560     assert(VA.isRegLoc() && "Parameter must be in a register!");
2561 
2562     Register Reg = VA.getLocReg();
2563     const TargetRegisterClass *RC = nullptr;
2564     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2565       RC = &AMDGPU::VGPR_32RegClass;
2566     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2567       RC = &AMDGPU::SGPR_32RegClass;
2568     else
2569       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2570     EVT ValVT = VA.getValVT();
2571 
2572     Reg = MF.addLiveIn(Reg, RC);
2573     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2574 
2575     if (Arg.Flags.isSRet()) {
2576       // The return object should be reasonably addressable.
2577 
2578       // FIXME: This helps when the return is a real sret. If it is a
2579       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2580       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2581       unsigned NumBits
2582         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2583       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2584         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2585     }
2586 
2587     // If this is an 8 or 16-bit value, it is really passed promoted
2588     // to 32 bits. Insert an assert[sz]ext to capture this, then
2589     // truncate to the right size.
2590     switch (VA.getLocInfo()) {
2591     case CCValAssign::Full:
2592       break;
2593     case CCValAssign::BCvt:
2594       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2595       break;
2596     case CCValAssign::SExt:
2597       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2598                         DAG.getValueType(ValVT));
2599       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2600       break;
2601     case CCValAssign::ZExt:
2602       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2603                         DAG.getValueType(ValVT));
2604       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2605       break;
2606     case CCValAssign::AExt:
2607       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2608       break;
2609     default:
2610       llvm_unreachable("Unknown loc info!");
2611     }
2612 
2613     InVals.push_back(Val);
2614   }
2615 
2616   // Start adding system SGPRs.
2617   if (IsEntryFunc) {
2618     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2619   } else {
2620     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2621     if (!IsGraphics)
2622       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2623   }
2624 
2625   auto &ArgUsageInfo =
2626     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2627   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2628 
2629   unsigned StackArgSize = CCInfo.getNextStackOffset();
2630   Info->setBytesInStackArgArea(StackArgSize);
2631 
2632   return Chains.empty() ? Chain :
2633     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2634 }
2635 
2636 // TODO: If return values can't fit in registers, we should return as many as
2637 // possible in registers before passing on stack.
2638 bool SITargetLowering::CanLowerReturn(
2639   CallingConv::ID CallConv,
2640   MachineFunction &MF, bool IsVarArg,
2641   const SmallVectorImpl<ISD::OutputArg> &Outs,
2642   LLVMContext &Context) const {
2643   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2644   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2645   // for shaders. Vector types should be explicitly handled by CC.
2646   if (AMDGPU::isEntryFunctionCC(CallConv))
2647     return true;
2648 
2649   SmallVector<CCValAssign, 16> RVLocs;
2650   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2651   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2652 }
2653 
2654 SDValue
2655 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2656                               bool isVarArg,
2657                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2658                               const SmallVectorImpl<SDValue> &OutVals,
2659                               const SDLoc &DL, SelectionDAG &DAG) const {
2660   MachineFunction &MF = DAG.getMachineFunction();
2661   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2662 
2663   if (AMDGPU::isKernel(CallConv)) {
2664     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2665                                              OutVals, DL, DAG);
2666   }
2667 
2668   bool IsShader = AMDGPU::isShader(CallConv);
2669 
2670   Info->setIfReturnsVoid(Outs.empty());
2671   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2672 
2673   // CCValAssign - represent the assignment of the return value to a location.
2674   SmallVector<CCValAssign, 48> RVLocs;
2675   SmallVector<ISD::OutputArg, 48> Splits;
2676 
2677   // CCState - Info about the registers and stack slots.
2678   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2679                  *DAG.getContext());
2680 
2681   // Analyze outgoing return values.
2682   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2683 
2684   SDValue Flag;
2685   SmallVector<SDValue, 48> RetOps;
2686   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2687 
2688   // Copy the result values into the output registers.
2689   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2690        ++I, ++RealRVLocIdx) {
2691     CCValAssign &VA = RVLocs[I];
2692     assert(VA.isRegLoc() && "Can only return in registers!");
2693     // TODO: Partially return in registers if return values don't fit.
2694     SDValue Arg = OutVals[RealRVLocIdx];
2695 
2696     // Copied from other backends.
2697     switch (VA.getLocInfo()) {
2698     case CCValAssign::Full:
2699       break;
2700     case CCValAssign::BCvt:
2701       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2702       break;
2703     case CCValAssign::SExt:
2704       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2705       break;
2706     case CCValAssign::ZExt:
2707       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2708       break;
2709     case CCValAssign::AExt:
2710       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2711       break;
2712     default:
2713       llvm_unreachable("Unknown loc info!");
2714     }
2715 
2716     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2717     Flag = Chain.getValue(1);
2718     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2719   }
2720 
2721   // FIXME: Does sret work properly?
2722   if (!Info->isEntryFunction()) {
2723     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2724     const MCPhysReg *I =
2725       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2726     if (I) {
2727       for (; *I; ++I) {
2728         if (AMDGPU::SReg_64RegClass.contains(*I))
2729           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2730         else if (AMDGPU::SReg_32RegClass.contains(*I))
2731           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2732         else
2733           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2734       }
2735     }
2736   }
2737 
2738   // Update chain and glue.
2739   RetOps[0] = Chain;
2740   if (Flag.getNode())
2741     RetOps.push_back(Flag);
2742 
2743   unsigned Opc = AMDGPUISD::ENDPGM;
2744   if (!IsWaveEnd)
2745     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2746   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2747 }
2748 
2749 SDValue SITargetLowering::LowerCallResult(
2750     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2751     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2752     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2753     SDValue ThisVal) const {
2754   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2755 
2756   // Assign locations to each value returned by this call.
2757   SmallVector<CCValAssign, 16> RVLocs;
2758   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2759                  *DAG.getContext());
2760   CCInfo.AnalyzeCallResult(Ins, RetCC);
2761 
2762   // Copy all of the result registers out of their specified physreg.
2763   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2764     CCValAssign VA = RVLocs[i];
2765     SDValue Val;
2766 
2767     if (VA.isRegLoc()) {
2768       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2769       Chain = Val.getValue(1);
2770       InFlag = Val.getValue(2);
2771     } else if (VA.isMemLoc()) {
2772       report_fatal_error("TODO: return values in memory");
2773     } else
2774       llvm_unreachable("unknown argument location type");
2775 
2776     switch (VA.getLocInfo()) {
2777     case CCValAssign::Full:
2778       break;
2779     case CCValAssign::BCvt:
2780       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2781       break;
2782     case CCValAssign::ZExt:
2783       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2784                         DAG.getValueType(VA.getValVT()));
2785       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2786       break;
2787     case CCValAssign::SExt:
2788       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2789                         DAG.getValueType(VA.getValVT()));
2790       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2791       break;
2792     case CCValAssign::AExt:
2793       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2794       break;
2795     default:
2796       llvm_unreachable("Unknown loc info!");
2797     }
2798 
2799     InVals.push_back(Val);
2800   }
2801 
2802   return Chain;
2803 }
2804 
2805 // Add code to pass special inputs required depending on used features separate
2806 // from the explicit user arguments present in the IR.
2807 void SITargetLowering::passSpecialInputs(
2808     CallLoweringInfo &CLI,
2809     CCState &CCInfo,
2810     const SIMachineFunctionInfo &Info,
2811     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2812     SmallVectorImpl<SDValue> &MemOpChains,
2813     SDValue Chain) const {
2814   // If we don't have a call site, this was a call inserted by
2815   // legalization. These can never use special inputs.
2816   if (!CLI.CB)
2817     return;
2818 
2819   SelectionDAG &DAG = CLI.DAG;
2820   const SDLoc &DL = CLI.DL;
2821   const Function &F = DAG.getMachineFunction().getFunction();
2822 
2823   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2824   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2825 
2826   const AMDGPUFunctionArgInfo *CalleeArgInfo
2827     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2828   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2829     auto &ArgUsageInfo =
2830       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2831     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2832   }
2833 
2834   // TODO: Unify with private memory register handling. This is complicated by
2835   // the fact that at least in kernels, the input argument is not necessarily
2836   // in the same location as the input.
2837   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2838                              StringLiteral> ImplicitAttrs[] = {
2839     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2840     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2841     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2842     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2843     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2844     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2845     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2846   };
2847 
2848   for (auto Attr : ImplicitAttrs) {
2849     const ArgDescriptor *OutgoingArg;
2850     const TargetRegisterClass *ArgRC;
2851     LLT ArgTy;
2852 
2853     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2854 
2855     // If the callee does not use the attribute value, skip copying the value.
2856     if (CLI.CB->hasFnAttr(Attr.second))
2857       continue;
2858 
2859     std::tie(OutgoingArg, ArgRC, ArgTy) =
2860         CalleeArgInfo->getPreloadedValue(InputID);
2861     if (!OutgoingArg)
2862       continue;
2863 
2864     const ArgDescriptor *IncomingArg;
2865     const TargetRegisterClass *IncomingArgRC;
2866     LLT Ty;
2867     std::tie(IncomingArg, IncomingArgRC, Ty) =
2868         CallerArgInfo.getPreloadedValue(InputID);
2869     assert(IncomingArgRC == ArgRC);
2870 
2871     // All special arguments are ints for now.
2872     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2873     SDValue InputReg;
2874 
2875     if (IncomingArg) {
2876       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2877     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2878       // The implicit arg ptr is special because it doesn't have a corresponding
2879       // input for kernels, and is computed from the kernarg segment pointer.
2880       InputReg = getImplicitArgPtr(DAG, DL);
2881     } else {
2882       // We may have proven the input wasn't needed, although the ABI is
2883       // requiring it. We just need to allocate the register appropriately.
2884       InputReg = DAG.getUNDEF(ArgVT);
2885     }
2886 
2887     if (OutgoingArg->isRegister()) {
2888       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2889       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2890         report_fatal_error("failed to allocate implicit input argument");
2891     } else {
2892       unsigned SpecialArgOffset =
2893           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2894       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2895                                               SpecialArgOffset);
2896       MemOpChains.push_back(ArgStore);
2897     }
2898   }
2899 
2900   // Pack workitem IDs into a single register or pass it as is if already
2901   // packed.
2902   const ArgDescriptor *OutgoingArg;
2903   const TargetRegisterClass *ArgRC;
2904   LLT Ty;
2905 
2906   std::tie(OutgoingArg, ArgRC, Ty) =
2907       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2908   if (!OutgoingArg)
2909     std::tie(OutgoingArg, ArgRC, Ty) =
2910         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2911   if (!OutgoingArg)
2912     std::tie(OutgoingArg, ArgRC, Ty) =
2913         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2914   if (!OutgoingArg)
2915     return;
2916 
2917   const ArgDescriptor *IncomingArgX = std::get<0>(
2918       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2919   const ArgDescriptor *IncomingArgY = std::get<0>(
2920       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2921   const ArgDescriptor *IncomingArgZ = std::get<0>(
2922       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2923 
2924   SDValue InputReg;
2925   SDLoc SL;
2926 
2927   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2928   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2929   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2930 
2931   // If incoming ids are not packed we need to pack them.
2932   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2933       NeedWorkItemIDX) {
2934     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2935       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2936     } else {
2937       InputReg = DAG.getConstant(0, DL, MVT::i32);
2938     }
2939   }
2940 
2941   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2942       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2943     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2944     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2945                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2946     InputReg = InputReg.getNode() ?
2947                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2948   }
2949 
2950   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2951       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2952     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2953     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2954                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2955     InputReg = InputReg.getNode() ?
2956                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2957   }
2958 
2959   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2960     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2961       // We're in a situation where the outgoing function requires the workitem
2962       // ID, but the calling function does not have it (e.g a graphics function
2963       // calling a C calling convention function). This is illegal, but we need
2964       // to produce something.
2965       InputReg = DAG.getUNDEF(MVT::i32);
2966     } else {
2967       // Workitem ids are already packed, any of present incoming arguments
2968       // will carry all required fields.
2969       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2970         IncomingArgX ? *IncomingArgX :
2971         IncomingArgY ? *IncomingArgY :
2972         *IncomingArgZ, ~0u);
2973       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2974     }
2975   }
2976 
2977   if (OutgoingArg->isRegister()) {
2978     if (InputReg)
2979       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2980 
2981     CCInfo.AllocateReg(OutgoingArg->getRegister());
2982   } else {
2983     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2984     if (InputReg) {
2985       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2986                                               SpecialArgOffset);
2987       MemOpChains.push_back(ArgStore);
2988     }
2989   }
2990 }
2991 
2992 static bool canGuaranteeTCO(CallingConv::ID CC) {
2993   return CC == CallingConv::Fast;
2994 }
2995 
2996 /// Return true if we might ever do TCO for calls with this calling convention.
2997 static bool mayTailCallThisCC(CallingConv::ID CC) {
2998   switch (CC) {
2999   case CallingConv::C:
3000   case CallingConv::AMDGPU_Gfx:
3001     return true;
3002   default:
3003     return canGuaranteeTCO(CC);
3004   }
3005 }
3006 
3007 bool SITargetLowering::isEligibleForTailCallOptimization(
3008     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3009     const SmallVectorImpl<ISD::OutputArg> &Outs,
3010     const SmallVectorImpl<SDValue> &OutVals,
3011     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3012   if (!mayTailCallThisCC(CalleeCC))
3013     return false;
3014 
3015   // For a divergent call target, we need to do a waterfall loop over the
3016   // possible callees which precludes us from using a simple jump.
3017   if (Callee->isDivergent())
3018     return false;
3019 
3020   MachineFunction &MF = DAG.getMachineFunction();
3021   const Function &CallerF = MF.getFunction();
3022   CallingConv::ID CallerCC = CallerF.getCallingConv();
3023   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3024   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3025 
3026   // Kernels aren't callable, and don't have a live in return address so it
3027   // doesn't make sense to do a tail call with entry functions.
3028   if (!CallerPreserved)
3029     return false;
3030 
3031   bool CCMatch = CallerCC == CalleeCC;
3032 
3033   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3034     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3035       return true;
3036     return false;
3037   }
3038 
3039   // TODO: Can we handle var args?
3040   if (IsVarArg)
3041     return false;
3042 
3043   for (const Argument &Arg : CallerF.args()) {
3044     if (Arg.hasByValAttr())
3045       return false;
3046   }
3047 
3048   LLVMContext &Ctx = *DAG.getContext();
3049 
3050   // Check that the call results are passed in the same way.
3051   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3052                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3053                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3054     return false;
3055 
3056   // The callee has to preserve all registers the caller needs to preserve.
3057   if (!CCMatch) {
3058     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3059     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3060       return false;
3061   }
3062 
3063   // Nothing more to check if the callee is taking no arguments.
3064   if (Outs.empty())
3065     return true;
3066 
3067   SmallVector<CCValAssign, 16> ArgLocs;
3068   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3069 
3070   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3071 
3072   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3073   // If the stack arguments for this call do not fit into our own save area then
3074   // the call cannot be made tail.
3075   // TODO: Is this really necessary?
3076   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3077     return false;
3078 
3079   const MachineRegisterInfo &MRI = MF.getRegInfo();
3080   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3081 }
3082 
3083 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3084   if (!CI->isTailCall())
3085     return false;
3086 
3087   const Function *ParentFn = CI->getParent()->getParent();
3088   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3089     return false;
3090   return true;
3091 }
3092 
3093 // The wave scratch offset register is used as the global base pointer.
3094 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3095                                     SmallVectorImpl<SDValue> &InVals) const {
3096   SelectionDAG &DAG = CLI.DAG;
3097   const SDLoc &DL = CLI.DL;
3098   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3099   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3100   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3101   SDValue Chain = CLI.Chain;
3102   SDValue Callee = CLI.Callee;
3103   bool &IsTailCall = CLI.IsTailCall;
3104   CallingConv::ID CallConv = CLI.CallConv;
3105   bool IsVarArg = CLI.IsVarArg;
3106   bool IsSibCall = false;
3107   bool IsThisReturn = false;
3108   MachineFunction &MF = DAG.getMachineFunction();
3109 
3110   if (Callee.isUndef() || isNullConstant(Callee)) {
3111     if (!CLI.IsTailCall) {
3112       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3113         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3114     }
3115 
3116     return Chain;
3117   }
3118 
3119   if (IsVarArg) {
3120     return lowerUnhandledCall(CLI, InVals,
3121                               "unsupported call to variadic function ");
3122   }
3123 
3124   if (!CLI.CB)
3125     report_fatal_error("unsupported libcall legalization");
3126 
3127   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3128     return lowerUnhandledCall(CLI, InVals,
3129                               "unsupported required tail call to function ");
3130   }
3131 
3132   if (AMDGPU::isShader(CallConv)) {
3133     // Note the issue is with the CC of the called function, not of the call
3134     // itself.
3135     return lowerUnhandledCall(CLI, InVals,
3136                               "unsupported call to a shader function ");
3137   }
3138 
3139   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3140       CallConv != CallingConv::AMDGPU_Gfx) {
3141     // Only allow calls with specific calling conventions.
3142     return lowerUnhandledCall(CLI, InVals,
3143                               "unsupported calling convention for call from "
3144                               "graphics shader of function ");
3145   }
3146 
3147   if (IsTailCall) {
3148     IsTailCall = isEligibleForTailCallOptimization(
3149       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3150     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3151       report_fatal_error("failed to perform tail call elimination on a call "
3152                          "site marked musttail");
3153     }
3154 
3155     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3156 
3157     // A sibling call is one where we're under the usual C ABI and not planning
3158     // to change that but can still do a tail call:
3159     if (!TailCallOpt && IsTailCall)
3160       IsSibCall = true;
3161 
3162     if (IsTailCall)
3163       ++NumTailCalls;
3164   }
3165 
3166   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3167   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3168   SmallVector<SDValue, 8> MemOpChains;
3169 
3170   // Analyze operands of the call, assigning locations to each operand.
3171   SmallVector<CCValAssign, 16> ArgLocs;
3172   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3173   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3174 
3175   if (CallConv != CallingConv::AMDGPU_Gfx) {
3176     // With a fixed ABI, allocate fixed registers before user arguments.
3177     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3178   }
3179 
3180   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3181 
3182   // Get a count of how many bytes are to be pushed on the stack.
3183   unsigned NumBytes = CCInfo.getNextStackOffset();
3184 
3185   if (IsSibCall) {
3186     // Since we're not changing the ABI to make this a tail call, the memory
3187     // operands are already available in the caller's incoming argument space.
3188     NumBytes = 0;
3189   }
3190 
3191   // FPDiff is the byte offset of the call's argument area from the callee's.
3192   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3193   // by this amount for a tail call. In a sibling call it must be 0 because the
3194   // caller will deallocate the entire stack and the callee still expects its
3195   // arguments to begin at SP+0. Completely unused for non-tail calls.
3196   int32_t FPDiff = 0;
3197   MachineFrameInfo &MFI = MF.getFrameInfo();
3198 
3199   // Adjust the stack pointer for the new arguments...
3200   // These operations are automatically eliminated by the prolog/epilog pass
3201   if (!IsSibCall) {
3202     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3203 
3204     if (!Subtarget->enableFlatScratch()) {
3205       SmallVector<SDValue, 4> CopyFromChains;
3206 
3207       // In the HSA case, this should be an identity copy.
3208       SDValue ScratchRSrcReg
3209         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3210       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3211       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3212       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3213     }
3214   }
3215 
3216   MVT PtrVT = MVT::i32;
3217 
3218   // Walk the register/memloc assignments, inserting copies/loads.
3219   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3220     CCValAssign &VA = ArgLocs[i];
3221     SDValue Arg = OutVals[i];
3222 
3223     // Promote the value if needed.
3224     switch (VA.getLocInfo()) {
3225     case CCValAssign::Full:
3226       break;
3227     case CCValAssign::BCvt:
3228       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3229       break;
3230     case CCValAssign::ZExt:
3231       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3232       break;
3233     case CCValAssign::SExt:
3234       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3235       break;
3236     case CCValAssign::AExt:
3237       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3238       break;
3239     case CCValAssign::FPExt:
3240       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3241       break;
3242     default:
3243       llvm_unreachable("Unknown loc info!");
3244     }
3245 
3246     if (VA.isRegLoc()) {
3247       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3248     } else {
3249       assert(VA.isMemLoc());
3250 
3251       SDValue DstAddr;
3252       MachinePointerInfo DstInfo;
3253 
3254       unsigned LocMemOffset = VA.getLocMemOffset();
3255       int32_t Offset = LocMemOffset;
3256 
3257       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3258       MaybeAlign Alignment;
3259 
3260       if (IsTailCall) {
3261         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3262         unsigned OpSize = Flags.isByVal() ?
3263           Flags.getByValSize() : VA.getValVT().getStoreSize();
3264 
3265         // FIXME: We can have better than the minimum byval required alignment.
3266         Alignment =
3267             Flags.isByVal()
3268                 ? Flags.getNonZeroByValAlign()
3269                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3270 
3271         Offset = Offset + FPDiff;
3272         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3273 
3274         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3275         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3276 
3277         // Make sure any stack arguments overlapping with where we're storing
3278         // are loaded before this eventual operation. Otherwise they'll be
3279         // clobbered.
3280 
3281         // FIXME: Why is this really necessary? This seems to just result in a
3282         // lot of code to copy the stack and write them back to the same
3283         // locations, which are supposed to be immutable?
3284         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3285       } else {
3286         // Stores to the argument stack area are relative to the stack pointer.
3287         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3288                                         MVT::i32);
3289         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3290         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3291         Alignment =
3292             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3293       }
3294 
3295       if (Outs[i].Flags.isByVal()) {
3296         SDValue SizeNode =
3297             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3298         SDValue Cpy =
3299             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3300                           Outs[i].Flags.getNonZeroByValAlign(),
3301                           /*isVol = */ false, /*AlwaysInline = */ true,
3302                           /*isTailCall = */ false, DstInfo,
3303                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3304 
3305         MemOpChains.push_back(Cpy);
3306       } else {
3307         SDValue Store =
3308             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3309         MemOpChains.push_back(Store);
3310       }
3311     }
3312   }
3313 
3314   if (!MemOpChains.empty())
3315     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3316 
3317   // Build a sequence of copy-to-reg nodes chained together with token chain
3318   // and flag operands which copy the outgoing args into the appropriate regs.
3319   SDValue InFlag;
3320   for (auto &RegToPass : RegsToPass) {
3321     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3322                              RegToPass.second, InFlag);
3323     InFlag = Chain.getValue(1);
3324   }
3325 
3326 
3327   // We don't usually want to end the call-sequence here because we would tidy
3328   // the frame up *after* the call, however in the ABI-changing tail-call case
3329   // we've carefully laid out the parameters so that when sp is reset they'll be
3330   // in the correct location.
3331   if (IsTailCall && !IsSibCall) {
3332     Chain = DAG.getCALLSEQ_END(Chain,
3333                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3334                                DAG.getTargetConstant(0, DL, MVT::i32),
3335                                InFlag, DL);
3336     InFlag = Chain.getValue(1);
3337   }
3338 
3339   std::vector<SDValue> Ops;
3340   Ops.push_back(Chain);
3341   Ops.push_back(Callee);
3342   // Add a redundant copy of the callee global which will not be legalized, as
3343   // we need direct access to the callee later.
3344   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3345     const GlobalValue *GV = GSD->getGlobal();
3346     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3347   } else {
3348     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3349   }
3350 
3351   if (IsTailCall) {
3352     // Each tail call may have to adjust the stack by a different amount, so
3353     // this information must travel along with the operation for eventual
3354     // consumption by emitEpilogue.
3355     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3356   }
3357 
3358   // Add argument registers to the end of the list so that they are known live
3359   // into the call.
3360   for (auto &RegToPass : RegsToPass) {
3361     Ops.push_back(DAG.getRegister(RegToPass.first,
3362                                   RegToPass.second.getValueType()));
3363   }
3364 
3365   // Add a register mask operand representing the call-preserved registers.
3366 
3367   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3368   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3369   assert(Mask && "Missing call preserved mask for calling convention");
3370   Ops.push_back(DAG.getRegisterMask(Mask));
3371 
3372   if (InFlag.getNode())
3373     Ops.push_back(InFlag);
3374 
3375   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3376 
3377   // If we're doing a tall call, use a TC_RETURN here rather than an
3378   // actual call instruction.
3379   if (IsTailCall) {
3380     MFI.setHasTailCall();
3381     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3382   }
3383 
3384   // Returns a chain and a flag for retval copy to use.
3385   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3386   Chain = Call.getValue(0);
3387   InFlag = Call.getValue(1);
3388 
3389   uint64_t CalleePopBytes = NumBytes;
3390   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3391                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3392                              InFlag, DL);
3393   if (!Ins.empty())
3394     InFlag = Chain.getValue(1);
3395 
3396   // Handle result values, copying them out of physregs into vregs that we
3397   // return.
3398   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3399                          InVals, IsThisReturn,
3400                          IsThisReturn ? OutVals[0] : SDValue());
3401 }
3402 
3403 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3404 // except for applying the wave size scale to the increment amount.
3405 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3406     SDValue Op, SelectionDAG &DAG) const {
3407   const MachineFunction &MF = DAG.getMachineFunction();
3408   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3409 
3410   SDLoc dl(Op);
3411   EVT VT = Op.getValueType();
3412   SDValue Tmp1 = Op;
3413   SDValue Tmp2 = Op.getValue(1);
3414   SDValue Tmp3 = Op.getOperand(2);
3415   SDValue Chain = Tmp1.getOperand(0);
3416 
3417   Register SPReg = Info->getStackPtrOffsetReg();
3418 
3419   // Chain the dynamic stack allocation so that it doesn't modify the stack
3420   // pointer when other instructions are using the stack.
3421   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3422 
3423   SDValue Size  = Tmp2.getOperand(1);
3424   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3425   Chain = SP.getValue(1);
3426   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3427   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3428   const TargetFrameLowering *TFL = ST.getFrameLowering();
3429   unsigned Opc =
3430     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3431     ISD::ADD : ISD::SUB;
3432 
3433   SDValue ScaledSize = DAG.getNode(
3434       ISD::SHL, dl, VT, Size,
3435       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3436 
3437   Align StackAlign = TFL->getStackAlign();
3438   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3439   if (Alignment && *Alignment > StackAlign) {
3440     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3441                        DAG.getConstant(-(uint64_t)Alignment->value()
3442                                            << ST.getWavefrontSizeLog2(),
3443                                        dl, VT));
3444   }
3445 
3446   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3447   Tmp2 = DAG.getCALLSEQ_END(
3448       Chain, DAG.getIntPtrConstant(0, dl, true),
3449       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3450 
3451   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3452 }
3453 
3454 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3455                                                   SelectionDAG &DAG) const {
3456   // We only handle constant sizes here to allow non-entry block, static sized
3457   // allocas. A truly dynamic value is more difficult to support because we
3458   // don't know if the size value is uniform or not. If the size isn't uniform,
3459   // we would need to do a wave reduction to get the maximum size to know how
3460   // much to increment the uniform stack pointer.
3461   SDValue Size = Op.getOperand(1);
3462   if (isa<ConstantSDNode>(Size))
3463       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3464 
3465   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3466 }
3467 
3468 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3469                                              const MachineFunction &MF) const {
3470   Register Reg = StringSwitch<Register>(RegName)
3471     .Case("m0", AMDGPU::M0)
3472     .Case("exec", AMDGPU::EXEC)
3473     .Case("exec_lo", AMDGPU::EXEC_LO)
3474     .Case("exec_hi", AMDGPU::EXEC_HI)
3475     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3476     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3477     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3478     .Default(Register());
3479 
3480   if (Reg == AMDGPU::NoRegister) {
3481     report_fatal_error(Twine("invalid register name \""
3482                              + StringRef(RegName)  + "\"."));
3483 
3484   }
3485 
3486   if (!Subtarget->hasFlatScrRegister() &&
3487        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3488     report_fatal_error(Twine("invalid register \""
3489                              + StringRef(RegName)  + "\" for subtarget."));
3490   }
3491 
3492   switch (Reg) {
3493   case AMDGPU::M0:
3494   case AMDGPU::EXEC_LO:
3495   case AMDGPU::EXEC_HI:
3496   case AMDGPU::FLAT_SCR_LO:
3497   case AMDGPU::FLAT_SCR_HI:
3498     if (VT.getSizeInBits() == 32)
3499       return Reg;
3500     break;
3501   case AMDGPU::EXEC:
3502   case AMDGPU::FLAT_SCR:
3503     if (VT.getSizeInBits() == 64)
3504       return Reg;
3505     break;
3506   default:
3507     llvm_unreachable("missing register type checking");
3508   }
3509 
3510   report_fatal_error(Twine("invalid type for register \""
3511                            + StringRef(RegName) + "\"."));
3512 }
3513 
3514 // If kill is not the last instruction, split the block so kill is always a
3515 // proper terminator.
3516 MachineBasicBlock *
3517 SITargetLowering::splitKillBlock(MachineInstr &MI,
3518                                  MachineBasicBlock *BB) const {
3519   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3520   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3521   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3522   return SplitBB;
3523 }
3524 
3525 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3526 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3527 // be the first instruction in the remainder block.
3528 //
3529 /// \returns { LoopBody, Remainder }
3530 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3531 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3532   MachineFunction *MF = MBB.getParent();
3533   MachineBasicBlock::iterator I(&MI);
3534 
3535   // To insert the loop we need to split the block. Move everything after this
3536   // point to a new block, and insert a new empty block between the two.
3537   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3538   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3539   MachineFunction::iterator MBBI(MBB);
3540   ++MBBI;
3541 
3542   MF->insert(MBBI, LoopBB);
3543   MF->insert(MBBI, RemainderBB);
3544 
3545   LoopBB->addSuccessor(LoopBB);
3546   LoopBB->addSuccessor(RemainderBB);
3547 
3548   // Move the rest of the block into a new block.
3549   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3550 
3551   if (InstInLoop) {
3552     auto Next = std::next(I);
3553 
3554     // Move instruction to loop body.
3555     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3556 
3557     // Move the rest of the block.
3558     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3559   } else {
3560     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3561   }
3562 
3563   MBB.addSuccessor(LoopBB);
3564 
3565   return std::make_pair(LoopBB, RemainderBB);
3566 }
3567 
3568 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3569 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3570   MachineBasicBlock *MBB = MI.getParent();
3571   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3572   auto I = MI.getIterator();
3573   auto E = std::next(I);
3574 
3575   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3576     .addImm(0);
3577 
3578   MIBundleBuilder Bundler(*MBB, I, E);
3579   finalizeBundle(*MBB, Bundler.begin());
3580 }
3581 
3582 MachineBasicBlock *
3583 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3584                                          MachineBasicBlock *BB) const {
3585   const DebugLoc &DL = MI.getDebugLoc();
3586 
3587   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3588 
3589   MachineBasicBlock *LoopBB;
3590   MachineBasicBlock *RemainderBB;
3591   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3592 
3593   // Apparently kill flags are only valid if the def is in the same block?
3594   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3595     Src->setIsKill(false);
3596 
3597   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3598 
3599   MachineBasicBlock::iterator I = LoopBB->end();
3600 
3601   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3602     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3603 
3604   // Clear TRAP_STS.MEM_VIOL
3605   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3606     .addImm(0)
3607     .addImm(EncodedReg);
3608 
3609   bundleInstWithWaitcnt(MI);
3610 
3611   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3612 
3613   // Load and check TRAP_STS.MEM_VIOL
3614   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3615     .addImm(EncodedReg);
3616 
3617   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3618   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3619     .addReg(Reg, RegState::Kill)
3620     .addImm(0);
3621   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3622     .addMBB(LoopBB);
3623 
3624   return RemainderBB;
3625 }
3626 
3627 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3628 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3629 // will only do one iteration. In the worst case, this will loop 64 times.
3630 //
3631 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3632 static MachineBasicBlock::iterator
3633 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3634                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3635                        const DebugLoc &DL, const MachineOperand &Idx,
3636                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3637                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3638                        Register &SGPRIdxReg) {
3639 
3640   MachineFunction *MF = OrigBB.getParent();
3641   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3642   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3643   MachineBasicBlock::iterator I = LoopBB.begin();
3644 
3645   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3646   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3647   Register NewExec = MRI.createVirtualRegister(BoolRC);
3648   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3649   Register CondReg = MRI.createVirtualRegister(BoolRC);
3650 
3651   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3652     .addReg(InitReg)
3653     .addMBB(&OrigBB)
3654     .addReg(ResultReg)
3655     .addMBB(&LoopBB);
3656 
3657   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3658     .addReg(InitSaveExecReg)
3659     .addMBB(&OrigBB)
3660     .addReg(NewExec)
3661     .addMBB(&LoopBB);
3662 
3663   // Read the next variant <- also loop target.
3664   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3665       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3666 
3667   // Compare the just read M0 value to all possible Idx values.
3668   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3669       .addReg(CurrentIdxReg)
3670       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3671 
3672   // Update EXEC, save the original EXEC value to VCC.
3673   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3674                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3675           NewExec)
3676     .addReg(CondReg, RegState::Kill);
3677 
3678   MRI.setSimpleHint(NewExec, CondReg);
3679 
3680   if (UseGPRIdxMode) {
3681     if (Offset == 0) {
3682       SGPRIdxReg = CurrentIdxReg;
3683     } else {
3684       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3685       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3686           .addReg(CurrentIdxReg, RegState::Kill)
3687           .addImm(Offset);
3688     }
3689   } else {
3690     // Move index from VCC into M0
3691     if (Offset == 0) {
3692       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3693         .addReg(CurrentIdxReg, RegState::Kill);
3694     } else {
3695       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3696         .addReg(CurrentIdxReg, RegState::Kill)
3697         .addImm(Offset);
3698     }
3699   }
3700 
3701   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3702   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3703   MachineInstr *InsertPt =
3704     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3705                                                   : AMDGPU::S_XOR_B64_term), Exec)
3706       .addReg(Exec)
3707       .addReg(NewExec);
3708 
3709   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3710   // s_cbranch_scc0?
3711 
3712   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3713   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3714     .addMBB(&LoopBB);
3715 
3716   return InsertPt->getIterator();
3717 }
3718 
3719 // This has slightly sub-optimal regalloc when the source vector is killed by
3720 // the read. The register allocator does not understand that the kill is
3721 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3722 // subregister from it, using 1 more VGPR than necessary. This was saved when
3723 // this was expanded after register allocation.
3724 static MachineBasicBlock::iterator
3725 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3726                unsigned InitResultReg, unsigned PhiReg, int Offset,
3727                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3728   MachineFunction *MF = MBB.getParent();
3729   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3730   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3731   MachineRegisterInfo &MRI = MF->getRegInfo();
3732   const DebugLoc &DL = MI.getDebugLoc();
3733   MachineBasicBlock::iterator I(&MI);
3734 
3735   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3736   Register DstReg = MI.getOperand(0).getReg();
3737   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3738   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3739   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3740   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3741 
3742   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3743 
3744   // Save the EXEC mask
3745   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3746     .addReg(Exec);
3747 
3748   MachineBasicBlock *LoopBB;
3749   MachineBasicBlock *RemainderBB;
3750   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3751 
3752   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3753 
3754   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3755                                       InitResultReg, DstReg, PhiReg, TmpExec,
3756                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3757 
3758   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3759   MachineFunction::iterator MBBI(LoopBB);
3760   ++MBBI;
3761   MF->insert(MBBI, LandingPad);
3762   LoopBB->removeSuccessor(RemainderBB);
3763   LandingPad->addSuccessor(RemainderBB);
3764   LoopBB->addSuccessor(LandingPad);
3765   MachineBasicBlock::iterator First = LandingPad->begin();
3766   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3767     .addReg(SaveExec);
3768 
3769   return InsPt;
3770 }
3771 
3772 // Returns subreg index, offset
3773 static std::pair<unsigned, int>
3774 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3775                             const TargetRegisterClass *SuperRC,
3776                             unsigned VecReg,
3777                             int Offset) {
3778   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3779 
3780   // Skip out of bounds offsets, or else we would end up using an undefined
3781   // register.
3782   if (Offset >= NumElts || Offset < 0)
3783     return std::make_pair(AMDGPU::sub0, Offset);
3784 
3785   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3786 }
3787 
3788 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3789                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3790                                  int Offset) {
3791   MachineBasicBlock *MBB = MI.getParent();
3792   const DebugLoc &DL = MI.getDebugLoc();
3793   MachineBasicBlock::iterator I(&MI);
3794 
3795   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3796 
3797   assert(Idx->getReg() != AMDGPU::NoRegister);
3798 
3799   if (Offset == 0) {
3800     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3801   } else {
3802     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3803         .add(*Idx)
3804         .addImm(Offset);
3805   }
3806 }
3807 
3808 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3809                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3810                                    int Offset) {
3811   MachineBasicBlock *MBB = MI.getParent();
3812   const DebugLoc &DL = MI.getDebugLoc();
3813   MachineBasicBlock::iterator I(&MI);
3814 
3815   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3816 
3817   if (Offset == 0)
3818     return Idx->getReg();
3819 
3820   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3821   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3822       .add(*Idx)
3823       .addImm(Offset);
3824   return Tmp;
3825 }
3826 
3827 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3828                                           MachineBasicBlock &MBB,
3829                                           const GCNSubtarget &ST) {
3830   const SIInstrInfo *TII = ST.getInstrInfo();
3831   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3832   MachineFunction *MF = MBB.getParent();
3833   MachineRegisterInfo &MRI = MF->getRegInfo();
3834 
3835   Register Dst = MI.getOperand(0).getReg();
3836   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3837   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3838   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3839 
3840   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3841   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3842 
3843   unsigned SubReg;
3844   std::tie(SubReg, Offset)
3845     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3846 
3847   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3848 
3849   // Check for a SGPR index.
3850   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3851     MachineBasicBlock::iterator I(&MI);
3852     const DebugLoc &DL = MI.getDebugLoc();
3853 
3854     if (UseGPRIdxMode) {
3855       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3856       // to avoid interfering with other uses, so probably requires a new
3857       // optimization pass.
3858       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3859 
3860       const MCInstrDesc &GPRIDXDesc =
3861           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3862       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3863           .addReg(SrcReg)
3864           .addReg(Idx)
3865           .addImm(SubReg);
3866     } else {
3867       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3868 
3869       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3870         .addReg(SrcReg, 0, SubReg)
3871         .addReg(SrcReg, RegState::Implicit);
3872     }
3873 
3874     MI.eraseFromParent();
3875 
3876     return &MBB;
3877   }
3878 
3879   // Control flow needs to be inserted if indexing with a VGPR.
3880   const DebugLoc &DL = MI.getDebugLoc();
3881   MachineBasicBlock::iterator I(&MI);
3882 
3883   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3884   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3885 
3886   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3887 
3888   Register SGPRIdxReg;
3889   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3890                               UseGPRIdxMode, SGPRIdxReg);
3891 
3892   MachineBasicBlock *LoopBB = InsPt->getParent();
3893 
3894   if (UseGPRIdxMode) {
3895     const MCInstrDesc &GPRIDXDesc =
3896         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3897 
3898     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3899         .addReg(SrcReg)
3900         .addReg(SGPRIdxReg)
3901         .addImm(SubReg);
3902   } else {
3903     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3904       .addReg(SrcReg, 0, SubReg)
3905       .addReg(SrcReg, RegState::Implicit);
3906   }
3907 
3908   MI.eraseFromParent();
3909 
3910   return LoopBB;
3911 }
3912 
3913 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3914                                           MachineBasicBlock &MBB,
3915                                           const GCNSubtarget &ST) {
3916   const SIInstrInfo *TII = ST.getInstrInfo();
3917   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3918   MachineFunction *MF = MBB.getParent();
3919   MachineRegisterInfo &MRI = MF->getRegInfo();
3920 
3921   Register Dst = MI.getOperand(0).getReg();
3922   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3923   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3924   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3925   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3926   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3927   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3928 
3929   // This can be an immediate, but will be folded later.
3930   assert(Val->getReg());
3931 
3932   unsigned SubReg;
3933   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3934                                                          SrcVec->getReg(),
3935                                                          Offset);
3936   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3937 
3938   if (Idx->getReg() == AMDGPU::NoRegister) {
3939     MachineBasicBlock::iterator I(&MI);
3940     const DebugLoc &DL = MI.getDebugLoc();
3941 
3942     assert(Offset == 0);
3943 
3944     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3945         .add(*SrcVec)
3946         .add(*Val)
3947         .addImm(SubReg);
3948 
3949     MI.eraseFromParent();
3950     return &MBB;
3951   }
3952 
3953   // Check for a SGPR index.
3954   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3955     MachineBasicBlock::iterator I(&MI);
3956     const DebugLoc &DL = MI.getDebugLoc();
3957 
3958     if (UseGPRIdxMode) {
3959       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3960 
3961       const MCInstrDesc &GPRIDXDesc =
3962           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3963       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3964           .addReg(SrcVec->getReg())
3965           .add(*Val)
3966           .addReg(Idx)
3967           .addImm(SubReg);
3968     } else {
3969       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3970 
3971       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3972           TRI.getRegSizeInBits(*VecRC), 32, false);
3973       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3974           .addReg(SrcVec->getReg())
3975           .add(*Val)
3976           .addImm(SubReg);
3977     }
3978     MI.eraseFromParent();
3979     return &MBB;
3980   }
3981 
3982   // Control flow needs to be inserted if indexing with a VGPR.
3983   if (Val->isReg())
3984     MRI.clearKillFlags(Val->getReg());
3985 
3986   const DebugLoc &DL = MI.getDebugLoc();
3987 
3988   Register PhiReg = MRI.createVirtualRegister(VecRC);
3989 
3990   Register SGPRIdxReg;
3991   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3992                               UseGPRIdxMode, SGPRIdxReg);
3993   MachineBasicBlock *LoopBB = InsPt->getParent();
3994 
3995   if (UseGPRIdxMode) {
3996     const MCInstrDesc &GPRIDXDesc =
3997         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3998 
3999     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4000         .addReg(PhiReg)
4001         .add(*Val)
4002         .addReg(SGPRIdxReg)
4003         .addImm(AMDGPU::sub0);
4004   } else {
4005     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4006         TRI.getRegSizeInBits(*VecRC), 32, false);
4007     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4008         .addReg(PhiReg)
4009         .add(*Val)
4010         .addImm(AMDGPU::sub0);
4011   }
4012 
4013   MI.eraseFromParent();
4014   return LoopBB;
4015 }
4016 
4017 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4018   MachineInstr &MI, MachineBasicBlock *BB) const {
4019 
4020   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4021   MachineFunction *MF = BB->getParent();
4022   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4023 
4024   switch (MI.getOpcode()) {
4025   case AMDGPU::S_UADDO_PSEUDO:
4026   case AMDGPU::S_USUBO_PSEUDO: {
4027     const DebugLoc &DL = MI.getDebugLoc();
4028     MachineOperand &Dest0 = MI.getOperand(0);
4029     MachineOperand &Dest1 = MI.getOperand(1);
4030     MachineOperand &Src0 = MI.getOperand(2);
4031     MachineOperand &Src1 = MI.getOperand(3);
4032 
4033     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4034                        ? AMDGPU::S_ADD_I32
4035                        : AMDGPU::S_SUB_I32;
4036     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4037 
4038     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4039         .addImm(1)
4040         .addImm(0);
4041 
4042     MI.eraseFromParent();
4043     return BB;
4044   }
4045   case AMDGPU::S_ADD_U64_PSEUDO:
4046   case AMDGPU::S_SUB_U64_PSEUDO: {
4047     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4048     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4049     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4050     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4051     const DebugLoc &DL = MI.getDebugLoc();
4052 
4053     MachineOperand &Dest = MI.getOperand(0);
4054     MachineOperand &Src0 = MI.getOperand(1);
4055     MachineOperand &Src1 = MI.getOperand(2);
4056 
4057     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4058     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4059 
4060     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4061         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4062     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4063         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4064 
4065     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4066         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4067     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4068         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4069 
4070     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4071 
4072     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4073     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4074     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4075     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4076     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4077         .addReg(DestSub0)
4078         .addImm(AMDGPU::sub0)
4079         .addReg(DestSub1)
4080         .addImm(AMDGPU::sub1);
4081     MI.eraseFromParent();
4082     return BB;
4083   }
4084   case AMDGPU::V_ADD_U64_PSEUDO:
4085   case AMDGPU::V_SUB_U64_PSEUDO: {
4086     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4087     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4088     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4089     const DebugLoc &DL = MI.getDebugLoc();
4090 
4091     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4092 
4093     MachineOperand &Dest = MI.getOperand(0);
4094     MachineOperand &Src0 = MI.getOperand(1);
4095     MachineOperand &Src1 = MI.getOperand(2);
4096 
4097     if (IsAdd && ST.hasLshlAddB64()) {
4098       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4099                          Dest.getReg())
4100                      .add(Src0)
4101                      .addImm(0)
4102                      .add(Src1);
4103       TII->legalizeOperands(*Add);
4104       MI.eraseFromParent();
4105       return BB;
4106     }
4107 
4108     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4109 
4110     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4111     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4112 
4113     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4114     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4115 
4116     const TargetRegisterClass *Src0RC = Src0.isReg()
4117                                             ? MRI.getRegClass(Src0.getReg())
4118                                             : &AMDGPU::VReg_64RegClass;
4119     const TargetRegisterClass *Src1RC = Src1.isReg()
4120                                             ? MRI.getRegClass(Src1.getReg())
4121                                             : &AMDGPU::VReg_64RegClass;
4122 
4123     const TargetRegisterClass *Src0SubRC =
4124         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4125     const TargetRegisterClass *Src1SubRC =
4126         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4127 
4128     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4129         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4130     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4131         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4132 
4133     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4134         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4135     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4136         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4137 
4138     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4139     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4140                                .addReg(CarryReg, RegState::Define)
4141                                .add(SrcReg0Sub0)
4142                                .add(SrcReg1Sub0)
4143                                .addImm(0); // clamp bit
4144 
4145     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4146     MachineInstr *HiHalf =
4147         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4148             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4149             .add(SrcReg0Sub1)
4150             .add(SrcReg1Sub1)
4151             .addReg(CarryReg, RegState::Kill)
4152             .addImm(0); // clamp bit
4153 
4154     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4155         .addReg(DestSub0)
4156         .addImm(AMDGPU::sub0)
4157         .addReg(DestSub1)
4158         .addImm(AMDGPU::sub1);
4159     TII->legalizeOperands(*LoHalf);
4160     TII->legalizeOperands(*HiHalf);
4161     MI.eraseFromParent();
4162     return BB;
4163   }
4164   case AMDGPU::S_ADD_CO_PSEUDO:
4165   case AMDGPU::S_SUB_CO_PSEUDO: {
4166     // This pseudo has a chance to be selected
4167     // only from uniform add/subcarry node. All the VGPR operands
4168     // therefore assumed to be splat vectors.
4169     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4170     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4171     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4172     MachineBasicBlock::iterator MII = MI;
4173     const DebugLoc &DL = MI.getDebugLoc();
4174     MachineOperand &Dest = MI.getOperand(0);
4175     MachineOperand &CarryDest = MI.getOperand(1);
4176     MachineOperand &Src0 = MI.getOperand(2);
4177     MachineOperand &Src1 = MI.getOperand(3);
4178     MachineOperand &Src2 = MI.getOperand(4);
4179     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4180                        ? AMDGPU::S_ADDC_U32
4181                        : AMDGPU::S_SUBB_U32;
4182     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4183       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4184       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4185           .addReg(Src0.getReg());
4186       Src0.setReg(RegOp0);
4187     }
4188     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4189       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4190       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4191           .addReg(Src1.getReg());
4192       Src1.setReg(RegOp1);
4193     }
4194     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4195     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4196       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4197           .addReg(Src2.getReg());
4198       Src2.setReg(RegOp2);
4199     }
4200 
4201     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4202     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4203     assert(WaveSize == 64 || WaveSize == 32);
4204 
4205     if (WaveSize == 64) {
4206       if (ST.hasScalarCompareEq64()) {
4207         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4208             .addReg(Src2.getReg())
4209             .addImm(0);
4210       } else {
4211         const TargetRegisterClass *SubRC =
4212             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4213         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4214             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4215         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4216             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4217         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4218 
4219         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4220             .add(Src2Sub0)
4221             .add(Src2Sub1);
4222 
4223         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4224             .addReg(Src2_32, RegState::Kill)
4225             .addImm(0);
4226       }
4227     } else {
4228       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4229           .addReg(Src2.getReg())
4230           .addImm(0);
4231     }
4232 
4233     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4234 
4235     unsigned SelOpc =
4236         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4237 
4238     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4239         .addImm(-1)
4240         .addImm(0);
4241 
4242     MI.eraseFromParent();
4243     return BB;
4244   }
4245   case AMDGPU::SI_INIT_M0: {
4246     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4247             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4248         .add(MI.getOperand(0));
4249     MI.eraseFromParent();
4250     return BB;
4251   }
4252   case AMDGPU::GET_GROUPSTATICSIZE: {
4253     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4254            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4255     DebugLoc DL = MI.getDebugLoc();
4256     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4257         .add(MI.getOperand(0))
4258         .addImm(MFI->getLDSSize());
4259     MI.eraseFromParent();
4260     return BB;
4261   }
4262   case AMDGPU::SI_INDIRECT_SRC_V1:
4263   case AMDGPU::SI_INDIRECT_SRC_V2:
4264   case AMDGPU::SI_INDIRECT_SRC_V4:
4265   case AMDGPU::SI_INDIRECT_SRC_V8:
4266   case AMDGPU::SI_INDIRECT_SRC_V16:
4267   case AMDGPU::SI_INDIRECT_SRC_V32:
4268     return emitIndirectSrc(MI, *BB, *getSubtarget());
4269   case AMDGPU::SI_INDIRECT_DST_V1:
4270   case AMDGPU::SI_INDIRECT_DST_V2:
4271   case AMDGPU::SI_INDIRECT_DST_V4:
4272   case AMDGPU::SI_INDIRECT_DST_V8:
4273   case AMDGPU::SI_INDIRECT_DST_V16:
4274   case AMDGPU::SI_INDIRECT_DST_V32:
4275     return emitIndirectDst(MI, *BB, *getSubtarget());
4276   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4277   case AMDGPU::SI_KILL_I1_PSEUDO:
4278     return splitKillBlock(MI, BB);
4279   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4280     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4281     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4282     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4283 
4284     Register Dst = MI.getOperand(0).getReg();
4285     Register Src0 = MI.getOperand(1).getReg();
4286     Register Src1 = MI.getOperand(2).getReg();
4287     const DebugLoc &DL = MI.getDebugLoc();
4288     Register SrcCond = MI.getOperand(3).getReg();
4289 
4290     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4291     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4292     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4293     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4294 
4295     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4296       .addReg(SrcCond);
4297     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4298       .addImm(0)
4299       .addReg(Src0, 0, AMDGPU::sub0)
4300       .addImm(0)
4301       .addReg(Src1, 0, AMDGPU::sub0)
4302       .addReg(SrcCondCopy);
4303     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4304       .addImm(0)
4305       .addReg(Src0, 0, AMDGPU::sub1)
4306       .addImm(0)
4307       .addReg(Src1, 0, AMDGPU::sub1)
4308       .addReg(SrcCondCopy);
4309 
4310     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4311       .addReg(DstLo)
4312       .addImm(AMDGPU::sub0)
4313       .addReg(DstHi)
4314       .addImm(AMDGPU::sub1);
4315     MI.eraseFromParent();
4316     return BB;
4317   }
4318   case AMDGPU::SI_BR_UNDEF: {
4319     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4320     const DebugLoc &DL = MI.getDebugLoc();
4321     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4322                            .add(MI.getOperand(0));
4323     Br->getOperand(1).setIsUndef(true); // read undef SCC
4324     MI.eraseFromParent();
4325     return BB;
4326   }
4327   case AMDGPU::ADJCALLSTACKUP:
4328   case AMDGPU::ADJCALLSTACKDOWN: {
4329     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4330     MachineInstrBuilder MIB(*MF, &MI);
4331     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4332        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4333     return BB;
4334   }
4335   case AMDGPU::SI_CALL_ISEL: {
4336     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4337     const DebugLoc &DL = MI.getDebugLoc();
4338 
4339     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4340 
4341     MachineInstrBuilder MIB;
4342     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4343 
4344     for (const MachineOperand &MO : MI.operands())
4345       MIB.add(MO);
4346 
4347     MIB.cloneMemRefs(MI);
4348     MI.eraseFromParent();
4349     return BB;
4350   }
4351   case AMDGPU::V_ADD_CO_U32_e32:
4352   case AMDGPU::V_SUB_CO_U32_e32:
4353   case AMDGPU::V_SUBREV_CO_U32_e32: {
4354     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4355     const DebugLoc &DL = MI.getDebugLoc();
4356     unsigned Opc = MI.getOpcode();
4357 
4358     bool NeedClampOperand = false;
4359     if (TII->pseudoToMCOpcode(Opc) == -1) {
4360       Opc = AMDGPU::getVOPe64(Opc);
4361       NeedClampOperand = true;
4362     }
4363 
4364     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4365     if (TII->isVOP3(*I)) {
4366       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4367       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4368       I.addReg(TRI->getVCC(), RegState::Define);
4369     }
4370     I.add(MI.getOperand(1))
4371      .add(MI.getOperand(2));
4372     if (NeedClampOperand)
4373       I.addImm(0); // clamp bit for e64 encoding
4374 
4375     TII->legalizeOperands(*I);
4376 
4377     MI.eraseFromParent();
4378     return BB;
4379   }
4380   case AMDGPU::V_ADDC_U32_e32:
4381   case AMDGPU::V_SUBB_U32_e32:
4382   case AMDGPU::V_SUBBREV_U32_e32:
4383     // These instructions have an implicit use of vcc which counts towards the
4384     // constant bus limit.
4385     TII->legalizeOperands(MI);
4386     return BB;
4387   case AMDGPU::DS_GWS_INIT:
4388   case AMDGPU::DS_GWS_SEMA_BR:
4389   case AMDGPU::DS_GWS_BARRIER:
4390     if (Subtarget->needsAlignedVGPRs()) {
4391       // Add implicit aligned super-reg to force alignment on the data operand.
4392       const DebugLoc &DL = MI.getDebugLoc();
4393       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4394       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4395       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4396       Register DataReg = Op->getReg();
4397       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4398       Register Undef = MRI.createVirtualRegister(
4399           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4400       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4401       Register NewVR =
4402           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4403                                            : &AMDGPU::VReg_64_Align2RegClass);
4404       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4405           .addReg(DataReg, 0, Op->getSubReg())
4406           .addImm(AMDGPU::sub0)
4407           .addReg(Undef)
4408           .addImm(AMDGPU::sub1);
4409       Op->setReg(NewVR);
4410       Op->setSubReg(AMDGPU::sub0);
4411       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4412     }
4413     LLVM_FALLTHROUGH;
4414   case AMDGPU::DS_GWS_SEMA_V:
4415   case AMDGPU::DS_GWS_SEMA_P:
4416   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4417     // A s_waitcnt 0 is required to be the instruction immediately following.
4418     if (getSubtarget()->hasGWSAutoReplay()) {
4419       bundleInstWithWaitcnt(MI);
4420       return BB;
4421     }
4422 
4423     return emitGWSMemViolTestLoop(MI, BB);
4424   case AMDGPU::S_SETREG_B32: {
4425     // Try to optimize cases that only set the denormal mode or rounding mode.
4426     //
4427     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4428     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4429     // instead.
4430     //
4431     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4432     // allow you to have a no side effect instruction in the output of a
4433     // sideeffecting pattern.
4434     unsigned ID, Offset, Width;
4435     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4436     if (ID != AMDGPU::Hwreg::ID_MODE)
4437       return BB;
4438 
4439     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4440     const unsigned SetMask = WidthMask << Offset;
4441 
4442     if (getSubtarget()->hasDenormModeInst()) {
4443       unsigned SetDenormOp = 0;
4444       unsigned SetRoundOp = 0;
4445 
4446       // The dedicated instructions can only set the whole denorm or round mode
4447       // at once, not a subset of bits in either.
4448       if (SetMask ==
4449           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4450         // If this fully sets both the round and denorm mode, emit the two
4451         // dedicated instructions for these.
4452         SetRoundOp = AMDGPU::S_ROUND_MODE;
4453         SetDenormOp = AMDGPU::S_DENORM_MODE;
4454       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4455         SetRoundOp = AMDGPU::S_ROUND_MODE;
4456       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4457         SetDenormOp = AMDGPU::S_DENORM_MODE;
4458       }
4459 
4460       if (SetRoundOp || SetDenormOp) {
4461         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4462         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4463         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4464           unsigned ImmVal = Def->getOperand(1).getImm();
4465           if (SetRoundOp) {
4466             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4467                 .addImm(ImmVal & 0xf);
4468 
4469             // If we also have the denorm mode, get just the denorm mode bits.
4470             ImmVal >>= 4;
4471           }
4472 
4473           if (SetDenormOp) {
4474             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4475                 .addImm(ImmVal & 0xf);
4476           }
4477 
4478           MI.eraseFromParent();
4479           return BB;
4480         }
4481       }
4482     }
4483 
4484     // If only FP bits are touched, used the no side effects pseudo.
4485     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4486                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4487       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4488 
4489     return BB;
4490   }
4491   default:
4492     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4493   }
4494 }
4495 
4496 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4497   return isTypeLegal(VT.getScalarType());
4498 }
4499 
4500 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4501   // This currently forces unfolding various combinations of fsub into fma with
4502   // free fneg'd operands. As long as we have fast FMA (controlled by
4503   // isFMAFasterThanFMulAndFAdd), we should perform these.
4504 
4505   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4506   // most of these combines appear to be cycle neutral but save on instruction
4507   // count / code size.
4508   return true;
4509 }
4510 
4511 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4512 
4513 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4514                                          EVT VT) const {
4515   if (!VT.isVector()) {
4516     return MVT::i1;
4517   }
4518   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4519 }
4520 
4521 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4522   // TODO: Should i16 be used always if legal? For now it would force VALU
4523   // shifts.
4524   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4525 }
4526 
4527 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4528   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4529              ? Ty.changeElementSize(16)
4530              : Ty.changeElementSize(32);
4531 }
4532 
4533 // Answering this is somewhat tricky and depends on the specific device which
4534 // have different rates for fma or all f64 operations.
4535 //
4536 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4537 // regardless of which device (although the number of cycles differs between
4538 // devices), so it is always profitable for f64.
4539 //
4540 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4541 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4542 // which we can always do even without fused FP ops since it returns the same
4543 // result as the separate operations and since it is always full
4544 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4545 // however does not support denormals, so we do report fma as faster if we have
4546 // a fast fma device and require denormals.
4547 //
4548 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4549                                                   EVT VT) const {
4550   VT = VT.getScalarType();
4551 
4552   switch (VT.getSimpleVT().SimpleTy) {
4553   case MVT::f32: {
4554     // If mad is not available this depends only on if f32 fma is full rate.
4555     if (!Subtarget->hasMadMacF32Insts())
4556       return Subtarget->hasFastFMAF32();
4557 
4558     // Otherwise f32 mad is always full rate and returns the same result as
4559     // the separate operations so should be preferred over fma.
4560     // However does not support denormals.
4561     if (hasFP32Denormals(MF))
4562       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4563 
4564     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4565     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4566   }
4567   case MVT::f64:
4568     return true;
4569   case MVT::f16:
4570     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4571   default:
4572     break;
4573   }
4574 
4575   return false;
4576 }
4577 
4578 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4579                                                   LLT Ty) const {
4580   switch (Ty.getScalarSizeInBits()) {
4581   case 16:
4582     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4583   case 32:
4584     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4585   case 64:
4586     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4587   default:
4588     break;
4589   }
4590 
4591   return false;
4592 }
4593 
4594 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4595   if (!Ty.isScalar())
4596     return false;
4597 
4598   if (Ty.getScalarSizeInBits() == 16)
4599     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4600   if (Ty.getScalarSizeInBits() == 32)
4601     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4602 
4603   return false;
4604 }
4605 
4606 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4607                                    const SDNode *N) const {
4608   // TODO: Check future ftz flag
4609   // v_mad_f32/v_mac_f32 do not support denormals.
4610   EVT VT = N->getValueType(0);
4611   if (VT == MVT::f32)
4612     return Subtarget->hasMadMacF32Insts() &&
4613            !hasFP32Denormals(DAG.getMachineFunction());
4614   if (VT == MVT::f16) {
4615     return Subtarget->hasMadF16() &&
4616            !hasFP64FP16Denormals(DAG.getMachineFunction());
4617   }
4618 
4619   return false;
4620 }
4621 
4622 //===----------------------------------------------------------------------===//
4623 // Custom DAG Lowering Operations
4624 //===----------------------------------------------------------------------===//
4625 
4626 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4627 // wider vector type is legal.
4628 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4629                                              SelectionDAG &DAG) const {
4630   unsigned Opc = Op.getOpcode();
4631   EVT VT = Op.getValueType();
4632   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4633 
4634   SDValue Lo, Hi;
4635   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4636 
4637   SDLoc SL(Op);
4638   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4639                              Op->getFlags());
4640   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4641                              Op->getFlags());
4642 
4643   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4644 }
4645 
4646 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4647 // wider vector type is legal.
4648 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4649                                               SelectionDAG &DAG) const {
4650   unsigned Opc = Op.getOpcode();
4651   EVT VT = Op.getValueType();
4652   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4653          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4654          VT == MVT::v16f32 || VT == MVT::v32f32);
4655 
4656   SDValue Lo0, Hi0;
4657   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4658   SDValue Lo1, Hi1;
4659   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4660 
4661   SDLoc SL(Op);
4662 
4663   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4664                              Op->getFlags());
4665   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4666                              Op->getFlags());
4667 
4668   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4669 }
4670 
4671 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4672                                               SelectionDAG &DAG) const {
4673   unsigned Opc = Op.getOpcode();
4674   EVT VT = Op.getValueType();
4675   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4676          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4677          VT == MVT::v16f32 || VT == MVT::v32f32);
4678 
4679   SDValue Lo0, Hi0;
4680   SDValue Op0 = Op.getOperand(0);
4681   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4682                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4683                          : std::make_pair(Op0, Op0);
4684   SDValue Lo1, Hi1;
4685   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4686   SDValue Lo2, Hi2;
4687   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4688 
4689   SDLoc SL(Op);
4690   auto ResVT = DAG.GetSplitDestVTs(VT);
4691 
4692   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4693                              Op->getFlags());
4694   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4695                              Op->getFlags());
4696 
4697   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4698 }
4699 
4700 
4701 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4702   switch (Op.getOpcode()) {
4703   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4704   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4705   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4706   case ISD::LOAD: {
4707     SDValue Result = LowerLOAD(Op, DAG);
4708     assert((!Result.getNode() ||
4709             Result.getNode()->getNumValues() == 2) &&
4710            "Load should return a value and a chain");
4711     return Result;
4712   }
4713 
4714   case ISD::FSIN:
4715   case ISD::FCOS:
4716     return LowerTrig(Op, DAG);
4717   case ISD::SELECT: return LowerSELECT(Op, DAG);
4718   case ISD::FDIV: return LowerFDIV(Op, DAG);
4719   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4720   case ISD::STORE: return LowerSTORE(Op, DAG);
4721   case ISD::GlobalAddress: {
4722     MachineFunction &MF = DAG.getMachineFunction();
4723     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4724     return LowerGlobalAddress(MFI, Op, DAG);
4725   }
4726   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4727   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4728   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4729   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4730   case ISD::INSERT_SUBVECTOR:
4731     return lowerINSERT_SUBVECTOR(Op, DAG);
4732   case ISD::INSERT_VECTOR_ELT:
4733     return lowerINSERT_VECTOR_ELT(Op, DAG);
4734   case ISD::EXTRACT_VECTOR_ELT:
4735     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4736   case ISD::VECTOR_SHUFFLE:
4737     return lowerVECTOR_SHUFFLE(Op, DAG);
4738   case ISD::BUILD_VECTOR:
4739     return lowerBUILD_VECTOR(Op, DAG);
4740   case ISD::FP_ROUND:
4741     return lowerFP_ROUND(Op, DAG);
4742   case ISD::FPTRUNC_ROUND: {
4743     unsigned Opc;
4744     SDLoc DL(Op);
4745 
4746     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4747       return SDValue();
4748 
4749     // Get the rounding mode from the last operand
4750     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4751     if (RoundMode == (int)RoundingMode::TowardPositive)
4752       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4753     else if (RoundMode == (int)RoundingMode::TowardNegative)
4754       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4755     else
4756       return SDValue();
4757 
4758     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4759   }
4760   case ISD::TRAP:
4761     return lowerTRAP(Op, DAG);
4762   case ISD::DEBUGTRAP:
4763     return lowerDEBUGTRAP(Op, DAG);
4764   case ISD::FABS:
4765   case ISD::FNEG:
4766   case ISD::FCANONICALIZE:
4767   case ISD::BSWAP:
4768     return splitUnaryVectorOp(Op, DAG);
4769   case ISD::FMINNUM:
4770   case ISD::FMAXNUM:
4771     return lowerFMINNUM_FMAXNUM(Op, DAG);
4772   case ISD::FMA:
4773     return splitTernaryVectorOp(Op, DAG);
4774   case ISD::FP_TO_SINT:
4775   case ISD::FP_TO_UINT:
4776     return LowerFP_TO_INT(Op, DAG);
4777   case ISD::SHL:
4778   case ISD::SRA:
4779   case ISD::SRL:
4780   case ISD::ADD:
4781   case ISD::SUB:
4782   case ISD::MUL:
4783   case ISD::SMIN:
4784   case ISD::SMAX:
4785   case ISD::UMIN:
4786   case ISD::UMAX:
4787   case ISD::FADD:
4788   case ISD::FMUL:
4789   case ISD::FMINNUM_IEEE:
4790   case ISD::FMAXNUM_IEEE:
4791   case ISD::UADDSAT:
4792   case ISD::USUBSAT:
4793   case ISD::SADDSAT:
4794   case ISD::SSUBSAT:
4795     return splitBinaryVectorOp(Op, DAG);
4796   case ISD::SMULO:
4797   case ISD::UMULO:
4798     return lowerXMULO(Op, DAG);
4799   case ISD::SMUL_LOHI:
4800   case ISD::UMUL_LOHI:
4801     return lowerXMUL_LOHI(Op, DAG);
4802   case ISD::DYNAMIC_STACKALLOC:
4803     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4804   }
4805   return SDValue();
4806 }
4807 
4808 // Used for D16: Casts the result of an instruction into the right vector,
4809 // packs values if loads return unpacked values.
4810 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4811                                        const SDLoc &DL,
4812                                        SelectionDAG &DAG, bool Unpacked) {
4813   if (!LoadVT.isVector())
4814     return Result;
4815 
4816   // Cast back to the original packed type or to a larger type that is a
4817   // multiple of 32 bit for D16. Widening the return type is a required for
4818   // legalization.
4819   EVT FittingLoadVT = LoadVT;
4820   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4821     FittingLoadVT =
4822         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4823                          LoadVT.getVectorNumElements() + 1);
4824   }
4825 
4826   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4827     // Truncate to v2i16/v4i16.
4828     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4829 
4830     // Workaround legalizer not scalarizing truncate after vector op
4831     // legalization but not creating intermediate vector trunc.
4832     SmallVector<SDValue, 4> Elts;
4833     DAG.ExtractVectorElements(Result, Elts);
4834     for (SDValue &Elt : Elts)
4835       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4836 
4837     // Pad illegal v1i16/v3fi6 to v4i16
4838     if ((LoadVT.getVectorNumElements() % 2) == 1)
4839       Elts.push_back(DAG.getUNDEF(MVT::i16));
4840 
4841     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4842 
4843     // Bitcast to original type (v2f16/v4f16).
4844     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4845   }
4846 
4847   // Cast back to the original packed type.
4848   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4849 }
4850 
4851 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4852                                               MemSDNode *M,
4853                                               SelectionDAG &DAG,
4854                                               ArrayRef<SDValue> Ops,
4855                                               bool IsIntrinsic) const {
4856   SDLoc DL(M);
4857 
4858   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4859   EVT LoadVT = M->getValueType(0);
4860 
4861   EVT EquivLoadVT = LoadVT;
4862   if (LoadVT.isVector()) {
4863     if (Unpacked) {
4864       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4865                                      LoadVT.getVectorNumElements());
4866     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4867       // Widen v3f16 to legal type
4868       EquivLoadVT =
4869           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4870                            LoadVT.getVectorNumElements() + 1);
4871     }
4872   }
4873 
4874   // Change from v4f16/v2f16 to EquivLoadVT.
4875   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4876 
4877   SDValue Load
4878     = DAG.getMemIntrinsicNode(
4879       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4880       VTList, Ops, M->getMemoryVT(),
4881       M->getMemOperand());
4882 
4883   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4884 
4885   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4886 }
4887 
4888 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4889                                              SelectionDAG &DAG,
4890                                              ArrayRef<SDValue> Ops) const {
4891   SDLoc DL(M);
4892   EVT LoadVT = M->getValueType(0);
4893   EVT EltType = LoadVT.getScalarType();
4894   EVT IntVT = LoadVT.changeTypeToInteger();
4895 
4896   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4897 
4898   unsigned Opc =
4899       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4900 
4901   if (IsD16) {
4902     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4903   }
4904 
4905   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4906   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4907     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4908 
4909   if (isTypeLegal(LoadVT)) {
4910     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4911                                M->getMemOperand(), DAG);
4912   }
4913 
4914   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4915   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4916   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4917                                         M->getMemOperand(), DAG);
4918   return DAG.getMergeValues(
4919       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4920       DL);
4921 }
4922 
4923 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4924                                   SDNode *N, SelectionDAG &DAG) {
4925   EVT VT = N->getValueType(0);
4926   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4927   unsigned CondCode = CD->getZExtValue();
4928   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4929     return DAG.getUNDEF(VT);
4930 
4931   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4932 
4933   SDValue LHS = N->getOperand(1);
4934   SDValue RHS = N->getOperand(2);
4935 
4936   SDLoc DL(N);
4937 
4938   EVT CmpVT = LHS.getValueType();
4939   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4940     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4941       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4942     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4943     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4944   }
4945 
4946   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4947 
4948   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4949   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4950 
4951   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4952                               DAG.getCondCode(CCOpcode));
4953   if (VT.bitsEq(CCVT))
4954     return SetCC;
4955   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4956 }
4957 
4958 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4959                                   SDNode *N, SelectionDAG &DAG) {
4960   EVT VT = N->getValueType(0);
4961   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4962 
4963   unsigned CondCode = CD->getZExtValue();
4964   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4965     return DAG.getUNDEF(VT);
4966 
4967   SDValue Src0 = N->getOperand(1);
4968   SDValue Src1 = N->getOperand(2);
4969   EVT CmpVT = Src0.getValueType();
4970   SDLoc SL(N);
4971 
4972   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4973     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4974     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4975   }
4976 
4977   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4978   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4979   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4980   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4981   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4982                               Src1, DAG.getCondCode(CCOpcode));
4983   if (VT.bitsEq(CCVT))
4984     return SetCC;
4985   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4986 }
4987 
4988 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4989                                     SelectionDAG &DAG) {
4990   EVT VT = N->getValueType(0);
4991   SDValue Src = N->getOperand(1);
4992   SDLoc SL(N);
4993 
4994   if (Src.getOpcode() == ISD::SETCC) {
4995     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4996     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4997                        Src.getOperand(1), Src.getOperand(2));
4998   }
4999   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5000     // (ballot 0) -> 0
5001     if (Arg->isZero())
5002       return DAG.getConstant(0, SL, VT);
5003 
5004     // (ballot 1) -> EXEC/EXEC_LO
5005     if (Arg->isOne()) {
5006       Register Exec;
5007       if (VT.getScalarSizeInBits() == 32)
5008         Exec = AMDGPU::EXEC_LO;
5009       else if (VT.getScalarSizeInBits() == 64)
5010         Exec = AMDGPU::EXEC;
5011       else
5012         return SDValue();
5013 
5014       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5015     }
5016   }
5017 
5018   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5019   // ISD::SETNE)
5020   return DAG.getNode(
5021       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5022       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5023 }
5024 
5025 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5026                                           SmallVectorImpl<SDValue> &Results,
5027                                           SelectionDAG &DAG) const {
5028   switch (N->getOpcode()) {
5029   case ISD::INSERT_VECTOR_ELT: {
5030     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5031       Results.push_back(Res);
5032     return;
5033   }
5034   case ISD::EXTRACT_VECTOR_ELT: {
5035     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5036       Results.push_back(Res);
5037     return;
5038   }
5039   case ISD::INTRINSIC_WO_CHAIN: {
5040     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5041     switch (IID) {
5042     case Intrinsic::amdgcn_cvt_pkrtz: {
5043       SDValue Src0 = N->getOperand(1);
5044       SDValue Src1 = N->getOperand(2);
5045       SDLoc SL(N);
5046       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5047                                 Src0, Src1);
5048       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5049       return;
5050     }
5051     case Intrinsic::amdgcn_cvt_pknorm_i16:
5052     case Intrinsic::amdgcn_cvt_pknorm_u16:
5053     case Intrinsic::amdgcn_cvt_pk_i16:
5054     case Intrinsic::amdgcn_cvt_pk_u16: {
5055       SDValue Src0 = N->getOperand(1);
5056       SDValue Src1 = N->getOperand(2);
5057       SDLoc SL(N);
5058       unsigned Opcode;
5059 
5060       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5061         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5062       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5063         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5064       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5065         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5066       else
5067         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5068 
5069       EVT VT = N->getValueType(0);
5070       if (isTypeLegal(VT))
5071         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5072       else {
5073         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5074         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5075       }
5076       return;
5077     }
5078     }
5079     break;
5080   }
5081   case ISD::INTRINSIC_W_CHAIN: {
5082     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5083       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5084         // FIXME: Hacky
5085         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5086           Results.push_back(Res.getOperand(I));
5087         }
5088       } else {
5089         Results.push_back(Res);
5090         Results.push_back(Res.getValue(1));
5091       }
5092       return;
5093     }
5094 
5095     break;
5096   }
5097   case ISD::SELECT: {
5098     SDLoc SL(N);
5099     EVT VT = N->getValueType(0);
5100     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5101     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5102     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5103 
5104     EVT SelectVT = NewVT;
5105     if (NewVT.bitsLT(MVT::i32)) {
5106       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5107       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5108       SelectVT = MVT::i32;
5109     }
5110 
5111     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5112                                     N->getOperand(0), LHS, RHS);
5113 
5114     if (NewVT != SelectVT)
5115       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5116     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5117     return;
5118   }
5119   case ISD::FNEG: {
5120     if (N->getValueType(0) != MVT::v2f16)
5121       break;
5122 
5123     SDLoc SL(N);
5124     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5125 
5126     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5127                              BC,
5128                              DAG.getConstant(0x80008000, SL, MVT::i32));
5129     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5130     return;
5131   }
5132   case ISD::FABS: {
5133     if (N->getValueType(0) != MVT::v2f16)
5134       break;
5135 
5136     SDLoc SL(N);
5137     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5138 
5139     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5140                              BC,
5141                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5142     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5143     return;
5144   }
5145   default:
5146     break;
5147   }
5148 }
5149 
5150 /// Helper function for LowerBRCOND
5151 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5152 
5153   SDNode *Parent = Value.getNode();
5154   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5155        I != E; ++I) {
5156 
5157     if (I.getUse().get() != Value)
5158       continue;
5159 
5160     if (I->getOpcode() == Opcode)
5161       return *I;
5162   }
5163   return nullptr;
5164 }
5165 
5166 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5167   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5168     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5169     case Intrinsic::amdgcn_if:
5170       return AMDGPUISD::IF;
5171     case Intrinsic::amdgcn_else:
5172       return AMDGPUISD::ELSE;
5173     case Intrinsic::amdgcn_loop:
5174       return AMDGPUISD::LOOP;
5175     case Intrinsic::amdgcn_end_cf:
5176       llvm_unreachable("should not occur");
5177     default:
5178       return 0;
5179     }
5180   }
5181 
5182   // break, if_break, else_break are all only used as inputs to loop, not
5183   // directly as branch conditions.
5184   return 0;
5185 }
5186 
5187 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5188   const Triple &TT = getTargetMachine().getTargetTriple();
5189   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5190           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5191          AMDGPU::shouldEmitConstantsToTextSection(TT);
5192 }
5193 
5194 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5195   // FIXME: Either avoid relying on address space here or change the default
5196   // address space for functions to avoid the explicit check.
5197   return (GV->getValueType()->isFunctionTy() ||
5198           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5199          !shouldEmitFixup(GV) &&
5200          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5201 }
5202 
5203 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5204   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5205 }
5206 
5207 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5208   if (!GV->hasExternalLinkage())
5209     return true;
5210 
5211   const auto OS = getTargetMachine().getTargetTriple().getOS();
5212   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5213 }
5214 
5215 /// This transforms the control flow intrinsics to get the branch destination as
5216 /// last parameter, also switches branch target with BR if the need arise
5217 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5218                                       SelectionDAG &DAG) const {
5219   SDLoc DL(BRCOND);
5220 
5221   SDNode *Intr = BRCOND.getOperand(1).getNode();
5222   SDValue Target = BRCOND.getOperand(2);
5223   SDNode *BR = nullptr;
5224   SDNode *SetCC = nullptr;
5225 
5226   if (Intr->getOpcode() == ISD::SETCC) {
5227     // As long as we negate the condition everything is fine
5228     SetCC = Intr;
5229     Intr = SetCC->getOperand(0).getNode();
5230 
5231   } else {
5232     // Get the target from BR if we don't negate the condition
5233     BR = findUser(BRCOND, ISD::BR);
5234     assert(BR && "brcond missing unconditional branch user");
5235     Target = BR->getOperand(1);
5236   }
5237 
5238   unsigned CFNode = isCFIntrinsic(Intr);
5239   if (CFNode == 0) {
5240     // This is a uniform branch so we don't need to legalize.
5241     return BRCOND;
5242   }
5243 
5244   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5245                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5246 
5247   assert(!SetCC ||
5248         (SetCC->getConstantOperandVal(1) == 1 &&
5249          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5250                                                              ISD::SETNE));
5251 
5252   // operands of the new intrinsic call
5253   SmallVector<SDValue, 4> Ops;
5254   if (HaveChain)
5255     Ops.push_back(BRCOND.getOperand(0));
5256 
5257   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5258   Ops.push_back(Target);
5259 
5260   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5261 
5262   // build the new intrinsic call
5263   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5264 
5265   if (!HaveChain) {
5266     SDValue Ops[] =  {
5267       SDValue(Result, 0),
5268       BRCOND.getOperand(0)
5269     };
5270 
5271     Result = DAG.getMergeValues(Ops, DL).getNode();
5272   }
5273 
5274   if (BR) {
5275     // Give the branch instruction our target
5276     SDValue Ops[] = {
5277       BR->getOperand(0),
5278       BRCOND.getOperand(2)
5279     };
5280     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5281     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5282   }
5283 
5284   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5285 
5286   // Copy the intrinsic results to registers
5287   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5288     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5289     if (!CopyToReg)
5290       continue;
5291 
5292     Chain = DAG.getCopyToReg(
5293       Chain, DL,
5294       CopyToReg->getOperand(1),
5295       SDValue(Result, i - 1),
5296       SDValue());
5297 
5298     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5299   }
5300 
5301   // Remove the old intrinsic from the chain
5302   DAG.ReplaceAllUsesOfValueWith(
5303     SDValue(Intr, Intr->getNumValues() - 1),
5304     Intr->getOperand(0));
5305 
5306   return Chain;
5307 }
5308 
5309 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5310                                           SelectionDAG &DAG) const {
5311   MVT VT = Op.getSimpleValueType();
5312   SDLoc DL(Op);
5313   // Checking the depth
5314   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5315     return DAG.getConstant(0, DL, VT);
5316 
5317   MachineFunction &MF = DAG.getMachineFunction();
5318   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5319   // Check for kernel and shader functions
5320   if (Info->isEntryFunction())
5321     return DAG.getConstant(0, DL, VT);
5322 
5323   MachineFrameInfo &MFI = MF.getFrameInfo();
5324   // There is a call to @llvm.returnaddress in this function
5325   MFI.setReturnAddressIsTaken(true);
5326 
5327   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5328   // Get the return address reg and mark it as an implicit live-in
5329   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5330 
5331   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5332 }
5333 
5334 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5335                                             SDValue Op,
5336                                             const SDLoc &DL,
5337                                             EVT VT) const {
5338   return Op.getValueType().bitsLE(VT) ?
5339       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5340     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5341                 DAG.getTargetConstant(0, DL, MVT::i32));
5342 }
5343 
5344 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5345   assert(Op.getValueType() == MVT::f16 &&
5346          "Do not know how to custom lower FP_ROUND for non-f16 type");
5347 
5348   SDValue Src = Op.getOperand(0);
5349   EVT SrcVT = Src.getValueType();
5350   if (SrcVT != MVT::f64)
5351     return Op;
5352 
5353   SDLoc DL(Op);
5354 
5355   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5356   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5357   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5358 }
5359 
5360 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5361                                                SelectionDAG &DAG) const {
5362   EVT VT = Op.getValueType();
5363   const MachineFunction &MF = DAG.getMachineFunction();
5364   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5365   bool IsIEEEMode = Info->getMode().IEEE;
5366 
5367   // FIXME: Assert during selection that this is only selected for
5368   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5369   // mode functions, but this happens to be OK since it's only done in cases
5370   // where there is known no sNaN.
5371   if (IsIEEEMode)
5372     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5373 
5374   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5375     return splitBinaryVectorOp(Op, DAG);
5376   return Op;
5377 }
5378 
5379 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5380   EVT VT = Op.getValueType();
5381   SDLoc SL(Op);
5382   SDValue LHS = Op.getOperand(0);
5383   SDValue RHS = Op.getOperand(1);
5384   bool isSigned = Op.getOpcode() == ISD::SMULO;
5385 
5386   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5387     const APInt &C = RHSC->getAPIntValue();
5388     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5389     if (C.isPowerOf2()) {
5390       // smulo(x, signed_min) is same as umulo(x, signed_min).
5391       bool UseArithShift = isSigned && !C.isMinSignedValue();
5392       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5393       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5394       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5395           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5396                       SL, VT, Result, ShiftAmt),
5397           LHS, ISD::SETNE);
5398       return DAG.getMergeValues({ Result, Overflow }, SL);
5399     }
5400   }
5401 
5402   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5403   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5404                             SL, VT, LHS, RHS);
5405 
5406   SDValue Sign = isSigned
5407     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5408                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5409     : DAG.getConstant(0, SL, VT);
5410   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5411 
5412   return DAG.getMergeValues({ Result, Overflow }, SL);
5413 }
5414 
5415 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5416   if (Op->isDivergent()) {
5417     // Select to V_MAD_[IU]64_[IU]32.
5418     return Op;
5419   }
5420   if (Subtarget->hasSMulHi()) {
5421     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5422     return SDValue();
5423   }
5424   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5425   // calculate the high part, so we might as well do the whole thing with
5426   // V_MAD_[IU]64_[IU]32.
5427   return Op;
5428 }
5429 
5430 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5431   if (!Subtarget->isTrapHandlerEnabled() ||
5432       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5433     return lowerTrapEndpgm(Op, DAG);
5434 
5435   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5436     switch (*HsaAbiVer) {
5437     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5438     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5439       return lowerTrapHsaQueuePtr(Op, DAG);
5440     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5441     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5442       return Subtarget->supportsGetDoorbellID() ?
5443           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5444     }
5445   }
5446 
5447   llvm_unreachable("Unknown trap handler");
5448 }
5449 
5450 SDValue SITargetLowering::lowerTrapEndpgm(
5451     SDValue Op, SelectionDAG &DAG) const {
5452   SDLoc SL(Op);
5453   SDValue Chain = Op.getOperand(0);
5454   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5455 }
5456 
5457 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5458     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5459   MachineFunction &MF = DAG.getMachineFunction();
5460   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5461   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5462   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5463   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5464                      MachineMemOperand::MODereferenceable |
5465                          MachineMemOperand::MOInvariant);
5466 }
5467 
5468 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5469     SDValue Op, SelectionDAG &DAG) const {
5470   SDLoc SL(Op);
5471   SDValue Chain = Op.getOperand(0);
5472 
5473   SDValue QueuePtr;
5474   // For code object version 5, QueuePtr is passed through implicit kernarg.
5475   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5476     QueuePtr =
5477         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5478   } else {
5479     MachineFunction &MF = DAG.getMachineFunction();
5480     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5481     Register UserSGPR = Info->getQueuePtrUserSGPR();
5482 
5483     if (UserSGPR == AMDGPU::NoRegister) {
5484       // We probably are in a function incorrectly marked with
5485       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5486       // trap, so just use a null pointer.
5487       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5488     } else {
5489       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5490                                       MVT::i64);
5491     }
5492   }
5493 
5494   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5495   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5496                                    QueuePtr, SDValue());
5497 
5498   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5499   SDValue Ops[] = {
5500     ToReg,
5501     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5502     SGPR01,
5503     ToReg.getValue(1)
5504   };
5505   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5506 }
5507 
5508 SDValue SITargetLowering::lowerTrapHsa(
5509     SDValue Op, SelectionDAG &DAG) const {
5510   SDLoc SL(Op);
5511   SDValue Chain = Op.getOperand(0);
5512 
5513   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5514   SDValue Ops[] = {
5515     Chain,
5516     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5517   };
5518   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5519 }
5520 
5521 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5522   SDLoc SL(Op);
5523   SDValue Chain = Op.getOperand(0);
5524   MachineFunction &MF = DAG.getMachineFunction();
5525 
5526   if (!Subtarget->isTrapHandlerEnabled() ||
5527       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5528     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5529                                      "debugtrap handler not supported",
5530                                      Op.getDebugLoc(),
5531                                      DS_Warning);
5532     LLVMContext &Ctx = MF.getFunction().getContext();
5533     Ctx.diagnose(NoTrap);
5534     return Chain;
5535   }
5536 
5537   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5538   SDValue Ops[] = {
5539     Chain,
5540     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5541   };
5542   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5543 }
5544 
5545 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5546                                              SelectionDAG &DAG) const {
5547   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5548   if (Subtarget->hasApertureRegs()) {
5549     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5550         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5551         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5552     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5553         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5554         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5555     unsigned Encoding =
5556         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5557         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5558         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5559 
5560     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5561     SDValue ApertureReg = SDValue(
5562         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5563     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5564     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5565   }
5566 
5567   // For code object version 5, private_base and shared_base are passed through
5568   // implicit kernargs.
5569   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5570     ImplicitParameter Param =
5571         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5572     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5573   }
5574 
5575   MachineFunction &MF = DAG.getMachineFunction();
5576   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5577   Register UserSGPR = Info->getQueuePtrUserSGPR();
5578   if (UserSGPR == AMDGPU::NoRegister) {
5579     // We probably are in a function incorrectly marked with
5580     // amdgpu-no-queue-ptr. This is undefined.
5581     return DAG.getUNDEF(MVT::i32);
5582   }
5583 
5584   SDValue QueuePtr = CreateLiveInRegister(
5585     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5586 
5587   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5588   // private_segment_aperture_base_hi.
5589   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5590 
5591   SDValue Ptr =
5592       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5593 
5594   // TODO: Use custom target PseudoSourceValue.
5595   // TODO: We should use the value from the IR intrinsic call, but it might not
5596   // be available and how do we get it?
5597   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5598   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5599                      commonAlignment(Align(64), StructOffset),
5600                      MachineMemOperand::MODereferenceable |
5601                          MachineMemOperand::MOInvariant);
5602 }
5603 
5604 /// Return true if the value is a known valid address, such that a null check is
5605 /// not necessary.
5606 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5607                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5608   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5609       isa<BasicBlockSDNode>(Val))
5610     return true;
5611 
5612   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5613     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5614 
5615   // TODO: Search through arithmetic, handle arguments and loads
5616   // marked nonnull.
5617   return false;
5618 }
5619 
5620 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5621                                              SelectionDAG &DAG) const {
5622   SDLoc SL(Op);
5623   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5624 
5625   SDValue Src = ASC->getOperand(0);
5626   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5627   unsigned SrcAS = ASC->getSrcAddressSpace();
5628 
5629   const AMDGPUTargetMachine &TM =
5630     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5631 
5632   // flat -> local/private
5633   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5634     unsigned DestAS = ASC->getDestAddressSpace();
5635 
5636     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5637         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5638       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5639 
5640       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5641         return Ptr;
5642 
5643       unsigned NullVal = TM.getNullPointerValue(DestAS);
5644       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5645       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5646 
5647       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5648                          SegmentNullPtr);
5649     }
5650   }
5651 
5652   // local/private -> flat
5653   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5654     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5655         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5656 
5657       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5658       SDValue CvtPtr =
5659           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5660       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5661 
5662       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5663         return CvtPtr;
5664 
5665       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5666       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5667 
5668       SDValue NonNull
5669         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5670 
5671       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5672                          FlatNullPtr);
5673     }
5674   }
5675 
5676   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5677       Op.getValueType() == MVT::i64) {
5678     const SIMachineFunctionInfo *Info =
5679         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5680     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5681     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5682     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5683   }
5684 
5685   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5686       Src.getValueType() == MVT::i64)
5687     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5688 
5689   // global <-> flat are no-ops and never emitted.
5690 
5691   const MachineFunction &MF = DAG.getMachineFunction();
5692   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5693     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5694   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5695 
5696   return DAG.getUNDEF(ASC->getValueType(0));
5697 }
5698 
5699 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5700 // the small vector and inserting them into the big vector. That is better than
5701 // the default expansion of doing it via a stack slot. Even though the use of
5702 // the stack slot would be optimized away afterwards, the stack slot itself
5703 // remains.
5704 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5705                                                 SelectionDAG &DAG) const {
5706   SDValue Vec = Op.getOperand(0);
5707   SDValue Ins = Op.getOperand(1);
5708   SDValue Idx = Op.getOperand(2);
5709   EVT VecVT = Vec.getValueType();
5710   EVT InsVT = Ins.getValueType();
5711   EVT EltVT = VecVT.getVectorElementType();
5712   unsigned InsNumElts = InsVT.getVectorNumElements();
5713   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5714   SDLoc SL(Op);
5715 
5716   for (unsigned I = 0; I != InsNumElts; ++I) {
5717     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5718                               DAG.getConstant(I, SL, MVT::i32));
5719     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5720                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5721   }
5722   return Vec;
5723 }
5724 
5725 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5726                                                  SelectionDAG &DAG) const {
5727   SDValue Vec = Op.getOperand(0);
5728   SDValue InsVal = Op.getOperand(1);
5729   SDValue Idx = Op.getOperand(2);
5730   EVT VecVT = Vec.getValueType();
5731   EVT EltVT = VecVT.getVectorElementType();
5732   unsigned VecSize = VecVT.getSizeInBits();
5733   unsigned EltSize = EltVT.getSizeInBits();
5734 
5735 
5736   assert(VecSize <= 64);
5737 
5738   unsigned NumElts = VecVT.getVectorNumElements();
5739   SDLoc SL(Op);
5740   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5741 
5742   if (NumElts == 4 && EltSize == 16 && KIdx) {
5743     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5744 
5745     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5746                                  DAG.getConstant(0, SL, MVT::i32));
5747     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5748                                  DAG.getConstant(1, SL, MVT::i32));
5749 
5750     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5751     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5752 
5753     unsigned Idx = KIdx->getZExtValue();
5754     bool InsertLo = Idx < 2;
5755     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5756       InsertLo ? LoVec : HiVec,
5757       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5758       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5759 
5760     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5761 
5762     SDValue Concat = InsertLo ?
5763       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5764       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5765 
5766     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5767   }
5768 
5769   if (isa<ConstantSDNode>(Idx))
5770     return SDValue();
5771 
5772   MVT IntVT = MVT::getIntegerVT(VecSize);
5773 
5774   // Avoid stack access for dynamic indexing.
5775   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5776 
5777   // Create a congruent vector with the target value in each element so that
5778   // the required element can be masked and ORed into the target vector.
5779   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5780                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5781 
5782   assert(isPowerOf2_32(EltSize));
5783   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5784 
5785   // Convert vector index to bit-index.
5786   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5787 
5788   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5789   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5790                             DAG.getConstant(0xffff, SL, IntVT),
5791                             ScaledIdx);
5792 
5793   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5794   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5795                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5796 
5797   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5798   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5799 }
5800 
5801 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5802                                                   SelectionDAG &DAG) const {
5803   SDLoc SL(Op);
5804 
5805   EVT ResultVT = Op.getValueType();
5806   SDValue Vec = Op.getOperand(0);
5807   SDValue Idx = Op.getOperand(1);
5808   EVT VecVT = Vec.getValueType();
5809   unsigned VecSize = VecVT.getSizeInBits();
5810   EVT EltVT = VecVT.getVectorElementType();
5811 
5812   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5813 
5814   // Make sure we do any optimizations that will make it easier to fold
5815   // source modifiers before obscuring it with bit operations.
5816 
5817   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5818   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5819     return Combined;
5820 
5821   if (VecSize == 128) {
5822     SDValue Lo, Hi;
5823     EVT LoVT, HiVT;
5824     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5825     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5826     Lo =
5827         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5828                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5829     Hi =
5830         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5831                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5832     EVT IdxVT = Idx.getValueType();
5833     unsigned NElem = VecVT.getVectorNumElements();
5834     assert(isPowerOf2_32(NElem));
5835     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5836     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5837     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5838     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5839   }
5840 
5841   assert(VecSize <= 64);
5842 
5843   unsigned EltSize = EltVT.getSizeInBits();
5844   assert(isPowerOf2_32(EltSize));
5845 
5846   MVT IntVT = MVT::getIntegerVT(VecSize);
5847   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5848 
5849   // Convert vector index to bit-index (* EltSize)
5850   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5851 
5852   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5853   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5854 
5855   if (ResultVT == MVT::f16) {
5856     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5857     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5858   }
5859 
5860   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5861 }
5862 
5863 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5864   assert(Elt % 2 == 0);
5865   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5866 }
5867 
5868 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5869                                               SelectionDAG &DAG) const {
5870   SDLoc SL(Op);
5871   EVT ResultVT = Op.getValueType();
5872   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5873 
5874   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5875   EVT EltVT = PackVT.getVectorElementType();
5876   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5877 
5878   // vector_shuffle <0,1,6,7> lhs, rhs
5879   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5880   //
5881   // vector_shuffle <6,7,2,3> lhs, rhs
5882   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5883   //
5884   // vector_shuffle <6,7,0,1> lhs, rhs
5885   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5886 
5887   // Avoid scalarizing when both halves are reading from consecutive elements.
5888   SmallVector<SDValue, 4> Pieces;
5889   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5890     if (elementPairIsContiguous(SVN->getMask(), I)) {
5891       const int Idx = SVN->getMaskElt(I);
5892       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5893       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5894       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5895                                     PackVT, SVN->getOperand(VecIdx),
5896                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5897       Pieces.push_back(SubVec);
5898     } else {
5899       const int Idx0 = SVN->getMaskElt(I);
5900       const int Idx1 = SVN->getMaskElt(I + 1);
5901       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5902       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5903       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5904       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5905 
5906       SDValue Vec0 = SVN->getOperand(VecIdx0);
5907       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5908                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5909 
5910       SDValue Vec1 = SVN->getOperand(VecIdx1);
5911       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5912                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5913       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5914     }
5915   }
5916 
5917   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5918 }
5919 
5920 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5921                                             SelectionDAG &DAG) const {
5922   SDLoc SL(Op);
5923   EVT VT = Op.getValueType();
5924 
5925   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5926       VT == MVT::v8i16 || VT == MVT::v8f16) {
5927     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5928                                   VT.getVectorNumElements() / 2);
5929     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5930 
5931     // Turn into pair of packed build_vectors.
5932     // TODO: Special case for constants that can be materialized with s_mov_b64.
5933     SmallVector<SDValue, 4> LoOps, HiOps;
5934     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5935       LoOps.push_back(Op.getOperand(I));
5936       HiOps.push_back(Op.getOperand(I + E));
5937     }
5938     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5939     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5940 
5941     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5942     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5943 
5944     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5945                                        { CastLo, CastHi });
5946     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5947   }
5948 
5949   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5950   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5951 
5952   SDValue Lo = Op.getOperand(0);
5953   SDValue Hi = Op.getOperand(1);
5954 
5955   // Avoid adding defined bits with the zero_extend.
5956   if (Hi.isUndef()) {
5957     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5958     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5959     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5960   }
5961 
5962   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5963   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5964 
5965   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5966                               DAG.getConstant(16, SL, MVT::i32));
5967   if (Lo.isUndef())
5968     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5969 
5970   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5971   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5972 
5973   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5974   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5975 }
5976 
5977 bool
5978 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5979   // We can fold offsets for anything that doesn't require a GOT relocation.
5980   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5981           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5982           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5983          !shouldEmitGOTReloc(GA->getGlobal());
5984 }
5985 
5986 static SDValue
5987 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5988                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5989                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5990   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5991   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5992   // lowered to the following code sequence:
5993   //
5994   // For constant address space:
5995   //   s_getpc_b64 s[0:1]
5996   //   s_add_u32 s0, s0, $symbol
5997   //   s_addc_u32 s1, s1, 0
5998   //
5999   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6000   //   a fixup or relocation is emitted to replace $symbol with a literal
6001   //   constant, which is a pc-relative offset from the encoding of the $symbol
6002   //   operand to the global variable.
6003   //
6004   // For global address space:
6005   //   s_getpc_b64 s[0:1]
6006   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6007   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6008   //
6009   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6010   //   fixups or relocations are emitted to replace $symbol@*@lo and
6011   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6012   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6013   //   operand to the global variable.
6014   //
6015   // What we want here is an offset from the value returned by s_getpc
6016   // (which is the address of the s_add_u32 instruction) to the global
6017   // variable, but since the encoding of $symbol starts 4 bytes after the start
6018   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6019   // small. This requires us to add 4 to the global variable offset in order to
6020   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6021   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6022   // instruction.
6023   SDValue PtrLo =
6024       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6025   SDValue PtrHi;
6026   if (GAFlags == SIInstrInfo::MO_NONE) {
6027     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6028   } else {
6029     PtrHi =
6030         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6031   }
6032   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6033 }
6034 
6035 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6036                                              SDValue Op,
6037                                              SelectionDAG &DAG) const {
6038   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6039   SDLoc DL(GSD);
6040   EVT PtrVT = Op.getValueType();
6041 
6042   const GlobalValue *GV = GSD->getGlobal();
6043   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6044        shouldUseLDSConstAddress(GV)) ||
6045       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6046       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6047     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6048         GV->hasExternalLinkage()) {
6049       Type *Ty = GV->getValueType();
6050       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6051       // zero-sized type in other languages to declare the dynamic shared
6052       // memory which size is not known at the compile time. They will be
6053       // allocated by the runtime and placed directly after the static
6054       // allocated ones. They all share the same offset.
6055       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6056         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6057         // Adjust alignment for that dynamic shared memory array.
6058         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6059         return SDValue(
6060             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6061       }
6062     }
6063     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6064   }
6065 
6066   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6067     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6068                                             SIInstrInfo::MO_ABS32_LO);
6069     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6070   }
6071 
6072   if (shouldEmitFixup(GV))
6073     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6074   else if (shouldEmitPCReloc(GV))
6075     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6076                                    SIInstrInfo::MO_REL32);
6077 
6078   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6079                                             SIInstrInfo::MO_GOTPCREL32);
6080 
6081   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6082   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6083   const DataLayout &DataLayout = DAG.getDataLayout();
6084   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6085   MachinePointerInfo PtrInfo
6086     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6087 
6088   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6089                      MachineMemOperand::MODereferenceable |
6090                          MachineMemOperand::MOInvariant);
6091 }
6092 
6093 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6094                                    const SDLoc &DL, SDValue V) const {
6095   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6096   // the destination register.
6097   //
6098   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6099   // so we will end up with redundant moves to m0.
6100   //
6101   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6102 
6103   // A Null SDValue creates a glue result.
6104   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6105                                   V, Chain);
6106   return SDValue(M0, 0);
6107 }
6108 
6109 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6110                                                  SDValue Op,
6111                                                  MVT VT,
6112                                                  unsigned Offset) const {
6113   SDLoc SL(Op);
6114   SDValue Param = lowerKernargMemParameter(
6115       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6116   // The local size values will have the hi 16-bits as zero.
6117   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6118                      DAG.getValueType(VT));
6119 }
6120 
6121 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6122                                         EVT VT) {
6123   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6124                                       "non-hsa intrinsic with hsa target",
6125                                       DL.getDebugLoc());
6126   DAG.getContext()->diagnose(BadIntrin);
6127   return DAG.getUNDEF(VT);
6128 }
6129 
6130 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6131                                          EVT VT) {
6132   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6133                                       "intrinsic not supported on subtarget",
6134                                       DL.getDebugLoc());
6135   DAG.getContext()->diagnose(BadIntrin);
6136   return DAG.getUNDEF(VT);
6137 }
6138 
6139 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6140                                     ArrayRef<SDValue> Elts) {
6141   assert(!Elts.empty());
6142   MVT Type;
6143   unsigned NumElts = Elts.size();
6144 
6145   if (NumElts <= 8) {
6146     Type = MVT::getVectorVT(MVT::f32, NumElts);
6147   } else {
6148     assert(Elts.size() <= 16);
6149     Type = MVT::v16f32;
6150     NumElts = 16;
6151   }
6152 
6153   SmallVector<SDValue, 16> VecElts(NumElts);
6154   for (unsigned i = 0; i < Elts.size(); ++i) {
6155     SDValue Elt = Elts[i];
6156     if (Elt.getValueType() != MVT::f32)
6157       Elt = DAG.getBitcast(MVT::f32, Elt);
6158     VecElts[i] = Elt;
6159   }
6160   for (unsigned i = Elts.size(); i < NumElts; ++i)
6161     VecElts[i] = DAG.getUNDEF(MVT::f32);
6162 
6163   if (NumElts == 1)
6164     return VecElts[0];
6165   return DAG.getBuildVector(Type, DL, VecElts);
6166 }
6167 
6168 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6169                               SDValue Src, int ExtraElts) {
6170   EVT SrcVT = Src.getValueType();
6171 
6172   SmallVector<SDValue, 8> Elts;
6173 
6174   if (SrcVT.isVector())
6175     DAG.ExtractVectorElements(Src, Elts);
6176   else
6177     Elts.push_back(Src);
6178 
6179   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6180   while (ExtraElts--)
6181     Elts.push_back(Undef);
6182 
6183   return DAG.getBuildVector(CastVT, DL, Elts);
6184 }
6185 
6186 // Re-construct the required return value for a image load intrinsic.
6187 // This is more complicated due to the optional use TexFailCtrl which means the required
6188 // return type is an aggregate
6189 static SDValue constructRetValue(SelectionDAG &DAG,
6190                                  MachineSDNode *Result,
6191                                  ArrayRef<EVT> ResultTypes,
6192                                  bool IsTexFail, bool Unpacked, bool IsD16,
6193                                  int DMaskPop, int NumVDataDwords,
6194                                  const SDLoc &DL) {
6195   // Determine the required return type. This is the same regardless of IsTexFail flag
6196   EVT ReqRetVT = ResultTypes[0];
6197   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6198   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6199     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6200 
6201   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6202     DMaskPop : (DMaskPop + 1) / 2;
6203 
6204   MVT DataDwordVT = NumDataDwords == 1 ?
6205     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6206 
6207   MVT MaskPopVT = MaskPopDwords == 1 ?
6208     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6209 
6210   SDValue Data(Result, 0);
6211   SDValue TexFail;
6212 
6213   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6214     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6215     if (MaskPopVT.isVector()) {
6216       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6217                          SDValue(Result, 0), ZeroIdx);
6218     } else {
6219       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6220                          SDValue(Result, 0), ZeroIdx);
6221     }
6222   }
6223 
6224   if (DataDwordVT.isVector())
6225     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6226                           NumDataDwords - MaskPopDwords);
6227 
6228   if (IsD16)
6229     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6230 
6231   EVT LegalReqRetVT = ReqRetVT;
6232   if (!ReqRetVT.isVector()) {
6233     if (!Data.getValueType().isInteger())
6234       Data = DAG.getNode(ISD::BITCAST, DL,
6235                          Data.getValueType().changeTypeToInteger(), Data);
6236     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6237   } else {
6238     // We need to widen the return vector to a legal type
6239     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6240         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6241       LegalReqRetVT =
6242           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6243                            ReqRetVT.getVectorNumElements() + 1);
6244     }
6245   }
6246   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6247 
6248   if (IsTexFail) {
6249     TexFail =
6250         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6251                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6252 
6253     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6254   }
6255 
6256   if (Result->getNumValues() == 1)
6257     return Data;
6258 
6259   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6260 }
6261 
6262 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6263                          SDValue *LWE, bool &IsTexFail) {
6264   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6265 
6266   uint64_t Value = TexFailCtrlConst->getZExtValue();
6267   if (Value) {
6268     IsTexFail = true;
6269   }
6270 
6271   SDLoc DL(TexFailCtrlConst);
6272   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6273   Value &= ~(uint64_t)0x1;
6274   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6275   Value &= ~(uint64_t)0x2;
6276 
6277   return Value == 0;
6278 }
6279 
6280 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6281                                       MVT PackVectorVT,
6282                                       SmallVectorImpl<SDValue> &PackedAddrs,
6283                                       unsigned DimIdx, unsigned EndIdx,
6284                                       unsigned NumGradients) {
6285   SDLoc DL(Op);
6286   for (unsigned I = DimIdx; I < EndIdx; I++) {
6287     SDValue Addr = Op.getOperand(I);
6288 
6289     // Gradients are packed with undef for each coordinate.
6290     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6291     // 1D: undef,dx/dh; undef,dx/dv
6292     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6293     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6294     if (((I + 1) >= EndIdx) ||
6295         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6296                                          I == DimIdx + NumGradients - 1))) {
6297       if (Addr.getValueType() != MVT::i16)
6298         Addr = DAG.getBitcast(MVT::i16, Addr);
6299       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6300     } else {
6301       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6302       I++;
6303     }
6304     Addr = DAG.getBitcast(MVT::f32, Addr);
6305     PackedAddrs.push_back(Addr);
6306   }
6307 }
6308 
6309 SDValue SITargetLowering::lowerImage(SDValue Op,
6310                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6311                                      SelectionDAG &DAG, bool WithChain) const {
6312   SDLoc DL(Op);
6313   MachineFunction &MF = DAG.getMachineFunction();
6314   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6315   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6316       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6317   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6318   unsigned IntrOpcode = Intr->BaseOpcode;
6319   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6320 
6321   SmallVector<EVT, 3> ResultTypes(Op->values());
6322   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6323   bool IsD16 = false;
6324   bool IsG16 = false;
6325   bool IsA16 = false;
6326   SDValue VData;
6327   int NumVDataDwords;
6328   bool AdjustRetType = false;
6329 
6330   // Offset of intrinsic arguments
6331   const unsigned ArgOffset = WithChain ? 2 : 1;
6332 
6333   unsigned DMask;
6334   unsigned DMaskLanes = 0;
6335 
6336   if (BaseOpcode->Atomic) {
6337     VData = Op.getOperand(2);
6338 
6339     bool Is64Bit = VData.getValueType() == MVT::i64;
6340     if (BaseOpcode->AtomicX2) {
6341       SDValue VData2 = Op.getOperand(3);
6342       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6343                                  {VData, VData2});
6344       if (Is64Bit)
6345         VData = DAG.getBitcast(MVT::v4i32, VData);
6346 
6347       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6348       DMask = Is64Bit ? 0xf : 0x3;
6349       NumVDataDwords = Is64Bit ? 4 : 2;
6350     } else {
6351       DMask = Is64Bit ? 0x3 : 0x1;
6352       NumVDataDwords = Is64Bit ? 2 : 1;
6353     }
6354   } else {
6355     auto *DMaskConst =
6356         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6357     DMask = DMaskConst->getZExtValue();
6358     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6359 
6360     if (BaseOpcode->Store) {
6361       VData = Op.getOperand(2);
6362 
6363       MVT StoreVT = VData.getSimpleValueType();
6364       if (StoreVT.getScalarType() == MVT::f16) {
6365         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6366           return Op; // D16 is unsupported for this instruction
6367 
6368         IsD16 = true;
6369         VData = handleD16VData(VData, DAG, true);
6370       }
6371 
6372       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6373     } else {
6374       // Work out the num dwords based on the dmask popcount and underlying type
6375       // and whether packing is supported.
6376       MVT LoadVT = ResultTypes[0].getSimpleVT();
6377       if (LoadVT.getScalarType() == MVT::f16) {
6378         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6379           return Op; // D16 is unsupported for this instruction
6380 
6381         IsD16 = true;
6382       }
6383 
6384       // Confirm that the return type is large enough for the dmask specified
6385       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6386           (!LoadVT.isVector() && DMaskLanes > 1))
6387           return Op;
6388 
6389       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6390       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6391       // instructions.
6392       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6393           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6394         NumVDataDwords = (DMaskLanes + 1) / 2;
6395       else
6396         NumVDataDwords = DMaskLanes;
6397 
6398       AdjustRetType = true;
6399     }
6400   }
6401 
6402   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6403   SmallVector<SDValue, 4> VAddrs;
6404 
6405   // Check for 16 bit addresses or derivatives and pack if true.
6406   MVT VAddrVT =
6407       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6408   MVT VAddrScalarVT = VAddrVT.getScalarType();
6409   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6410   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6411 
6412   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6413   VAddrScalarVT = VAddrVT.getScalarType();
6414   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6415   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6416 
6417   // Push back extra arguments.
6418   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6419     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6420       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6421       // Special handling of bias when A16 is on. Bias is of type half but
6422       // occupies full 32-bit.
6423       SDValue Bias = DAG.getBuildVector(
6424           MVT::v2f16, DL,
6425           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6426       VAddrs.push_back(Bias);
6427     } else {
6428       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6429              "Bias needs to be converted to 16 bit in A16 mode");
6430       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6431     }
6432   }
6433 
6434   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6435     // 16 bit gradients are supported, but are tied to the A16 control
6436     // so both gradients and addresses must be 16 bit
6437     LLVM_DEBUG(
6438         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6439                   "require 16 bit args for both gradients and addresses");
6440     return Op;
6441   }
6442 
6443   if (IsA16) {
6444     if (!ST->hasA16()) {
6445       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6446                            "support 16 bit addresses\n");
6447       return Op;
6448     }
6449   }
6450 
6451   // We've dealt with incorrect input so we know that if IsA16, IsG16
6452   // are set then we have to compress/pack operands (either address,
6453   // gradient or both)
6454   // In the case where a16 and gradients are tied (no G16 support) then we
6455   // have already verified that both IsA16 and IsG16 are true
6456   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6457     // Activate g16
6458     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6459         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6460     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6461   }
6462 
6463   // Add gradients (packed or unpacked)
6464   if (IsG16) {
6465     // Pack the gradients
6466     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6467     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6468                               ArgOffset + Intr->GradientStart,
6469                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6470   } else {
6471     for (unsigned I = ArgOffset + Intr->GradientStart;
6472          I < ArgOffset + Intr->CoordStart; I++)
6473       VAddrs.push_back(Op.getOperand(I));
6474   }
6475 
6476   // Add addresses (packed or unpacked)
6477   if (IsA16) {
6478     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6479                               ArgOffset + Intr->CoordStart, VAddrEnd,
6480                               0 /* No gradients */);
6481   } else {
6482     // Add uncompressed address
6483     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6484       VAddrs.push_back(Op.getOperand(I));
6485   }
6486 
6487   // If the register allocator cannot place the address registers contiguously
6488   // without introducing moves, then using the non-sequential address encoding
6489   // is always preferable, since it saves VALU instructions and is usually a
6490   // wash in terms of code size or even better.
6491   //
6492   // However, we currently have no way of hinting to the register allocator that
6493   // MIMG addresses should be placed contiguously when it is possible to do so,
6494   // so force non-NSA for the common 2-address case as a heuristic.
6495   //
6496   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6497   // allocation when possible.
6498   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6499                 VAddrs.size() >= 3 &&
6500                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6501   SDValue VAddr;
6502   if (!UseNSA)
6503     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6504 
6505   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6506   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6507   SDValue Unorm;
6508   if (!BaseOpcode->Sampler) {
6509     Unorm = True;
6510   } else {
6511     auto UnormConst =
6512         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6513 
6514     Unorm = UnormConst->getZExtValue() ? True : False;
6515   }
6516 
6517   SDValue TFE;
6518   SDValue LWE;
6519   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6520   bool IsTexFail = false;
6521   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6522     return Op;
6523 
6524   if (IsTexFail) {
6525     if (!DMaskLanes) {
6526       // Expecting to get an error flag since TFC is on - and dmask is 0
6527       // Force dmask to be at least 1 otherwise the instruction will fail
6528       DMask = 0x1;
6529       DMaskLanes = 1;
6530       NumVDataDwords = 1;
6531     }
6532     NumVDataDwords += 1;
6533     AdjustRetType = true;
6534   }
6535 
6536   // Has something earlier tagged that the return type needs adjusting
6537   // This happens if the instruction is a load or has set TexFailCtrl flags
6538   if (AdjustRetType) {
6539     // NumVDataDwords reflects the true number of dwords required in the return type
6540     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6541       // This is a no-op load. This can be eliminated
6542       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6543       if (isa<MemSDNode>(Op))
6544         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6545       return Undef;
6546     }
6547 
6548     EVT NewVT = NumVDataDwords > 1 ?
6549                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6550                 : MVT::i32;
6551 
6552     ResultTypes[0] = NewVT;
6553     if (ResultTypes.size() == 3) {
6554       // Original result was aggregate type used for TexFailCtrl results
6555       // The actual instruction returns as a vector type which has now been
6556       // created. Remove the aggregate result.
6557       ResultTypes.erase(&ResultTypes[1]);
6558     }
6559   }
6560 
6561   unsigned CPol = cast<ConstantSDNode>(
6562       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6563   if (BaseOpcode->Atomic)
6564     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6565   if (CPol & ~AMDGPU::CPol::ALL)
6566     return Op;
6567 
6568   SmallVector<SDValue, 26> Ops;
6569   if (BaseOpcode->Store || BaseOpcode->Atomic)
6570     Ops.push_back(VData); // vdata
6571   if (UseNSA)
6572     append_range(Ops, VAddrs);
6573   else
6574     Ops.push_back(VAddr);
6575   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6576   if (BaseOpcode->Sampler)
6577     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6578   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6579   if (IsGFX10Plus)
6580     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6581   Ops.push_back(Unorm);
6582   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6583   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6584                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6585   if (IsGFX10Plus)
6586     Ops.push_back(IsA16 ? True : False);
6587   if (!Subtarget->hasGFX90AInsts()) {
6588     Ops.push_back(TFE); //tfe
6589   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6590     report_fatal_error("TFE is not supported on this GPU");
6591   }
6592   Ops.push_back(LWE); // lwe
6593   if (!IsGFX10Plus)
6594     Ops.push_back(DimInfo->DA ? True : False);
6595   if (BaseOpcode->HasD16)
6596     Ops.push_back(IsD16 ? True : False);
6597   if (isa<MemSDNode>(Op))
6598     Ops.push_back(Op.getOperand(0)); // chain
6599 
6600   int NumVAddrDwords =
6601       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6602   int Opcode = -1;
6603 
6604   if (IsGFX10Plus) {
6605     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6606                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6607                                           : AMDGPU::MIMGEncGfx10Default,
6608                                    NumVDataDwords, NumVAddrDwords);
6609   } else {
6610     if (Subtarget->hasGFX90AInsts()) {
6611       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6612                                      NumVDataDwords, NumVAddrDwords);
6613       if (Opcode == -1)
6614         report_fatal_error(
6615             "requested image instruction is not supported on this GPU");
6616     }
6617     if (Opcode == -1 &&
6618         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6619       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6620                                      NumVDataDwords, NumVAddrDwords);
6621     if (Opcode == -1)
6622       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6623                                      NumVDataDwords, NumVAddrDwords);
6624   }
6625   assert(Opcode != -1);
6626 
6627   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6628   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6629     MachineMemOperand *MemRef = MemOp->getMemOperand();
6630     DAG.setNodeMemRefs(NewNode, {MemRef});
6631   }
6632 
6633   if (BaseOpcode->AtomicX2) {
6634     SmallVector<SDValue, 1> Elt;
6635     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6636     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6637   }
6638   if (BaseOpcode->Store)
6639     return SDValue(NewNode, 0);
6640   return constructRetValue(DAG, NewNode,
6641                            OrigResultTypes, IsTexFail,
6642                            Subtarget->hasUnpackedD16VMem(), IsD16,
6643                            DMaskLanes, NumVDataDwords, DL);
6644 }
6645 
6646 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6647                                        SDValue Offset, SDValue CachePolicy,
6648                                        SelectionDAG &DAG) const {
6649   MachineFunction &MF = DAG.getMachineFunction();
6650 
6651   const DataLayout &DataLayout = DAG.getDataLayout();
6652   Align Alignment =
6653       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6654 
6655   MachineMemOperand *MMO = MF.getMachineMemOperand(
6656       MachinePointerInfo(),
6657       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6658           MachineMemOperand::MOInvariant,
6659       VT.getStoreSize(), Alignment);
6660 
6661   if (!Offset->isDivergent()) {
6662     SDValue Ops[] = {
6663         Rsrc,
6664         Offset, // Offset
6665         CachePolicy
6666     };
6667 
6668     // Widen vec3 load to vec4.
6669     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6670       EVT WidenedVT =
6671           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6672       auto WidenedOp = DAG.getMemIntrinsicNode(
6673           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6674           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6675       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6676                                    DAG.getVectorIdxConstant(0, DL));
6677       return Subvector;
6678     }
6679 
6680     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6681                                    DAG.getVTList(VT), Ops, VT, MMO);
6682   }
6683 
6684   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6685   // assume that the buffer is unswizzled.
6686   SmallVector<SDValue, 4> Loads;
6687   unsigned NumLoads = 1;
6688   MVT LoadVT = VT.getSimpleVT();
6689   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6690   assert((LoadVT.getScalarType() == MVT::i32 ||
6691           LoadVT.getScalarType() == MVT::f32));
6692 
6693   if (NumElts == 8 || NumElts == 16) {
6694     NumLoads = NumElts / 4;
6695     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6696   }
6697 
6698   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6699   SDValue Ops[] = {
6700       DAG.getEntryNode(),                               // Chain
6701       Rsrc,                                             // rsrc
6702       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6703       {},                                               // voffset
6704       {},                                               // soffset
6705       {},                                               // offset
6706       CachePolicy,                                      // cachepolicy
6707       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6708   };
6709 
6710   // Use the alignment to ensure that the required offsets will fit into the
6711   // immediate offsets.
6712   setBufferOffsets(Offset, DAG, &Ops[3],
6713                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6714 
6715   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6716   for (unsigned i = 0; i < NumLoads; ++i) {
6717     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6718     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6719                                         LoadVT, MMO, DAG));
6720   }
6721 
6722   if (NumElts == 8 || NumElts == 16)
6723     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6724 
6725   return Loads[0];
6726 }
6727 
6728 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6729                                                   SelectionDAG &DAG) const {
6730   MachineFunction &MF = DAG.getMachineFunction();
6731   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6732 
6733   EVT VT = Op.getValueType();
6734   SDLoc DL(Op);
6735   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6736 
6737   // TODO: Should this propagate fast-math-flags?
6738 
6739   switch (IntrinsicID) {
6740   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6741     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6742       return emitNonHSAIntrinsicError(DAG, DL, VT);
6743     return getPreloadedValue(DAG, *MFI, VT,
6744                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6745   }
6746   case Intrinsic::amdgcn_dispatch_ptr:
6747   case Intrinsic::amdgcn_queue_ptr: {
6748     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6749       DiagnosticInfoUnsupported BadIntrin(
6750           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6751           DL.getDebugLoc());
6752       DAG.getContext()->diagnose(BadIntrin);
6753       return DAG.getUNDEF(VT);
6754     }
6755 
6756     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6757       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6758     return getPreloadedValue(DAG, *MFI, VT, RegID);
6759   }
6760   case Intrinsic::amdgcn_implicitarg_ptr: {
6761     if (MFI->isEntryFunction())
6762       return getImplicitArgPtr(DAG, DL);
6763     return getPreloadedValue(DAG, *MFI, VT,
6764                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6765   }
6766   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6767     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6768       // This only makes sense to call in a kernel, so just lower to null.
6769       return DAG.getConstant(0, DL, VT);
6770     }
6771 
6772     return getPreloadedValue(DAG, *MFI, VT,
6773                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6774   }
6775   case Intrinsic::amdgcn_dispatch_id: {
6776     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6777   }
6778   case Intrinsic::amdgcn_rcp:
6779     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6780   case Intrinsic::amdgcn_rsq:
6781     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6782   case Intrinsic::amdgcn_rsq_legacy:
6783     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6784       return emitRemovedIntrinsicError(DAG, DL, VT);
6785     return SDValue();
6786   case Intrinsic::amdgcn_rcp_legacy:
6787     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6788       return emitRemovedIntrinsicError(DAG, DL, VT);
6789     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6790   case Intrinsic::amdgcn_rsq_clamp: {
6791     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6792       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6793 
6794     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6795     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6796     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6797 
6798     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6799     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6800                               DAG.getConstantFP(Max, DL, VT));
6801     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6802                        DAG.getConstantFP(Min, DL, VT));
6803   }
6804   case Intrinsic::r600_read_ngroups_x:
6805     if (Subtarget->isAmdHsaOS())
6806       return emitNonHSAIntrinsicError(DAG, DL, VT);
6807 
6808     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6809                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6810                                     false);
6811   case Intrinsic::r600_read_ngroups_y:
6812     if (Subtarget->isAmdHsaOS())
6813       return emitNonHSAIntrinsicError(DAG, DL, VT);
6814 
6815     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6816                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6817                                     false);
6818   case Intrinsic::r600_read_ngroups_z:
6819     if (Subtarget->isAmdHsaOS())
6820       return emitNonHSAIntrinsicError(DAG, DL, VT);
6821 
6822     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6823                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6824                                     false);
6825   case Intrinsic::r600_read_global_size_x:
6826     if (Subtarget->isAmdHsaOS())
6827       return emitNonHSAIntrinsicError(DAG, DL, VT);
6828 
6829     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6830                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6831                                     Align(4), false);
6832   case Intrinsic::r600_read_global_size_y:
6833     if (Subtarget->isAmdHsaOS())
6834       return emitNonHSAIntrinsicError(DAG, DL, VT);
6835 
6836     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6837                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6838                                     Align(4), false);
6839   case Intrinsic::r600_read_global_size_z:
6840     if (Subtarget->isAmdHsaOS())
6841       return emitNonHSAIntrinsicError(DAG, DL, VT);
6842 
6843     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6844                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6845                                     Align(4), false);
6846   case Intrinsic::r600_read_local_size_x:
6847     if (Subtarget->isAmdHsaOS())
6848       return emitNonHSAIntrinsicError(DAG, DL, VT);
6849 
6850     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6851                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6852   case Intrinsic::r600_read_local_size_y:
6853     if (Subtarget->isAmdHsaOS())
6854       return emitNonHSAIntrinsicError(DAG, DL, VT);
6855 
6856     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6857                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6858   case Intrinsic::r600_read_local_size_z:
6859     if (Subtarget->isAmdHsaOS())
6860       return emitNonHSAIntrinsicError(DAG, DL, VT);
6861 
6862     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6863                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6864   case Intrinsic::amdgcn_workgroup_id_x:
6865     return getPreloadedValue(DAG, *MFI, VT,
6866                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6867   case Intrinsic::amdgcn_workgroup_id_y:
6868     return getPreloadedValue(DAG, *MFI, VT,
6869                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6870   case Intrinsic::amdgcn_workgroup_id_z:
6871     return getPreloadedValue(DAG, *MFI, VT,
6872                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6873   case Intrinsic::amdgcn_workitem_id_x:
6874     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6875       return DAG.getConstant(0, DL, MVT::i32);
6876 
6877     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6878                           SDLoc(DAG.getEntryNode()),
6879                           MFI->getArgInfo().WorkItemIDX);
6880   case Intrinsic::amdgcn_workitem_id_y:
6881     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6882       return DAG.getConstant(0, DL, MVT::i32);
6883 
6884     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6885                           SDLoc(DAG.getEntryNode()),
6886                           MFI->getArgInfo().WorkItemIDY);
6887   case Intrinsic::amdgcn_workitem_id_z:
6888     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6889       return DAG.getConstant(0, DL, MVT::i32);
6890 
6891     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6892                           SDLoc(DAG.getEntryNode()),
6893                           MFI->getArgInfo().WorkItemIDZ);
6894   case Intrinsic::amdgcn_wavefrontsize:
6895     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6896                            SDLoc(Op), MVT::i32);
6897   case Intrinsic::amdgcn_s_buffer_load: {
6898     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6899     if (CPol & ~AMDGPU::CPol::ALL)
6900       return Op;
6901     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6902                         DAG);
6903   }
6904   case Intrinsic::amdgcn_fdiv_fast:
6905     return lowerFDIV_FAST(Op, DAG);
6906   case Intrinsic::amdgcn_sin:
6907     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6908 
6909   case Intrinsic::amdgcn_cos:
6910     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6911 
6912   case Intrinsic::amdgcn_mul_u24:
6913     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6914   case Intrinsic::amdgcn_mul_i24:
6915     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6916 
6917   case Intrinsic::amdgcn_log_clamp: {
6918     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6919       return SDValue();
6920 
6921     return emitRemovedIntrinsicError(DAG, DL, VT);
6922   }
6923   case Intrinsic::amdgcn_ldexp:
6924     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6925                        Op.getOperand(1), Op.getOperand(2));
6926 
6927   case Intrinsic::amdgcn_fract:
6928     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6929 
6930   case Intrinsic::amdgcn_class:
6931     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6932                        Op.getOperand(1), Op.getOperand(2));
6933   case Intrinsic::amdgcn_div_fmas:
6934     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6936                        Op.getOperand(4));
6937 
6938   case Intrinsic::amdgcn_div_fixup:
6939     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6940                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6941 
6942   case Intrinsic::amdgcn_div_scale: {
6943     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6944 
6945     // Translate to the operands expected by the machine instruction. The
6946     // first parameter must be the same as the first instruction.
6947     SDValue Numerator = Op.getOperand(1);
6948     SDValue Denominator = Op.getOperand(2);
6949 
6950     // Note this order is opposite of the machine instruction's operations,
6951     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6952     // intrinsic has the numerator as the first operand to match a normal
6953     // division operation.
6954 
6955     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6956 
6957     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6958                        Denominator, Numerator);
6959   }
6960   case Intrinsic::amdgcn_icmp: {
6961     // There is a Pat that handles this variant, so return it as-is.
6962     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6963         Op.getConstantOperandVal(2) == 0 &&
6964         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6965       return Op;
6966     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6967   }
6968   case Intrinsic::amdgcn_fcmp: {
6969     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6970   }
6971   case Intrinsic::amdgcn_ballot:
6972     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6973   case Intrinsic::amdgcn_fmed3:
6974     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6975                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6976   case Intrinsic::amdgcn_fdot2:
6977     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6978                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6979                        Op.getOperand(4));
6980   case Intrinsic::amdgcn_fmul_legacy:
6981     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6982                        Op.getOperand(1), Op.getOperand(2));
6983   case Intrinsic::amdgcn_sffbh:
6984     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6985   case Intrinsic::amdgcn_sbfe:
6986     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6987                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6988   case Intrinsic::amdgcn_ubfe:
6989     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6990                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6991   case Intrinsic::amdgcn_cvt_pkrtz:
6992   case Intrinsic::amdgcn_cvt_pknorm_i16:
6993   case Intrinsic::amdgcn_cvt_pknorm_u16:
6994   case Intrinsic::amdgcn_cvt_pk_i16:
6995   case Intrinsic::amdgcn_cvt_pk_u16: {
6996     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6997     EVT VT = Op.getValueType();
6998     unsigned Opcode;
6999 
7000     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7001       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7002     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7003       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7004     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7005       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7006     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7007       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7008     else
7009       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7010 
7011     if (isTypeLegal(VT))
7012       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7013 
7014     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7015                                Op.getOperand(1), Op.getOperand(2));
7016     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7017   }
7018   case Intrinsic::amdgcn_fmad_ftz:
7019     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7020                        Op.getOperand(2), Op.getOperand(3));
7021 
7022   case Intrinsic::amdgcn_if_break:
7023     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7024                                       Op->getOperand(1), Op->getOperand(2)), 0);
7025 
7026   case Intrinsic::amdgcn_groupstaticsize: {
7027     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7028     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7029       return Op;
7030 
7031     const Module *M = MF.getFunction().getParent();
7032     const GlobalValue *GV =
7033         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7034     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7035                                             SIInstrInfo::MO_ABS32_LO);
7036     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7037   }
7038   case Intrinsic::amdgcn_is_shared:
7039   case Intrinsic::amdgcn_is_private: {
7040     SDLoc SL(Op);
7041     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7042       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7043     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7044     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7045                                  Op.getOperand(1));
7046 
7047     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7048                                 DAG.getConstant(1, SL, MVT::i32));
7049     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7050   }
7051   case Intrinsic::amdgcn_perm:
7052     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7053                        Op.getOperand(2), Op.getOperand(3));
7054   case Intrinsic::amdgcn_reloc_constant: {
7055     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7056     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7057     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7058     auto RelocSymbol = cast<GlobalVariable>(
7059         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7060     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7061                                             SIInstrInfo::MO_ABS32_LO);
7062     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7063   }
7064   default:
7065     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7066             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7067       return lowerImage(Op, ImageDimIntr, DAG, false);
7068 
7069     return Op;
7070   }
7071 }
7072 
7073 /// Update \p MMO based on the offset inputs to an intrinsic.
7074 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7075                             SDValue SOffset, SDValue Offset,
7076                             SDValue VIndex = SDValue()) {
7077   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7078       !isa<ConstantSDNode>(Offset)) {
7079     // The combined offset is not known to be constant, so we cannot represent
7080     // it in the MMO. Give up.
7081     MMO->setValue((Value *)nullptr);
7082     return;
7083   }
7084 
7085   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7086                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7087     // The strided index component of the address is not known to be zero, so we
7088     // cannot represent it in the MMO. Give up.
7089     MMO->setValue((Value *)nullptr);
7090     return;
7091   }
7092 
7093   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7094                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7095                  cast<ConstantSDNode>(Offset)->getSExtValue());
7096 }
7097 
7098 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7099                                                      SelectionDAG &DAG,
7100                                                      unsigned NewOpcode) const {
7101   SDLoc DL(Op);
7102 
7103   SDValue VData = Op.getOperand(2);
7104   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7105   SDValue Ops[] = {
7106     Op.getOperand(0), // Chain
7107     VData,            // vdata
7108     Op.getOperand(3), // rsrc
7109     DAG.getConstant(0, DL, MVT::i32), // vindex
7110     Offsets.first,    // voffset
7111     Op.getOperand(5), // soffset
7112     Offsets.second,   // offset
7113     Op.getOperand(6), // cachepolicy
7114     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7115   };
7116 
7117   auto *M = cast<MemSDNode>(Op);
7118   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7119 
7120   EVT MemVT = VData.getValueType();
7121   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7122                                  M->getMemOperand());
7123 }
7124 
7125 // Return a value to use for the idxen operand by examining the vindex operand.
7126 static unsigned getIdxEn(SDValue VIndex) {
7127   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7128     // No need to set idxen if vindex is known to be zero.
7129     return VIndexC->getZExtValue() != 0;
7130   return 1;
7131 }
7132 
7133 SDValue
7134 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7135                                                 unsigned NewOpcode) const {
7136   SDLoc DL(Op);
7137 
7138   SDValue VData = Op.getOperand(2);
7139   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7140   SDValue Ops[] = {
7141     Op.getOperand(0), // Chain
7142     VData,            // vdata
7143     Op.getOperand(3), // rsrc
7144     Op.getOperand(4), // vindex
7145     Offsets.first,    // voffset
7146     Op.getOperand(6), // soffset
7147     Offsets.second,   // offset
7148     Op.getOperand(7), // cachepolicy
7149     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7150   };
7151 
7152   auto *M = cast<MemSDNode>(Op);
7153   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7154 
7155   EVT MemVT = VData.getValueType();
7156   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7157                                  M->getMemOperand());
7158 }
7159 
7160 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7161                                                  SelectionDAG &DAG) const {
7162   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7163   SDLoc DL(Op);
7164 
7165   switch (IntrID) {
7166   case Intrinsic::amdgcn_ds_ordered_add:
7167   case Intrinsic::amdgcn_ds_ordered_swap: {
7168     MemSDNode *M = cast<MemSDNode>(Op);
7169     SDValue Chain = M->getOperand(0);
7170     SDValue M0 = M->getOperand(2);
7171     SDValue Value = M->getOperand(3);
7172     unsigned IndexOperand = M->getConstantOperandVal(7);
7173     unsigned WaveRelease = M->getConstantOperandVal(8);
7174     unsigned WaveDone = M->getConstantOperandVal(9);
7175 
7176     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7177     IndexOperand &= ~0x3f;
7178     unsigned CountDw = 0;
7179 
7180     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7181       CountDw = (IndexOperand >> 24) & 0xf;
7182       IndexOperand &= ~(0xf << 24);
7183 
7184       if (CountDw < 1 || CountDw > 4) {
7185         report_fatal_error(
7186             "ds_ordered_count: dword count must be between 1 and 4");
7187       }
7188     }
7189 
7190     if (IndexOperand)
7191       report_fatal_error("ds_ordered_count: bad index operand");
7192 
7193     if (WaveDone && !WaveRelease)
7194       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7195 
7196     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7197     unsigned ShaderType =
7198         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7199     unsigned Offset0 = OrderedCountIndex << 2;
7200     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7201                        (Instruction << 4);
7202 
7203     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7204       Offset1 |= (CountDw - 1) << 6;
7205 
7206     unsigned Offset = Offset0 | (Offset1 << 8);
7207 
7208     SDValue Ops[] = {
7209       Chain,
7210       Value,
7211       DAG.getTargetConstant(Offset, DL, MVT::i16),
7212       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7213     };
7214     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7215                                    M->getVTList(), Ops, M->getMemoryVT(),
7216                                    M->getMemOperand());
7217   }
7218   case Intrinsic::amdgcn_ds_fadd: {
7219     MemSDNode *M = cast<MemSDNode>(Op);
7220     unsigned Opc;
7221     switch (IntrID) {
7222     case Intrinsic::amdgcn_ds_fadd:
7223       Opc = ISD::ATOMIC_LOAD_FADD;
7224       break;
7225     }
7226 
7227     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7228                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7229                          M->getMemOperand());
7230   }
7231   case Intrinsic::amdgcn_atomic_inc:
7232   case Intrinsic::amdgcn_atomic_dec:
7233   case Intrinsic::amdgcn_ds_fmin:
7234   case Intrinsic::amdgcn_ds_fmax: {
7235     MemSDNode *M = cast<MemSDNode>(Op);
7236     unsigned Opc;
7237     switch (IntrID) {
7238     case Intrinsic::amdgcn_atomic_inc:
7239       Opc = AMDGPUISD::ATOMIC_INC;
7240       break;
7241     case Intrinsic::amdgcn_atomic_dec:
7242       Opc = AMDGPUISD::ATOMIC_DEC;
7243       break;
7244     case Intrinsic::amdgcn_ds_fmin:
7245       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7246       break;
7247     case Intrinsic::amdgcn_ds_fmax:
7248       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7249       break;
7250     default:
7251       llvm_unreachable("Unknown intrinsic!");
7252     }
7253     SDValue Ops[] = {
7254       M->getOperand(0), // Chain
7255       M->getOperand(2), // Ptr
7256       M->getOperand(3)  // Value
7257     };
7258 
7259     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7260                                    M->getMemoryVT(), M->getMemOperand());
7261   }
7262   case Intrinsic::amdgcn_buffer_load:
7263   case Intrinsic::amdgcn_buffer_load_format: {
7264     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7265     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7266     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7267     SDValue Ops[] = {
7268       Op.getOperand(0), // Chain
7269       Op.getOperand(2), // rsrc
7270       Op.getOperand(3), // vindex
7271       SDValue(),        // voffset -- will be set by setBufferOffsets
7272       SDValue(),        // soffset -- will be set by setBufferOffsets
7273       SDValue(),        // offset -- will be set by setBufferOffsets
7274       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7275       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7276     };
7277     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7278 
7279     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7280         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7281 
7282     EVT VT = Op.getValueType();
7283     EVT IntVT = VT.changeTypeToInteger();
7284     auto *M = cast<MemSDNode>(Op);
7285     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7286     EVT LoadVT = Op.getValueType();
7287 
7288     if (LoadVT.getScalarType() == MVT::f16)
7289       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7290                                  M, DAG, Ops);
7291 
7292     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7293     if (LoadVT.getScalarType() == MVT::i8 ||
7294         LoadVT.getScalarType() == MVT::i16)
7295       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7296 
7297     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7298                                M->getMemOperand(), DAG);
7299   }
7300   case Intrinsic::amdgcn_raw_buffer_load:
7301   case Intrinsic::amdgcn_raw_buffer_load_format: {
7302     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7303 
7304     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7305     SDValue Ops[] = {
7306       Op.getOperand(0), // Chain
7307       Op.getOperand(2), // rsrc
7308       DAG.getConstant(0, DL, MVT::i32), // vindex
7309       Offsets.first,    // voffset
7310       Op.getOperand(4), // soffset
7311       Offsets.second,   // offset
7312       Op.getOperand(5), // cachepolicy, swizzled buffer
7313       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7314     };
7315 
7316     auto *M = cast<MemSDNode>(Op);
7317     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7318     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7319   }
7320   case Intrinsic::amdgcn_struct_buffer_load:
7321   case Intrinsic::amdgcn_struct_buffer_load_format: {
7322     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7323 
7324     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7325     SDValue Ops[] = {
7326       Op.getOperand(0), // Chain
7327       Op.getOperand(2), // rsrc
7328       Op.getOperand(3), // vindex
7329       Offsets.first,    // voffset
7330       Op.getOperand(5), // soffset
7331       Offsets.second,   // offset
7332       Op.getOperand(6), // cachepolicy, swizzled buffer
7333       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7334     };
7335 
7336     auto *M = cast<MemSDNode>(Op);
7337     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7338     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7339   }
7340   case Intrinsic::amdgcn_tbuffer_load: {
7341     MemSDNode *M = cast<MemSDNode>(Op);
7342     EVT LoadVT = Op.getValueType();
7343 
7344     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7345     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7346     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7347     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7348     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7349     SDValue Ops[] = {
7350       Op.getOperand(0),  // Chain
7351       Op.getOperand(2),  // rsrc
7352       Op.getOperand(3),  // vindex
7353       Op.getOperand(4),  // voffset
7354       Op.getOperand(5),  // soffset
7355       Op.getOperand(6),  // offset
7356       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7357       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7358       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7359     };
7360 
7361     if (LoadVT.getScalarType() == MVT::f16)
7362       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7363                                  M, DAG, Ops);
7364     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7365                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7366                                DAG);
7367   }
7368   case Intrinsic::amdgcn_raw_tbuffer_load: {
7369     MemSDNode *M = cast<MemSDNode>(Op);
7370     EVT LoadVT = Op.getValueType();
7371     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7372 
7373     SDValue Ops[] = {
7374       Op.getOperand(0),  // Chain
7375       Op.getOperand(2),  // rsrc
7376       DAG.getConstant(0, DL, MVT::i32), // vindex
7377       Offsets.first,     // voffset
7378       Op.getOperand(4),  // soffset
7379       Offsets.second,    // offset
7380       Op.getOperand(5),  // format
7381       Op.getOperand(6),  // cachepolicy, swizzled buffer
7382       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7383     };
7384 
7385     if (LoadVT.getScalarType() == MVT::f16)
7386       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7387                                  M, DAG, Ops);
7388     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7389                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7390                                DAG);
7391   }
7392   case Intrinsic::amdgcn_struct_tbuffer_load: {
7393     MemSDNode *M = cast<MemSDNode>(Op);
7394     EVT LoadVT = Op.getValueType();
7395     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7396 
7397     SDValue Ops[] = {
7398       Op.getOperand(0),  // Chain
7399       Op.getOperand(2),  // rsrc
7400       Op.getOperand(3),  // vindex
7401       Offsets.first,     // voffset
7402       Op.getOperand(5),  // soffset
7403       Offsets.second,    // offset
7404       Op.getOperand(6),  // format
7405       Op.getOperand(7),  // cachepolicy, swizzled buffer
7406       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7407     };
7408 
7409     if (LoadVT.getScalarType() == MVT::f16)
7410       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7411                                  M, DAG, Ops);
7412     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7413                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7414                                DAG);
7415   }
7416   case Intrinsic::amdgcn_buffer_atomic_swap:
7417   case Intrinsic::amdgcn_buffer_atomic_add:
7418   case Intrinsic::amdgcn_buffer_atomic_sub:
7419   case Intrinsic::amdgcn_buffer_atomic_csub:
7420   case Intrinsic::amdgcn_buffer_atomic_smin:
7421   case Intrinsic::amdgcn_buffer_atomic_umin:
7422   case Intrinsic::amdgcn_buffer_atomic_smax:
7423   case Intrinsic::amdgcn_buffer_atomic_umax:
7424   case Intrinsic::amdgcn_buffer_atomic_and:
7425   case Intrinsic::amdgcn_buffer_atomic_or:
7426   case Intrinsic::amdgcn_buffer_atomic_xor:
7427   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7428     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7429     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7430     SDValue Ops[] = {
7431       Op.getOperand(0), // Chain
7432       Op.getOperand(2), // vdata
7433       Op.getOperand(3), // rsrc
7434       Op.getOperand(4), // vindex
7435       SDValue(),        // voffset -- will be set by setBufferOffsets
7436       SDValue(),        // soffset -- will be set by setBufferOffsets
7437       SDValue(),        // offset -- will be set by setBufferOffsets
7438       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7439       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7440     };
7441     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7442 
7443     EVT VT = Op.getValueType();
7444 
7445     auto *M = cast<MemSDNode>(Op);
7446     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7447     unsigned Opcode = 0;
7448 
7449     switch (IntrID) {
7450     case Intrinsic::amdgcn_buffer_atomic_swap:
7451       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7452       break;
7453     case Intrinsic::amdgcn_buffer_atomic_add:
7454       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7455       break;
7456     case Intrinsic::amdgcn_buffer_atomic_sub:
7457       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7458       break;
7459     case Intrinsic::amdgcn_buffer_atomic_csub:
7460       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7461       break;
7462     case Intrinsic::amdgcn_buffer_atomic_smin:
7463       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7464       break;
7465     case Intrinsic::amdgcn_buffer_atomic_umin:
7466       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7467       break;
7468     case Intrinsic::amdgcn_buffer_atomic_smax:
7469       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7470       break;
7471     case Intrinsic::amdgcn_buffer_atomic_umax:
7472       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7473       break;
7474     case Intrinsic::amdgcn_buffer_atomic_and:
7475       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7476       break;
7477     case Intrinsic::amdgcn_buffer_atomic_or:
7478       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7479       break;
7480     case Intrinsic::amdgcn_buffer_atomic_xor:
7481       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7482       break;
7483     case Intrinsic::amdgcn_buffer_atomic_fadd:
7484       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7485         DiagnosticInfoUnsupported
7486           NoFpRet(DAG.getMachineFunction().getFunction(),
7487                   "return versions of fp atomics not supported",
7488                   DL.getDebugLoc(), DS_Error);
7489         DAG.getContext()->diagnose(NoFpRet);
7490         return SDValue();
7491       }
7492       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7493       break;
7494     default:
7495       llvm_unreachable("unhandled atomic opcode");
7496     }
7497 
7498     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7499                                    M->getMemOperand());
7500   }
7501   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7502     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7503   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7504     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7505   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7506     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7507   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7508     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7509   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7510     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7511   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7512     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7513   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7514     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7515   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7516     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7517   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7518     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7519   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7520     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7521   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7522     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7523   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7524     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7525   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7526     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7527   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7528     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7529   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7530     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7531   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7532     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7533   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7534     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7535   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7536     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7537   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7538     return lowerStructBufferAtomicIntrin(Op, DAG,
7539                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7540   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7541     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7542   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7543     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7544   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7545     return lowerStructBufferAtomicIntrin(Op, DAG,
7546                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7547   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7548     return lowerStructBufferAtomicIntrin(Op, DAG,
7549                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7550   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7551     return lowerStructBufferAtomicIntrin(Op, DAG,
7552                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7553   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7554     return lowerStructBufferAtomicIntrin(Op, DAG,
7555                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7556   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7557     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7558   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7559     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7560   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7561     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7562   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7563     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7564   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7565     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7566 
7567   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7568     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7569     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7570     SDValue Ops[] = {
7571       Op.getOperand(0), // Chain
7572       Op.getOperand(2), // src
7573       Op.getOperand(3), // cmp
7574       Op.getOperand(4), // rsrc
7575       Op.getOperand(5), // vindex
7576       SDValue(),        // voffset -- will be set by setBufferOffsets
7577       SDValue(),        // soffset -- will be set by setBufferOffsets
7578       SDValue(),        // offset -- will be set by setBufferOffsets
7579       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7580       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7581     };
7582     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7583 
7584     EVT VT = Op.getValueType();
7585     auto *M = cast<MemSDNode>(Op);
7586     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7587 
7588     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7589                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7590   }
7591   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7592     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7593     SDValue Ops[] = {
7594       Op.getOperand(0), // Chain
7595       Op.getOperand(2), // src
7596       Op.getOperand(3), // cmp
7597       Op.getOperand(4), // rsrc
7598       DAG.getConstant(0, DL, MVT::i32), // vindex
7599       Offsets.first,    // voffset
7600       Op.getOperand(6), // soffset
7601       Offsets.second,   // offset
7602       Op.getOperand(7), // cachepolicy
7603       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7604     };
7605     EVT VT = Op.getValueType();
7606     auto *M = cast<MemSDNode>(Op);
7607     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7608 
7609     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7610                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7611   }
7612   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7613     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7614     SDValue Ops[] = {
7615       Op.getOperand(0), // Chain
7616       Op.getOperand(2), // src
7617       Op.getOperand(3), // cmp
7618       Op.getOperand(4), // rsrc
7619       Op.getOperand(5), // vindex
7620       Offsets.first,    // voffset
7621       Op.getOperand(7), // soffset
7622       Offsets.second,   // offset
7623       Op.getOperand(8), // cachepolicy
7624       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7625     };
7626     EVT VT = Op.getValueType();
7627     auto *M = cast<MemSDNode>(Op);
7628     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7629 
7630     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7631                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7632   }
7633   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7634     MemSDNode *M = cast<MemSDNode>(Op);
7635     SDValue NodePtr = M->getOperand(2);
7636     SDValue RayExtent = M->getOperand(3);
7637     SDValue RayOrigin = M->getOperand(4);
7638     SDValue RayDir = M->getOperand(5);
7639     SDValue RayInvDir = M->getOperand(6);
7640     SDValue TDescr = M->getOperand(7);
7641 
7642     assert(NodePtr.getValueType() == MVT::i32 ||
7643            NodePtr.getValueType() == MVT::i64);
7644     assert(RayDir.getValueType() == MVT::v3f16 ||
7645            RayDir.getValueType() == MVT::v3f32);
7646 
7647     if (!Subtarget->hasGFX10_AEncoding()) {
7648       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7649       return SDValue();
7650     }
7651 
7652     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7653     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7654     const unsigned NumVDataDwords = 4;
7655     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7656     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7657                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7658     const unsigned BaseOpcodes[2][2] = {
7659         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7660         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7661          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7662     int Opcode;
7663     if (UseNSA) {
7664       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7665                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7666                                      NumVAddrDwords);
7667     } else {
7668       Opcode = AMDGPU::getMIMGOpcode(
7669           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7670           PowerOf2Ceil(NumVAddrDwords));
7671     }
7672     assert(Opcode != -1);
7673 
7674     SmallVector<SDValue, 16> Ops;
7675 
7676     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7677       SmallVector<SDValue, 3> Lanes;
7678       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7679       if (Lanes[0].getValueSizeInBits() == 32) {
7680         for (unsigned I = 0; I < 3; ++I)
7681           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7682       } else {
7683         if (IsAligned) {
7684           Ops.push_back(
7685             DAG.getBitcast(MVT::i32,
7686                            DAG.getBuildVector(MVT::v2f16, DL,
7687                                               { Lanes[0], Lanes[1] })));
7688           Ops.push_back(Lanes[2]);
7689         } else {
7690           SDValue Elt0 = Ops.pop_back_val();
7691           Ops.push_back(
7692             DAG.getBitcast(MVT::i32,
7693                            DAG.getBuildVector(MVT::v2f16, DL,
7694                                               { Elt0, Lanes[0] })));
7695           Ops.push_back(
7696             DAG.getBitcast(MVT::i32,
7697                            DAG.getBuildVector(MVT::v2f16, DL,
7698                                               { Lanes[1], Lanes[2] })));
7699         }
7700       }
7701     };
7702 
7703     if (Is64)
7704       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7705     else
7706       Ops.push_back(NodePtr);
7707 
7708     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7709     packLanes(RayOrigin, true);
7710     packLanes(RayDir, true);
7711     packLanes(RayInvDir, false);
7712 
7713     if (!UseNSA) {
7714       // Build a single vector containing all the operands so far prepared.
7715       if (NumVAddrDwords > 8) {
7716         SDValue Undef = DAG.getUNDEF(MVT::i32);
7717         Ops.append(16 - Ops.size(), Undef);
7718       }
7719       assert(Ops.size() == 8 || Ops.size() == 16);
7720       SDValue MergedOps = DAG.getBuildVector(
7721           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7722       Ops.clear();
7723       Ops.push_back(MergedOps);
7724     }
7725 
7726     Ops.push_back(TDescr);
7727     if (IsA16)
7728       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7729     Ops.push_back(M->getChain());
7730 
7731     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7732     MachineMemOperand *MemRef = M->getMemOperand();
7733     DAG.setNodeMemRefs(NewNode, {MemRef});
7734     return SDValue(NewNode, 0);
7735   }
7736   case Intrinsic::amdgcn_global_atomic_fadd:
7737     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7738       DiagnosticInfoUnsupported
7739         NoFpRet(DAG.getMachineFunction().getFunction(),
7740                 "return versions of fp atomics not supported",
7741                 DL.getDebugLoc(), DS_Error);
7742       DAG.getContext()->diagnose(NoFpRet);
7743       return SDValue();
7744     }
7745     LLVM_FALLTHROUGH;
7746   case Intrinsic::amdgcn_global_atomic_fmin:
7747   case Intrinsic::amdgcn_global_atomic_fmax:
7748   case Intrinsic::amdgcn_flat_atomic_fadd:
7749   case Intrinsic::amdgcn_flat_atomic_fmin:
7750   case Intrinsic::amdgcn_flat_atomic_fmax: {
7751     MemSDNode *M = cast<MemSDNode>(Op);
7752     SDValue Ops[] = {
7753       M->getOperand(0), // Chain
7754       M->getOperand(2), // Ptr
7755       M->getOperand(3)  // Value
7756     };
7757     unsigned Opcode = 0;
7758     switch (IntrID) {
7759     case Intrinsic::amdgcn_global_atomic_fadd:
7760     case Intrinsic::amdgcn_flat_atomic_fadd: {
7761       EVT VT = Op.getOperand(3).getValueType();
7762       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7763                            DAG.getVTList(VT, MVT::Other), Ops,
7764                            M->getMemOperand());
7765     }
7766     case Intrinsic::amdgcn_global_atomic_fmin:
7767     case Intrinsic::amdgcn_flat_atomic_fmin: {
7768       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7769       break;
7770     }
7771     case Intrinsic::amdgcn_global_atomic_fmax:
7772     case Intrinsic::amdgcn_flat_atomic_fmax: {
7773       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7774       break;
7775     }
7776     default:
7777       llvm_unreachable("unhandled atomic opcode");
7778     }
7779     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7780                                    M->getVTList(), Ops, M->getMemoryVT(),
7781                                    M->getMemOperand());
7782   }
7783   default:
7784 
7785     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7786             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7787       return lowerImage(Op, ImageDimIntr, DAG, true);
7788 
7789     return SDValue();
7790   }
7791 }
7792 
7793 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7794 // dwordx4 if on SI.
7795 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7796                                               SDVTList VTList,
7797                                               ArrayRef<SDValue> Ops, EVT MemVT,
7798                                               MachineMemOperand *MMO,
7799                                               SelectionDAG &DAG) const {
7800   EVT VT = VTList.VTs[0];
7801   EVT WidenedVT = VT;
7802   EVT WidenedMemVT = MemVT;
7803   if (!Subtarget->hasDwordx3LoadStores() &&
7804       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7805     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7806                                  WidenedVT.getVectorElementType(), 4);
7807     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7808                                     WidenedMemVT.getVectorElementType(), 4);
7809     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7810   }
7811 
7812   assert(VTList.NumVTs == 2);
7813   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7814 
7815   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7816                                        WidenedMemVT, MMO);
7817   if (WidenedVT != VT) {
7818     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7819                                DAG.getVectorIdxConstant(0, DL));
7820     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7821   }
7822   return NewOp;
7823 }
7824 
7825 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7826                                          bool ImageStore) const {
7827   EVT StoreVT = VData.getValueType();
7828 
7829   // No change for f16 and legal vector D16 types.
7830   if (!StoreVT.isVector())
7831     return VData;
7832 
7833   SDLoc DL(VData);
7834   unsigned NumElements = StoreVT.getVectorNumElements();
7835 
7836   if (Subtarget->hasUnpackedD16VMem()) {
7837     // We need to unpack the packed data to store.
7838     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7839     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7840 
7841     EVT EquivStoreVT =
7842         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7843     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7844     return DAG.UnrollVectorOp(ZExt.getNode());
7845   }
7846 
7847   // The sq block of gfx8.1 does not estimate register use correctly for d16
7848   // image store instructions. The data operand is computed as if it were not a
7849   // d16 image instruction.
7850   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7851     // Bitcast to i16
7852     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7853     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7854 
7855     // Decompose into scalars
7856     SmallVector<SDValue, 4> Elts;
7857     DAG.ExtractVectorElements(IntVData, Elts);
7858 
7859     // Group pairs of i16 into v2i16 and bitcast to i32
7860     SmallVector<SDValue, 4> PackedElts;
7861     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7862       SDValue Pair =
7863           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7864       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7865       PackedElts.push_back(IntPair);
7866     }
7867     if ((NumElements % 2) == 1) {
7868       // Handle v3i16
7869       unsigned I = Elts.size() / 2;
7870       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7871                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7872       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7873       PackedElts.push_back(IntPair);
7874     }
7875 
7876     // Pad using UNDEF
7877     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7878 
7879     // Build final vector
7880     EVT VecVT =
7881         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7882     return DAG.getBuildVector(VecVT, DL, PackedElts);
7883   }
7884 
7885   if (NumElements == 3) {
7886     EVT IntStoreVT =
7887         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7888     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7889 
7890     EVT WidenedStoreVT = EVT::getVectorVT(
7891         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7892     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7893                                          WidenedStoreVT.getStoreSizeInBits());
7894     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7895     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7896   }
7897 
7898   assert(isTypeLegal(StoreVT));
7899   return VData;
7900 }
7901 
7902 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7903                                               SelectionDAG &DAG) const {
7904   SDLoc DL(Op);
7905   SDValue Chain = Op.getOperand(0);
7906   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7907   MachineFunction &MF = DAG.getMachineFunction();
7908 
7909   switch (IntrinsicID) {
7910   case Intrinsic::amdgcn_exp_compr: {
7911     SDValue Src0 = Op.getOperand(4);
7912     SDValue Src1 = Op.getOperand(5);
7913     // Hack around illegal type on SI by directly selecting it.
7914     if (isTypeLegal(Src0.getValueType()))
7915       return SDValue();
7916 
7917     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7918     SDValue Undef = DAG.getUNDEF(MVT::f32);
7919     const SDValue Ops[] = {
7920       Op.getOperand(2), // tgt
7921       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7922       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7923       Undef, // src2
7924       Undef, // src3
7925       Op.getOperand(7), // vm
7926       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7927       Op.getOperand(3), // en
7928       Op.getOperand(0) // Chain
7929     };
7930 
7931     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7932     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7933   }
7934   case Intrinsic::amdgcn_s_barrier: {
7935     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7936       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7937       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7938       if (WGSize <= ST.getWavefrontSize())
7939         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7940                                           Op.getOperand(0)), 0);
7941     }
7942     return SDValue();
7943   };
7944   case Intrinsic::amdgcn_tbuffer_store: {
7945     SDValue VData = Op.getOperand(2);
7946     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7947     if (IsD16)
7948       VData = handleD16VData(VData, DAG);
7949     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7950     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7951     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7952     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7953     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7954     SDValue Ops[] = {
7955       Chain,
7956       VData,             // vdata
7957       Op.getOperand(3),  // rsrc
7958       Op.getOperand(4),  // vindex
7959       Op.getOperand(5),  // voffset
7960       Op.getOperand(6),  // soffset
7961       Op.getOperand(7),  // offset
7962       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7963       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7964       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7965     };
7966     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7967                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7968     MemSDNode *M = cast<MemSDNode>(Op);
7969     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7970                                    M->getMemoryVT(), M->getMemOperand());
7971   }
7972 
7973   case Intrinsic::amdgcn_struct_tbuffer_store: {
7974     SDValue VData = Op.getOperand(2);
7975     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7976     if (IsD16)
7977       VData = handleD16VData(VData, DAG);
7978     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7979     SDValue Ops[] = {
7980       Chain,
7981       VData,             // vdata
7982       Op.getOperand(3),  // rsrc
7983       Op.getOperand(4),  // vindex
7984       Offsets.first,     // voffset
7985       Op.getOperand(6),  // soffset
7986       Offsets.second,    // offset
7987       Op.getOperand(7),  // format
7988       Op.getOperand(8),  // cachepolicy, swizzled buffer
7989       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7990     };
7991     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7992                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7993     MemSDNode *M = cast<MemSDNode>(Op);
7994     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7995                                    M->getMemoryVT(), M->getMemOperand());
7996   }
7997 
7998   case Intrinsic::amdgcn_raw_tbuffer_store: {
7999     SDValue VData = Op.getOperand(2);
8000     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8001     if (IsD16)
8002       VData = handleD16VData(VData, DAG);
8003     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8004     SDValue Ops[] = {
8005       Chain,
8006       VData,             // vdata
8007       Op.getOperand(3),  // rsrc
8008       DAG.getConstant(0, DL, MVT::i32), // vindex
8009       Offsets.first,     // voffset
8010       Op.getOperand(5),  // soffset
8011       Offsets.second,    // offset
8012       Op.getOperand(6),  // format
8013       Op.getOperand(7),  // cachepolicy, swizzled buffer
8014       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8015     };
8016     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8017                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8018     MemSDNode *M = cast<MemSDNode>(Op);
8019     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8020                                    M->getMemoryVT(), M->getMemOperand());
8021   }
8022 
8023   case Intrinsic::amdgcn_buffer_store:
8024   case Intrinsic::amdgcn_buffer_store_format: {
8025     SDValue VData = Op.getOperand(2);
8026     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8027     if (IsD16)
8028       VData = handleD16VData(VData, DAG);
8029     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8030     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8031     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8032     SDValue Ops[] = {
8033       Chain,
8034       VData,
8035       Op.getOperand(3), // rsrc
8036       Op.getOperand(4), // vindex
8037       SDValue(), // voffset -- will be set by setBufferOffsets
8038       SDValue(), // soffset -- will be set by setBufferOffsets
8039       SDValue(), // offset -- will be set by setBufferOffsets
8040       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8041       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8042     };
8043     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8044 
8045     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8046                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8047     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8048     MemSDNode *M = cast<MemSDNode>(Op);
8049     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8050 
8051     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8052     EVT VDataType = VData.getValueType().getScalarType();
8053     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8054       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8055 
8056     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8057                                    M->getMemoryVT(), M->getMemOperand());
8058   }
8059 
8060   case Intrinsic::amdgcn_raw_buffer_store:
8061   case Intrinsic::amdgcn_raw_buffer_store_format: {
8062     const bool IsFormat =
8063         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8064 
8065     SDValue VData = Op.getOperand(2);
8066     EVT VDataVT = VData.getValueType();
8067     EVT EltType = VDataVT.getScalarType();
8068     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8069     if (IsD16) {
8070       VData = handleD16VData(VData, DAG);
8071       VDataVT = VData.getValueType();
8072     }
8073 
8074     if (!isTypeLegal(VDataVT)) {
8075       VData =
8076           DAG.getNode(ISD::BITCAST, DL,
8077                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8078     }
8079 
8080     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8081     SDValue Ops[] = {
8082       Chain,
8083       VData,
8084       Op.getOperand(3), // rsrc
8085       DAG.getConstant(0, DL, MVT::i32), // vindex
8086       Offsets.first,    // voffset
8087       Op.getOperand(5), // soffset
8088       Offsets.second,   // offset
8089       Op.getOperand(6), // cachepolicy, swizzled buffer
8090       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8091     };
8092     unsigned Opc =
8093         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8094     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8095     MemSDNode *M = cast<MemSDNode>(Op);
8096     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8097 
8098     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8099     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8100       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8101 
8102     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8103                                    M->getMemoryVT(), M->getMemOperand());
8104   }
8105 
8106   case Intrinsic::amdgcn_struct_buffer_store:
8107   case Intrinsic::amdgcn_struct_buffer_store_format: {
8108     const bool IsFormat =
8109         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8110 
8111     SDValue VData = Op.getOperand(2);
8112     EVT VDataVT = VData.getValueType();
8113     EVT EltType = VDataVT.getScalarType();
8114     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8115 
8116     if (IsD16) {
8117       VData = handleD16VData(VData, DAG);
8118       VDataVT = VData.getValueType();
8119     }
8120 
8121     if (!isTypeLegal(VDataVT)) {
8122       VData =
8123           DAG.getNode(ISD::BITCAST, DL,
8124                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8125     }
8126 
8127     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8128     SDValue Ops[] = {
8129       Chain,
8130       VData,
8131       Op.getOperand(3), // rsrc
8132       Op.getOperand(4), // vindex
8133       Offsets.first,    // voffset
8134       Op.getOperand(6), // soffset
8135       Offsets.second,   // offset
8136       Op.getOperand(7), // cachepolicy, swizzled buffer
8137       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8138     };
8139     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8140                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8141     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8142     MemSDNode *M = cast<MemSDNode>(Op);
8143     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8144 
8145     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8146     EVT VDataType = VData.getValueType().getScalarType();
8147     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8148       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8149 
8150     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8151                                    M->getMemoryVT(), M->getMemOperand());
8152   }
8153   case Intrinsic::amdgcn_end_cf:
8154     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8155                                       Op->getOperand(2), Chain), 0);
8156 
8157   default: {
8158     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8159             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8160       return lowerImage(Op, ImageDimIntr, DAG, true);
8161 
8162     return Op;
8163   }
8164   }
8165 }
8166 
8167 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8168 // offset (the offset that is included in bounds checking and swizzling, to be
8169 // split between the instruction's voffset and immoffset fields) and soffset
8170 // (the offset that is excluded from bounds checking and swizzling, to go in
8171 // the instruction's soffset field).  This function takes the first kind of
8172 // offset and figures out how to split it between voffset and immoffset.
8173 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8174     SDValue Offset, SelectionDAG &DAG) const {
8175   SDLoc DL(Offset);
8176   const unsigned MaxImm = 4095;
8177   SDValue N0 = Offset;
8178   ConstantSDNode *C1 = nullptr;
8179 
8180   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8181     N0 = SDValue();
8182   else if (DAG.isBaseWithConstantOffset(N0)) {
8183     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8184     N0 = N0.getOperand(0);
8185   }
8186 
8187   if (C1) {
8188     unsigned ImmOffset = C1->getZExtValue();
8189     // If the immediate value is too big for the immoffset field, put the value
8190     // and -4096 into the immoffset field so that the value that is copied/added
8191     // for the voffset field is a multiple of 4096, and it stands more chance
8192     // of being CSEd with the copy/add for another similar load/store.
8193     // However, do not do that rounding down to a multiple of 4096 if that is a
8194     // negative number, as it appears to be illegal to have a negative offset
8195     // in the vgpr, even if adding the immediate offset makes it positive.
8196     unsigned Overflow = ImmOffset & ~MaxImm;
8197     ImmOffset -= Overflow;
8198     if ((int32_t)Overflow < 0) {
8199       Overflow += ImmOffset;
8200       ImmOffset = 0;
8201     }
8202     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8203     if (Overflow) {
8204       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8205       if (!N0)
8206         N0 = OverflowVal;
8207       else {
8208         SDValue Ops[] = { N0, OverflowVal };
8209         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8210       }
8211     }
8212   }
8213   if (!N0)
8214     N0 = DAG.getConstant(0, DL, MVT::i32);
8215   if (!C1)
8216     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8217   return {N0, SDValue(C1, 0)};
8218 }
8219 
8220 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8221 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8222 // pointed to by Offsets.
8223 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8224                                         SelectionDAG &DAG, SDValue *Offsets,
8225                                         Align Alignment) const {
8226   SDLoc DL(CombinedOffset);
8227   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8228     uint32_t Imm = C->getZExtValue();
8229     uint32_t SOffset, ImmOffset;
8230     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8231                                  Alignment)) {
8232       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8233       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8234       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8235       return;
8236     }
8237   }
8238   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8239     SDValue N0 = CombinedOffset.getOperand(0);
8240     SDValue N1 = CombinedOffset.getOperand(1);
8241     uint32_t SOffset, ImmOffset;
8242     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8243     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8244                                                 Subtarget, Alignment)) {
8245       Offsets[0] = N0;
8246       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8247       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8248       return;
8249     }
8250   }
8251   Offsets[0] = CombinedOffset;
8252   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8253   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8254 }
8255 
8256 // Handle 8 bit and 16 bit buffer loads
8257 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8258                                                      EVT LoadVT, SDLoc DL,
8259                                                      ArrayRef<SDValue> Ops,
8260                                                      MemSDNode *M) const {
8261   EVT IntVT = LoadVT.changeTypeToInteger();
8262   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8263          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8264 
8265   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8266   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8267                                                Ops, IntVT,
8268                                                M->getMemOperand());
8269   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8270   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8271 
8272   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8273 }
8274 
8275 // Handle 8 bit and 16 bit buffer stores
8276 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8277                                                       EVT VDataType, SDLoc DL,
8278                                                       SDValue Ops[],
8279                                                       MemSDNode *M) const {
8280   if (VDataType == MVT::f16)
8281     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8282 
8283   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8284   Ops[1] = BufferStoreExt;
8285   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8286                                  AMDGPUISD::BUFFER_STORE_SHORT;
8287   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8288   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8289                                      M->getMemOperand());
8290 }
8291 
8292 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8293                                  ISD::LoadExtType ExtType, SDValue Op,
8294                                  const SDLoc &SL, EVT VT) {
8295   if (VT.bitsLT(Op.getValueType()))
8296     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8297 
8298   switch (ExtType) {
8299   case ISD::SEXTLOAD:
8300     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8301   case ISD::ZEXTLOAD:
8302     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8303   case ISD::EXTLOAD:
8304     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8305   case ISD::NON_EXTLOAD:
8306     return Op;
8307   }
8308 
8309   llvm_unreachable("invalid ext type");
8310 }
8311 
8312 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8313   SelectionDAG &DAG = DCI.DAG;
8314   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8315     return SDValue();
8316 
8317   // FIXME: Constant loads should all be marked invariant.
8318   unsigned AS = Ld->getAddressSpace();
8319   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8320       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8321       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8322     return SDValue();
8323 
8324   // Don't do this early, since it may interfere with adjacent load merging for
8325   // illegal types. We can avoid losing alignment information for exotic types
8326   // pre-legalize.
8327   EVT MemVT = Ld->getMemoryVT();
8328   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8329       MemVT.getSizeInBits() >= 32)
8330     return SDValue();
8331 
8332   SDLoc SL(Ld);
8333 
8334   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8335          "unexpected vector extload");
8336 
8337   // TODO: Drop only high part of range.
8338   SDValue Ptr = Ld->getBasePtr();
8339   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8340                                 MVT::i32, SL, Ld->getChain(), Ptr,
8341                                 Ld->getOffset(),
8342                                 Ld->getPointerInfo(), MVT::i32,
8343                                 Ld->getAlignment(),
8344                                 Ld->getMemOperand()->getFlags(),
8345                                 Ld->getAAInfo(),
8346                                 nullptr); // Drop ranges
8347 
8348   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8349   if (MemVT.isFloatingPoint()) {
8350     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8351            "unexpected fp extload");
8352     TruncVT = MemVT.changeTypeToInteger();
8353   }
8354 
8355   SDValue Cvt = NewLoad;
8356   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8357     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8358                       DAG.getValueType(TruncVT));
8359   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8360              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8361     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8362   } else {
8363     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8364   }
8365 
8366   EVT VT = Ld->getValueType(0);
8367   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8368 
8369   DCI.AddToWorklist(Cvt.getNode());
8370 
8371   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8372   // the appropriate extension from the 32-bit load.
8373   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8374   DCI.AddToWorklist(Cvt.getNode());
8375 
8376   // Handle conversion back to floating point if necessary.
8377   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8378 
8379   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8380 }
8381 
8382 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8383   SDLoc DL(Op);
8384   LoadSDNode *Load = cast<LoadSDNode>(Op);
8385   ISD::LoadExtType ExtType = Load->getExtensionType();
8386   EVT MemVT = Load->getMemoryVT();
8387 
8388   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8389     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8390       return SDValue();
8391 
8392     // FIXME: Copied from PPC
8393     // First, load into 32 bits, then truncate to 1 bit.
8394 
8395     SDValue Chain = Load->getChain();
8396     SDValue BasePtr = Load->getBasePtr();
8397     MachineMemOperand *MMO = Load->getMemOperand();
8398 
8399     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8400 
8401     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8402                                    BasePtr, RealMemVT, MMO);
8403 
8404     if (!MemVT.isVector()) {
8405       SDValue Ops[] = {
8406         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8407         NewLD.getValue(1)
8408       };
8409 
8410       return DAG.getMergeValues(Ops, DL);
8411     }
8412 
8413     SmallVector<SDValue, 3> Elts;
8414     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8415       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8416                                 DAG.getConstant(I, DL, MVT::i32));
8417 
8418       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8419     }
8420 
8421     SDValue Ops[] = {
8422       DAG.getBuildVector(MemVT, DL, Elts),
8423       NewLD.getValue(1)
8424     };
8425 
8426     return DAG.getMergeValues(Ops, DL);
8427   }
8428 
8429   if (!MemVT.isVector())
8430     return SDValue();
8431 
8432   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8433          "Custom lowering for non-i32 vectors hasn't been implemented.");
8434 
8435   unsigned Alignment = Load->getAlignment();
8436   unsigned AS = Load->getAddressSpace();
8437   if (Subtarget->hasLDSMisalignedBug() &&
8438       AS == AMDGPUAS::FLAT_ADDRESS &&
8439       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8440     return SplitVectorLoad(Op, DAG);
8441   }
8442 
8443   MachineFunction &MF = DAG.getMachineFunction();
8444   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8445   // If there is a possibility that flat instruction access scratch memory
8446   // then we need to use the same legalization rules we use for private.
8447   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8448       !Subtarget->hasMultiDwordFlatScratchAddressing())
8449     AS = MFI->hasFlatScratchInit() ?
8450          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8451 
8452   unsigned NumElements = MemVT.getVectorNumElements();
8453 
8454   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8455       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8456     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8457       if (MemVT.isPow2VectorType())
8458         return SDValue();
8459       return WidenOrSplitVectorLoad(Op, DAG);
8460     }
8461     // Non-uniform loads will be selected to MUBUF instructions, so they
8462     // have the same legalization requirements as global and private
8463     // loads.
8464     //
8465   }
8466 
8467   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8468       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8469       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8470     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8471         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8472         Alignment >= 4 && NumElements < 32) {
8473       if (MemVT.isPow2VectorType())
8474         return SDValue();
8475       return WidenOrSplitVectorLoad(Op, DAG);
8476     }
8477     // Non-uniform loads will be selected to MUBUF instructions, so they
8478     // have the same legalization requirements as global and private
8479     // loads.
8480     //
8481   }
8482   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8483       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8484       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8485       AS == AMDGPUAS::FLAT_ADDRESS) {
8486     if (NumElements > 4)
8487       return SplitVectorLoad(Op, DAG);
8488     // v3 loads not supported on SI.
8489     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8490       return WidenOrSplitVectorLoad(Op, DAG);
8491 
8492     // v3 and v4 loads are supported for private and global memory.
8493     return SDValue();
8494   }
8495   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8496     // Depending on the setting of the private_element_size field in the
8497     // resource descriptor, we can only make private accesses up to a certain
8498     // size.
8499     switch (Subtarget->getMaxPrivateElementSize()) {
8500     case 4: {
8501       SDValue Ops[2];
8502       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8503       return DAG.getMergeValues(Ops, DL);
8504     }
8505     case 8:
8506       if (NumElements > 2)
8507         return SplitVectorLoad(Op, DAG);
8508       return SDValue();
8509     case 16:
8510       // Same as global/flat
8511       if (NumElements > 4)
8512         return SplitVectorLoad(Op, DAG);
8513       // v3 loads not supported on SI.
8514       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8515         return WidenOrSplitVectorLoad(Op, DAG);
8516 
8517       return SDValue();
8518     default:
8519       llvm_unreachable("unsupported private_element_size");
8520     }
8521   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8522     // Use ds_read_b128 or ds_read_b96 when possible.
8523     if (Subtarget->hasDS96AndDS128() &&
8524         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8525          MemVT.getStoreSize() == 12) &&
8526         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8527                                            Load->getAlign()))
8528       return SDValue();
8529 
8530     if (NumElements > 2)
8531       return SplitVectorLoad(Op, DAG);
8532 
8533     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
8534     // address is negative, then the instruction is incorrectly treated as
8535     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8536     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8537     // load later in the SILoadStoreOptimizer.
8538     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8539         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8540         Load->getAlignment() < 8) {
8541       return SplitVectorLoad(Op, DAG);
8542     }
8543   }
8544 
8545   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8546                                       MemVT, *Load->getMemOperand())) {
8547     SDValue Ops[2];
8548     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8549     return DAG.getMergeValues(Ops, DL);
8550   }
8551 
8552   return SDValue();
8553 }
8554 
8555 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8556   EVT VT = Op.getValueType();
8557   if (VT.getSizeInBits() == 128)
8558     return splitTernaryVectorOp(Op, DAG);
8559 
8560   assert(VT.getSizeInBits() == 64);
8561 
8562   SDLoc DL(Op);
8563   SDValue Cond = Op.getOperand(0);
8564 
8565   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8566   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8567 
8568   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8569   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8570 
8571   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8572   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8573 
8574   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8575 
8576   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8577   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8578 
8579   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8580 
8581   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8582   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8583 }
8584 
8585 // Catch division cases where we can use shortcuts with rcp and rsq
8586 // instructions.
8587 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8588                                               SelectionDAG &DAG) const {
8589   SDLoc SL(Op);
8590   SDValue LHS = Op.getOperand(0);
8591   SDValue RHS = Op.getOperand(1);
8592   EVT VT = Op.getValueType();
8593   const SDNodeFlags Flags = Op->getFlags();
8594 
8595   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8596 
8597   // Without !fpmath accuracy information, we can't do more because we don't
8598   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8599   if (!AllowInaccurateRcp)
8600     return SDValue();
8601 
8602   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8603     if (CLHS->isExactlyValue(1.0)) {
8604       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8605       // the CI documentation has a worst case error of 1 ulp.
8606       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8607       // use it as long as we aren't trying to use denormals.
8608       //
8609       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8610 
8611       // 1.0 / sqrt(x) -> rsq(x)
8612 
8613       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8614       // error seems really high at 2^29 ULP.
8615       if (RHS.getOpcode() == ISD::FSQRT)
8616         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8617 
8618       // 1.0 / x -> rcp(x)
8619       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8620     }
8621 
8622     // Same as for 1.0, but expand the sign out of the constant.
8623     if (CLHS->isExactlyValue(-1.0)) {
8624       // -1.0 / x -> rcp (fneg x)
8625       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8626       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8627     }
8628   }
8629 
8630   // Turn into multiply by the reciprocal.
8631   // x / y -> x * (1.0 / y)
8632   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8633   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8634 }
8635 
8636 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8637                                                 SelectionDAG &DAG) const {
8638   SDLoc SL(Op);
8639   SDValue X = Op.getOperand(0);
8640   SDValue Y = Op.getOperand(1);
8641   EVT VT = Op.getValueType();
8642   const SDNodeFlags Flags = Op->getFlags();
8643 
8644   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8645                             DAG.getTarget().Options.UnsafeFPMath;
8646   if (!AllowInaccurateDiv)
8647     return SDValue();
8648 
8649   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8650   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8651 
8652   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8653   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8654 
8655   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8656   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8657   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8658   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8659   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8660   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8661 }
8662 
8663 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8664                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8665                           SDNodeFlags Flags) {
8666   if (GlueChain->getNumValues() <= 1) {
8667     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8668   }
8669 
8670   assert(GlueChain->getNumValues() == 3);
8671 
8672   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8673   switch (Opcode) {
8674   default: llvm_unreachable("no chain equivalent for opcode");
8675   case ISD::FMUL:
8676     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8677     break;
8678   }
8679 
8680   return DAG.getNode(Opcode, SL, VTList,
8681                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8682                      Flags);
8683 }
8684 
8685 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8686                            EVT VT, SDValue A, SDValue B, SDValue C,
8687                            SDValue GlueChain, SDNodeFlags Flags) {
8688   if (GlueChain->getNumValues() <= 1) {
8689     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8690   }
8691 
8692   assert(GlueChain->getNumValues() == 3);
8693 
8694   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8695   switch (Opcode) {
8696   default: llvm_unreachable("no chain equivalent for opcode");
8697   case ISD::FMA:
8698     Opcode = AMDGPUISD::FMA_W_CHAIN;
8699     break;
8700   }
8701 
8702   return DAG.getNode(Opcode, SL, VTList,
8703                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8704                      Flags);
8705 }
8706 
8707 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8708   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8709     return FastLowered;
8710 
8711   SDLoc SL(Op);
8712   SDValue Src0 = Op.getOperand(0);
8713   SDValue Src1 = Op.getOperand(1);
8714 
8715   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8716   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8717 
8718   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8719   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8720 
8721   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8722   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8723 
8724   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8725 }
8726 
8727 // Faster 2.5 ULP division that does not support denormals.
8728 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8729   SDLoc SL(Op);
8730   SDValue LHS = Op.getOperand(1);
8731   SDValue RHS = Op.getOperand(2);
8732 
8733   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8734 
8735   const APFloat K0Val(BitsToFloat(0x6f800000));
8736   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8737 
8738   const APFloat K1Val(BitsToFloat(0x2f800000));
8739   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8740 
8741   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8742 
8743   EVT SetCCVT =
8744     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8745 
8746   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8747 
8748   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8749 
8750   // TODO: Should this propagate fast-math-flags?
8751   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8752 
8753   // rcp does not support denormals.
8754   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8755 
8756   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8757 
8758   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8759 }
8760 
8761 // Returns immediate value for setting the F32 denorm mode when using the
8762 // S_DENORM_MODE instruction.
8763 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8764                                     const SDLoc &SL, const GCNSubtarget *ST) {
8765   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8766   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8767                                 ? FP_DENORM_FLUSH_NONE
8768                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8769 
8770   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8771   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8772 }
8773 
8774 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8775   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8776     return FastLowered;
8777 
8778   // The selection matcher assumes anything with a chain selecting to a
8779   // mayRaiseFPException machine instruction. Since we're introducing a chain
8780   // here, we need to explicitly report nofpexcept for the regular fdiv
8781   // lowering.
8782   SDNodeFlags Flags = Op->getFlags();
8783   Flags.setNoFPExcept(true);
8784 
8785   SDLoc SL(Op);
8786   SDValue LHS = Op.getOperand(0);
8787   SDValue RHS = Op.getOperand(1);
8788 
8789   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8790 
8791   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8792 
8793   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8794                                           {RHS, RHS, LHS}, Flags);
8795   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8796                                         {LHS, RHS, LHS}, Flags);
8797 
8798   // Denominator is scaled to not be denormal, so using rcp is ok.
8799   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8800                                   DenominatorScaled, Flags);
8801   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8802                                      DenominatorScaled, Flags);
8803 
8804   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8805                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8806                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8807   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8808 
8809   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8810 
8811   if (!HasFP32Denormals) {
8812     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8813     // lowering. The chain dependence is insufficient, and we need glue. We do
8814     // not need the glue variants in a strictfp function.
8815 
8816     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8817 
8818     SDNode *EnableDenorm;
8819     if (Subtarget->hasDenormModeInst()) {
8820       const SDValue EnableDenormValue =
8821           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8822 
8823       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8824                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8825     } else {
8826       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8827                                                         SL, MVT::i32);
8828       EnableDenorm =
8829           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8830                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8831     }
8832 
8833     SDValue Ops[3] = {
8834       NegDivScale0,
8835       SDValue(EnableDenorm, 0),
8836       SDValue(EnableDenorm, 1)
8837     };
8838 
8839     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8840   }
8841 
8842   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8843                              ApproxRcp, One, NegDivScale0, Flags);
8844 
8845   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8846                              ApproxRcp, Fma0, Flags);
8847 
8848   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8849                            Fma1, Fma1, Flags);
8850 
8851   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8852                              NumeratorScaled, Mul, Flags);
8853 
8854   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8855                              Fma2, Fma1, Mul, Fma2, Flags);
8856 
8857   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8858                              NumeratorScaled, Fma3, Flags);
8859 
8860   if (!HasFP32Denormals) {
8861     SDNode *DisableDenorm;
8862     if (Subtarget->hasDenormModeInst()) {
8863       const SDValue DisableDenormValue =
8864           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8865 
8866       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8867                                   Fma4.getValue(1), DisableDenormValue,
8868                                   Fma4.getValue(2)).getNode();
8869     } else {
8870       const SDValue DisableDenormValue =
8871           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8872 
8873       DisableDenorm = DAG.getMachineNode(
8874           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8875           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8876     }
8877 
8878     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8879                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8880     DAG.setRoot(OutputChain);
8881   }
8882 
8883   SDValue Scale = NumeratorScaled.getValue(1);
8884   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8885                              {Fma4, Fma1, Fma3, Scale}, Flags);
8886 
8887   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8888 }
8889 
8890 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8891   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8892     return FastLowered;
8893 
8894   SDLoc SL(Op);
8895   SDValue X = Op.getOperand(0);
8896   SDValue Y = Op.getOperand(1);
8897 
8898   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8899 
8900   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8901 
8902   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8903 
8904   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8905 
8906   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8907 
8908   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8909 
8910   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8911 
8912   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8913 
8914   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8915 
8916   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8917   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8918 
8919   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8920                              NegDivScale0, Mul, DivScale1);
8921 
8922   SDValue Scale;
8923 
8924   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8925     // Workaround a hardware bug on SI where the condition output from div_scale
8926     // is not usable.
8927 
8928     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8929 
8930     // Figure out if the scale to use for div_fmas.
8931     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8932     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8933     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8934     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8935 
8936     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8937     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8938 
8939     SDValue Scale0Hi
8940       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8941     SDValue Scale1Hi
8942       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8943 
8944     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8945     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8946     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8947   } else {
8948     Scale = DivScale1.getValue(1);
8949   }
8950 
8951   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8952                              Fma4, Fma3, Mul, Scale);
8953 
8954   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8955 }
8956 
8957 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8958   EVT VT = Op.getValueType();
8959 
8960   if (VT == MVT::f32)
8961     return LowerFDIV32(Op, DAG);
8962 
8963   if (VT == MVT::f64)
8964     return LowerFDIV64(Op, DAG);
8965 
8966   if (VT == MVT::f16)
8967     return LowerFDIV16(Op, DAG);
8968 
8969   llvm_unreachable("Unexpected type for fdiv");
8970 }
8971 
8972 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8973   SDLoc DL(Op);
8974   StoreSDNode *Store = cast<StoreSDNode>(Op);
8975   EVT VT = Store->getMemoryVT();
8976 
8977   if (VT == MVT::i1) {
8978     return DAG.getTruncStore(Store->getChain(), DL,
8979        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8980        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8981   }
8982 
8983   assert(VT.isVector() &&
8984          Store->getValue().getValueType().getScalarType() == MVT::i32);
8985 
8986   unsigned AS = Store->getAddressSpace();
8987   if (Subtarget->hasLDSMisalignedBug() &&
8988       AS == AMDGPUAS::FLAT_ADDRESS &&
8989       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8990     return SplitVectorStore(Op, DAG);
8991   }
8992 
8993   MachineFunction &MF = DAG.getMachineFunction();
8994   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8995   // If there is a possibility that flat instruction access scratch memory
8996   // then we need to use the same legalization rules we use for private.
8997   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8998       !Subtarget->hasMultiDwordFlatScratchAddressing())
8999     AS = MFI->hasFlatScratchInit() ?
9000          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9001 
9002   unsigned NumElements = VT.getVectorNumElements();
9003   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9004       AS == AMDGPUAS::FLAT_ADDRESS) {
9005     if (NumElements > 4)
9006       return SplitVectorStore(Op, DAG);
9007     // v3 stores not supported on SI.
9008     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9009       return SplitVectorStore(Op, DAG);
9010 
9011     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9012                                         VT, *Store->getMemOperand()))
9013       return expandUnalignedStore(Store, DAG);
9014 
9015     return SDValue();
9016   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9017     switch (Subtarget->getMaxPrivateElementSize()) {
9018     case 4:
9019       return scalarizeVectorStore(Store, DAG);
9020     case 8:
9021       if (NumElements > 2)
9022         return SplitVectorStore(Op, DAG);
9023       return SDValue();
9024     case 16:
9025       if (NumElements > 4 ||
9026           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9027         return SplitVectorStore(Op, DAG);
9028       return SDValue();
9029     default:
9030       llvm_unreachable("unsupported private_element_size");
9031     }
9032   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9033     // Use ds_write_b128 or ds_write_b96 when possible.
9034     if (Subtarget->hasDS96AndDS128() &&
9035         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
9036          (VT.getStoreSize() == 12)) &&
9037         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9038                                            Store->getAlign()))
9039       return SDValue();
9040 
9041     if (NumElements > 2)
9042       return SplitVectorStore(Op, DAG);
9043 
9044     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
9045     // address is negative, then the instruction is incorrectly treated as
9046     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9047     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9048     // store later in the SILoadStoreOptimizer.
9049     if (!Subtarget->hasUsableDSOffset() &&
9050         NumElements == 2 && VT.getStoreSize() == 8 &&
9051         Store->getAlignment() < 8) {
9052       return SplitVectorStore(Op, DAG);
9053     }
9054 
9055     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9056                                         VT, *Store->getMemOperand())) {
9057       if (VT.isVector())
9058         return SplitVectorStore(Op, DAG);
9059       return expandUnalignedStore(Store, DAG);
9060     }
9061 
9062     return SDValue();
9063   } else {
9064     llvm_unreachable("unhandled address space");
9065   }
9066 }
9067 
9068 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9069   SDLoc DL(Op);
9070   EVT VT = Op.getValueType();
9071   SDValue Arg = Op.getOperand(0);
9072   SDValue TrigVal;
9073 
9074   // Propagate fast-math flags so that the multiply we introduce can be folded
9075   // if Arg is already the result of a multiply by constant.
9076   auto Flags = Op->getFlags();
9077 
9078   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9079 
9080   if (Subtarget->hasTrigReducedRange()) {
9081     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9082     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9083   } else {
9084     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9085   }
9086 
9087   switch (Op.getOpcode()) {
9088   case ISD::FCOS:
9089     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9090   case ISD::FSIN:
9091     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9092   default:
9093     llvm_unreachable("Wrong trig opcode");
9094   }
9095 }
9096 
9097 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9098   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9099   assert(AtomicNode->isCompareAndSwap());
9100   unsigned AS = AtomicNode->getAddressSpace();
9101 
9102   // No custom lowering required for local address space
9103   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9104     return Op;
9105 
9106   // Non-local address space requires custom lowering for atomic compare
9107   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9108   SDLoc DL(Op);
9109   SDValue ChainIn = Op.getOperand(0);
9110   SDValue Addr = Op.getOperand(1);
9111   SDValue Old = Op.getOperand(2);
9112   SDValue New = Op.getOperand(3);
9113   EVT VT = Op.getValueType();
9114   MVT SimpleVT = VT.getSimpleVT();
9115   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9116 
9117   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9118   SDValue Ops[] = { ChainIn, Addr, NewOld };
9119 
9120   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9121                                  Ops, VT, AtomicNode->getMemOperand());
9122 }
9123 
9124 //===----------------------------------------------------------------------===//
9125 // Custom DAG optimizations
9126 //===----------------------------------------------------------------------===//
9127 
9128 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9129                                                      DAGCombinerInfo &DCI) const {
9130   EVT VT = N->getValueType(0);
9131   EVT ScalarVT = VT.getScalarType();
9132   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9133     return SDValue();
9134 
9135   SelectionDAG &DAG = DCI.DAG;
9136   SDLoc DL(N);
9137 
9138   SDValue Src = N->getOperand(0);
9139   EVT SrcVT = Src.getValueType();
9140 
9141   // TODO: We could try to match extracting the higher bytes, which would be
9142   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9143   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9144   // about in practice.
9145   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9146     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9147       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9148       DCI.AddToWorklist(Cvt.getNode());
9149 
9150       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9151       if (ScalarVT != MVT::f32) {
9152         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9153                           DAG.getTargetConstant(0, DL, MVT::i32));
9154       }
9155       return Cvt;
9156     }
9157   }
9158 
9159   return SDValue();
9160 }
9161 
9162 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9163 
9164 // This is a variant of
9165 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9166 //
9167 // The normal DAG combiner will do this, but only if the add has one use since
9168 // that would increase the number of instructions.
9169 //
9170 // This prevents us from seeing a constant offset that can be folded into a
9171 // memory instruction's addressing mode. If we know the resulting add offset of
9172 // a pointer can be folded into an addressing offset, we can replace the pointer
9173 // operand with the add of new constant offset. This eliminates one of the uses,
9174 // and may allow the remaining use to also be simplified.
9175 //
9176 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9177                                                unsigned AddrSpace,
9178                                                EVT MemVT,
9179                                                DAGCombinerInfo &DCI) const {
9180   SDValue N0 = N->getOperand(0);
9181   SDValue N1 = N->getOperand(1);
9182 
9183   // We only do this to handle cases where it's profitable when there are
9184   // multiple uses of the add, so defer to the standard combine.
9185   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9186       N0->hasOneUse())
9187     return SDValue();
9188 
9189   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9190   if (!CN1)
9191     return SDValue();
9192 
9193   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9194   if (!CAdd)
9195     return SDValue();
9196 
9197   // If the resulting offset is too large, we can't fold it into the addressing
9198   // mode offset.
9199   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9200   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9201 
9202   AddrMode AM;
9203   AM.HasBaseReg = true;
9204   AM.BaseOffs = Offset.getSExtValue();
9205   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9206     return SDValue();
9207 
9208   SelectionDAG &DAG = DCI.DAG;
9209   SDLoc SL(N);
9210   EVT VT = N->getValueType(0);
9211 
9212   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9213   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9214 
9215   SDNodeFlags Flags;
9216   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9217                           (N0.getOpcode() == ISD::OR ||
9218                            N0->getFlags().hasNoUnsignedWrap()));
9219 
9220   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9221 }
9222 
9223 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9224 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9225 /// specific intrinsic, but they all place the pointer operand first.
9226 static unsigned getBasePtrIndex(const MemSDNode *N) {
9227   switch (N->getOpcode()) {
9228   case ISD::STORE:
9229   case ISD::INTRINSIC_W_CHAIN:
9230   case ISD::INTRINSIC_VOID:
9231     return 2;
9232   default:
9233     return 1;
9234   }
9235 }
9236 
9237 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9238                                                   DAGCombinerInfo &DCI) const {
9239   SelectionDAG &DAG = DCI.DAG;
9240   SDLoc SL(N);
9241 
9242   unsigned PtrIdx = getBasePtrIndex(N);
9243   SDValue Ptr = N->getOperand(PtrIdx);
9244 
9245   // TODO: We could also do this for multiplies.
9246   if (Ptr.getOpcode() == ISD::SHL) {
9247     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9248                                           N->getMemoryVT(), DCI);
9249     if (NewPtr) {
9250       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9251 
9252       NewOps[PtrIdx] = NewPtr;
9253       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9254     }
9255   }
9256 
9257   return SDValue();
9258 }
9259 
9260 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9261   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9262          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9263          (Opc == ISD::XOR && Val == 0);
9264 }
9265 
9266 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9267 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9268 // integer combine opportunities since most 64-bit operations are decomposed
9269 // this way.  TODO: We won't want this for SALU especially if it is an inline
9270 // immediate.
9271 SDValue SITargetLowering::splitBinaryBitConstantOp(
9272   DAGCombinerInfo &DCI,
9273   const SDLoc &SL,
9274   unsigned Opc, SDValue LHS,
9275   const ConstantSDNode *CRHS) const {
9276   uint64_t Val = CRHS->getZExtValue();
9277   uint32_t ValLo = Lo_32(Val);
9278   uint32_t ValHi = Hi_32(Val);
9279   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9280 
9281     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9282          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9283         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9284     // If we need to materialize a 64-bit immediate, it will be split up later
9285     // anyway. Avoid creating the harder to understand 64-bit immediate
9286     // materialization.
9287     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9288   }
9289 
9290   return SDValue();
9291 }
9292 
9293 // Returns true if argument is a boolean value which is not serialized into
9294 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9295 static bool isBoolSGPR(SDValue V) {
9296   if (V.getValueType() != MVT::i1)
9297     return false;
9298   switch (V.getOpcode()) {
9299   default:
9300     break;
9301   case ISD::SETCC:
9302   case AMDGPUISD::FP_CLASS:
9303     return true;
9304   case ISD::AND:
9305   case ISD::OR:
9306   case ISD::XOR:
9307     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9308   }
9309   return false;
9310 }
9311 
9312 // If a constant has all zeroes or all ones within each byte return it.
9313 // Otherwise return 0.
9314 static uint32_t getConstantPermuteMask(uint32_t C) {
9315   // 0xff for any zero byte in the mask
9316   uint32_t ZeroByteMask = 0;
9317   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9318   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9319   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9320   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9321   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9322   if ((NonZeroByteMask & C) != NonZeroByteMask)
9323     return 0; // Partial bytes selected.
9324   return C;
9325 }
9326 
9327 // Check if a node selects whole bytes from its operand 0 starting at a byte
9328 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9329 // or -1 if not succeeded.
9330 // Note byte select encoding:
9331 // value 0-3 selects corresponding source byte;
9332 // value 0xc selects zero;
9333 // value 0xff selects 0xff.
9334 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9335   assert(V.getValueSizeInBits() == 32);
9336 
9337   if (V.getNumOperands() != 2)
9338     return ~0;
9339 
9340   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9341   if (!N1)
9342     return ~0;
9343 
9344   uint32_t C = N1->getZExtValue();
9345 
9346   switch (V.getOpcode()) {
9347   default:
9348     break;
9349   case ISD::AND:
9350     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9351       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9352     }
9353     break;
9354 
9355   case ISD::OR:
9356     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9357       return (0x03020100 & ~ConstMask) | ConstMask;
9358     }
9359     break;
9360 
9361   case ISD::SHL:
9362     if (C % 8)
9363       return ~0;
9364 
9365     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9366 
9367   case ISD::SRL:
9368     if (C % 8)
9369       return ~0;
9370 
9371     return uint32_t(0x0c0c0c0c03020100ull >> C);
9372   }
9373 
9374   return ~0;
9375 }
9376 
9377 SDValue SITargetLowering::performAndCombine(SDNode *N,
9378                                             DAGCombinerInfo &DCI) const {
9379   if (DCI.isBeforeLegalize())
9380     return SDValue();
9381 
9382   SelectionDAG &DAG = DCI.DAG;
9383   EVT VT = N->getValueType(0);
9384   SDValue LHS = N->getOperand(0);
9385   SDValue RHS = N->getOperand(1);
9386 
9387 
9388   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9389   if (VT == MVT::i64 && CRHS) {
9390     if (SDValue Split
9391         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9392       return Split;
9393   }
9394 
9395   if (CRHS && VT == MVT::i32) {
9396     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9397     // nb = number of trailing zeroes in mask
9398     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9399     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9400     uint64_t Mask = CRHS->getZExtValue();
9401     unsigned Bits = countPopulation(Mask);
9402     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9403         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9404       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9405         unsigned Shift = CShift->getZExtValue();
9406         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9407         unsigned Offset = NB + Shift;
9408         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9409           SDLoc SL(N);
9410           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9411                                     LHS->getOperand(0),
9412                                     DAG.getConstant(Offset, SL, MVT::i32),
9413                                     DAG.getConstant(Bits, SL, MVT::i32));
9414           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9415           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9416                                     DAG.getValueType(NarrowVT));
9417           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9418                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9419           return Shl;
9420         }
9421       }
9422     }
9423 
9424     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9425     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9426         isa<ConstantSDNode>(LHS.getOperand(2))) {
9427       uint32_t Sel = getConstantPermuteMask(Mask);
9428       if (!Sel)
9429         return SDValue();
9430 
9431       // Select 0xc for all zero bytes
9432       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9433       SDLoc DL(N);
9434       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9435                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9436     }
9437   }
9438 
9439   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9440   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9441   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9442     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9443     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9444 
9445     SDValue X = LHS.getOperand(0);
9446     SDValue Y = RHS.getOperand(0);
9447     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9448       return SDValue();
9449 
9450     if (LCC == ISD::SETO) {
9451       if (X != LHS.getOperand(1))
9452         return SDValue();
9453 
9454       if (RCC == ISD::SETUNE) {
9455         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9456         if (!C1 || !C1->isInfinity() || C1->isNegative())
9457           return SDValue();
9458 
9459         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9460                               SIInstrFlags::N_SUBNORMAL |
9461                               SIInstrFlags::N_ZERO |
9462                               SIInstrFlags::P_ZERO |
9463                               SIInstrFlags::P_SUBNORMAL |
9464                               SIInstrFlags::P_NORMAL;
9465 
9466         static_assert(((~(SIInstrFlags::S_NAN |
9467                           SIInstrFlags::Q_NAN |
9468                           SIInstrFlags::N_INFINITY |
9469                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9470                       "mask not equal");
9471 
9472         SDLoc DL(N);
9473         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9474                            X, DAG.getConstant(Mask, DL, MVT::i32));
9475       }
9476     }
9477   }
9478 
9479   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9480     std::swap(LHS, RHS);
9481 
9482   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9483       RHS.hasOneUse()) {
9484     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9485     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9486     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9487     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9488     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9489         (RHS.getOperand(0) == LHS.getOperand(0) &&
9490          LHS.getOperand(0) == LHS.getOperand(1))) {
9491       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9492       unsigned NewMask = LCC == ISD::SETO ?
9493         Mask->getZExtValue() & ~OrdMask :
9494         Mask->getZExtValue() & OrdMask;
9495 
9496       SDLoc DL(N);
9497       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9498                          DAG.getConstant(NewMask, DL, MVT::i32));
9499     }
9500   }
9501 
9502   if (VT == MVT::i32 &&
9503       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9504     // and x, (sext cc from i1) => select cc, x, 0
9505     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9506       std::swap(LHS, RHS);
9507     if (isBoolSGPR(RHS.getOperand(0)))
9508       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9509                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9510   }
9511 
9512   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9513   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9514   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9515       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9516     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9517     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9518     if (LHSMask != ~0u && RHSMask != ~0u) {
9519       // Canonicalize the expression in an attempt to have fewer unique masks
9520       // and therefore fewer registers used to hold the masks.
9521       if (LHSMask > RHSMask) {
9522         std::swap(LHSMask, RHSMask);
9523         std::swap(LHS, RHS);
9524       }
9525 
9526       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9527       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9528       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9529       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9530 
9531       // Check of we need to combine values from two sources within a byte.
9532       if (!(LHSUsedLanes & RHSUsedLanes) &&
9533           // If we select high and lower word keep it for SDWA.
9534           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9535           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9536         // Each byte in each mask is either selector mask 0-3, or has higher
9537         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9538         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9539         // mask which is not 0xff wins. By anding both masks we have a correct
9540         // result except that 0x0c shall be corrected to give 0x0c only.
9541         uint32_t Mask = LHSMask & RHSMask;
9542         for (unsigned I = 0; I < 32; I += 8) {
9543           uint32_t ByteSel = 0xff << I;
9544           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9545             Mask &= (0x0c << I) & 0xffffffff;
9546         }
9547 
9548         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9549         // or 0x0c.
9550         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9551         SDLoc DL(N);
9552 
9553         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9554                            LHS.getOperand(0), RHS.getOperand(0),
9555                            DAG.getConstant(Sel, DL, MVT::i32));
9556       }
9557     }
9558   }
9559 
9560   return SDValue();
9561 }
9562 
9563 SDValue SITargetLowering::performOrCombine(SDNode *N,
9564                                            DAGCombinerInfo &DCI) const {
9565   SelectionDAG &DAG = DCI.DAG;
9566   SDValue LHS = N->getOperand(0);
9567   SDValue RHS = N->getOperand(1);
9568 
9569   EVT VT = N->getValueType(0);
9570   if (VT == MVT::i1) {
9571     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9572     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9573         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9574       SDValue Src = LHS.getOperand(0);
9575       if (Src != RHS.getOperand(0))
9576         return SDValue();
9577 
9578       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9579       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9580       if (!CLHS || !CRHS)
9581         return SDValue();
9582 
9583       // Only 10 bits are used.
9584       static const uint32_t MaxMask = 0x3ff;
9585 
9586       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9587       SDLoc DL(N);
9588       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9589                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9590     }
9591 
9592     return SDValue();
9593   }
9594 
9595   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9596   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9597       LHS.getOpcode() == AMDGPUISD::PERM &&
9598       isa<ConstantSDNode>(LHS.getOperand(2))) {
9599     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9600     if (!Sel)
9601       return SDValue();
9602 
9603     Sel |= LHS.getConstantOperandVal(2);
9604     SDLoc DL(N);
9605     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9606                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9607   }
9608 
9609   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9610   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9611   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9612       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9613     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9614     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9615     if (LHSMask != ~0u && RHSMask != ~0u) {
9616       // Canonicalize the expression in an attempt to have fewer unique masks
9617       // and therefore fewer registers used to hold the masks.
9618       if (LHSMask > RHSMask) {
9619         std::swap(LHSMask, RHSMask);
9620         std::swap(LHS, RHS);
9621       }
9622 
9623       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9624       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9625       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9626       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9627 
9628       // Check of we need to combine values from two sources within a byte.
9629       if (!(LHSUsedLanes & RHSUsedLanes) &&
9630           // If we select high and lower word keep it for SDWA.
9631           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9632           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9633         // Kill zero bytes selected by other mask. Zero value is 0xc.
9634         LHSMask &= ~RHSUsedLanes;
9635         RHSMask &= ~LHSUsedLanes;
9636         // Add 4 to each active LHS lane
9637         LHSMask |= LHSUsedLanes & 0x04040404;
9638         // Combine masks
9639         uint32_t Sel = LHSMask | RHSMask;
9640         SDLoc DL(N);
9641 
9642         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9643                            LHS.getOperand(0), RHS.getOperand(0),
9644                            DAG.getConstant(Sel, DL, MVT::i32));
9645       }
9646     }
9647   }
9648 
9649   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9650     return SDValue();
9651 
9652   // TODO: This could be a generic combine with a predicate for extracting the
9653   // high half of an integer being free.
9654 
9655   // (or i64:x, (zero_extend i32:y)) ->
9656   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9657   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9658       RHS.getOpcode() != ISD::ZERO_EXTEND)
9659     std::swap(LHS, RHS);
9660 
9661   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9662     SDValue ExtSrc = RHS.getOperand(0);
9663     EVT SrcVT = ExtSrc.getValueType();
9664     if (SrcVT == MVT::i32) {
9665       SDLoc SL(N);
9666       SDValue LowLHS, HiBits;
9667       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9668       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9669 
9670       DCI.AddToWorklist(LowOr.getNode());
9671       DCI.AddToWorklist(HiBits.getNode());
9672 
9673       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9674                                 LowOr, HiBits);
9675       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9676     }
9677   }
9678 
9679   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9680   if (CRHS) {
9681     if (SDValue Split
9682           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9683                                      N->getOperand(0), CRHS))
9684       return Split;
9685   }
9686 
9687   return SDValue();
9688 }
9689 
9690 SDValue SITargetLowering::performXorCombine(SDNode *N,
9691                                             DAGCombinerInfo &DCI) const {
9692   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9693     return RV;
9694 
9695   EVT VT = N->getValueType(0);
9696   if (VT != MVT::i64)
9697     return SDValue();
9698 
9699   SDValue LHS = N->getOperand(0);
9700   SDValue RHS = N->getOperand(1);
9701 
9702   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9703   if (CRHS) {
9704     if (SDValue Split
9705           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9706       return Split;
9707   }
9708 
9709   return SDValue();
9710 }
9711 
9712 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9713                                                    DAGCombinerInfo &DCI) const {
9714   if (!Subtarget->has16BitInsts() ||
9715       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9716     return SDValue();
9717 
9718   EVT VT = N->getValueType(0);
9719   if (VT != MVT::i32)
9720     return SDValue();
9721 
9722   SDValue Src = N->getOperand(0);
9723   if (Src.getValueType() != MVT::i16)
9724     return SDValue();
9725 
9726   return SDValue();
9727 }
9728 
9729 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9730                                                         DAGCombinerInfo &DCI)
9731                                                         const {
9732   SDValue Src = N->getOperand(0);
9733   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9734 
9735   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9736       VTSign->getVT() == MVT::i8) ||
9737       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9738       VTSign->getVT() == MVT::i16)) &&
9739       Src.hasOneUse()) {
9740     auto *M = cast<MemSDNode>(Src);
9741     SDValue Ops[] = {
9742       Src.getOperand(0), // Chain
9743       Src.getOperand(1), // rsrc
9744       Src.getOperand(2), // vindex
9745       Src.getOperand(3), // voffset
9746       Src.getOperand(4), // soffset
9747       Src.getOperand(5), // offset
9748       Src.getOperand(6),
9749       Src.getOperand(7)
9750     };
9751     // replace with BUFFER_LOAD_BYTE/SHORT
9752     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9753                                          Src.getOperand(0).getValueType());
9754     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9755                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9756     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9757                                                           ResList,
9758                                                           Ops, M->getMemoryVT(),
9759                                                           M->getMemOperand());
9760     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9761                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9762   }
9763   return SDValue();
9764 }
9765 
9766 SDValue SITargetLowering::performClassCombine(SDNode *N,
9767                                               DAGCombinerInfo &DCI) const {
9768   SelectionDAG &DAG = DCI.DAG;
9769   SDValue Mask = N->getOperand(1);
9770 
9771   // fp_class x, 0 -> false
9772   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9773     if (CMask->isZero())
9774       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9775   }
9776 
9777   if (N->getOperand(0).isUndef())
9778     return DAG.getUNDEF(MVT::i1);
9779 
9780   return SDValue();
9781 }
9782 
9783 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9784                                             DAGCombinerInfo &DCI) const {
9785   EVT VT = N->getValueType(0);
9786   SDValue N0 = N->getOperand(0);
9787 
9788   if (N0.isUndef())
9789     return N0;
9790 
9791   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9792                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9793     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9794                            N->getFlags());
9795   }
9796 
9797   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9798     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9799                            N0.getOperand(0), N->getFlags());
9800   }
9801 
9802   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9803 }
9804 
9805 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9806                                        unsigned MaxDepth) const {
9807   unsigned Opcode = Op.getOpcode();
9808   if (Opcode == ISD::FCANONICALIZE)
9809     return true;
9810 
9811   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9812     auto F = CFP->getValueAPF();
9813     if (F.isNaN() && F.isSignaling())
9814       return false;
9815     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9816   }
9817 
9818   // If source is a result of another standard FP operation it is already in
9819   // canonical form.
9820   if (MaxDepth == 0)
9821     return false;
9822 
9823   switch (Opcode) {
9824   // These will flush denorms if required.
9825   case ISD::FADD:
9826   case ISD::FSUB:
9827   case ISD::FMUL:
9828   case ISD::FCEIL:
9829   case ISD::FFLOOR:
9830   case ISD::FMA:
9831   case ISD::FMAD:
9832   case ISD::FSQRT:
9833   case ISD::FDIV:
9834   case ISD::FREM:
9835   case ISD::FP_ROUND:
9836   case ISD::FP_EXTEND:
9837   case AMDGPUISD::FMUL_LEGACY:
9838   case AMDGPUISD::FMAD_FTZ:
9839   case AMDGPUISD::RCP:
9840   case AMDGPUISD::RSQ:
9841   case AMDGPUISD::RSQ_CLAMP:
9842   case AMDGPUISD::RCP_LEGACY:
9843   case AMDGPUISD::RCP_IFLAG:
9844   case AMDGPUISD::DIV_SCALE:
9845   case AMDGPUISD::DIV_FMAS:
9846   case AMDGPUISD::DIV_FIXUP:
9847   case AMDGPUISD::FRACT:
9848   case AMDGPUISD::LDEXP:
9849   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9850   case AMDGPUISD::CVT_F32_UBYTE0:
9851   case AMDGPUISD::CVT_F32_UBYTE1:
9852   case AMDGPUISD::CVT_F32_UBYTE2:
9853   case AMDGPUISD::CVT_F32_UBYTE3:
9854     return true;
9855 
9856   // It can/will be lowered or combined as a bit operation.
9857   // Need to check their input recursively to handle.
9858   case ISD::FNEG:
9859   case ISD::FABS:
9860   case ISD::FCOPYSIGN:
9861     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9862 
9863   case ISD::FSIN:
9864   case ISD::FCOS:
9865   case ISD::FSINCOS:
9866     return Op.getValueType().getScalarType() != MVT::f16;
9867 
9868   case ISD::FMINNUM:
9869   case ISD::FMAXNUM:
9870   case ISD::FMINNUM_IEEE:
9871   case ISD::FMAXNUM_IEEE:
9872   case AMDGPUISD::CLAMP:
9873   case AMDGPUISD::FMED3:
9874   case AMDGPUISD::FMAX3:
9875   case AMDGPUISD::FMIN3: {
9876     // FIXME: Shouldn't treat the generic operations different based these.
9877     // However, we aren't really required to flush the result from
9878     // minnum/maxnum..
9879 
9880     // snans will be quieted, so we only need to worry about denormals.
9881     if (Subtarget->supportsMinMaxDenormModes() ||
9882         denormalsEnabledForType(DAG, Op.getValueType()))
9883       return true;
9884 
9885     // Flushing may be required.
9886     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9887     // targets need to check their input recursively.
9888 
9889     // FIXME: Does this apply with clamp? It's implemented with max.
9890     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9891       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9892         return false;
9893     }
9894 
9895     return true;
9896   }
9897   case ISD::SELECT: {
9898     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9899            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9900   }
9901   case ISD::BUILD_VECTOR: {
9902     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9903       SDValue SrcOp = Op.getOperand(i);
9904       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9905         return false;
9906     }
9907 
9908     return true;
9909   }
9910   case ISD::EXTRACT_VECTOR_ELT:
9911   case ISD::EXTRACT_SUBVECTOR: {
9912     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9913   }
9914   case ISD::INSERT_VECTOR_ELT: {
9915     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9916            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9917   }
9918   case ISD::UNDEF:
9919     // Could be anything.
9920     return false;
9921 
9922   case ISD::BITCAST:
9923     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9924   case ISD::TRUNCATE: {
9925     // Hack round the mess we make when legalizing extract_vector_elt
9926     if (Op.getValueType() == MVT::i16) {
9927       SDValue TruncSrc = Op.getOperand(0);
9928       if (TruncSrc.getValueType() == MVT::i32 &&
9929           TruncSrc.getOpcode() == ISD::BITCAST &&
9930           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9931         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9932       }
9933     }
9934     return false;
9935   }
9936   case ISD::INTRINSIC_WO_CHAIN: {
9937     unsigned IntrinsicID
9938       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9939     // TODO: Handle more intrinsics
9940     switch (IntrinsicID) {
9941     case Intrinsic::amdgcn_cvt_pkrtz:
9942     case Intrinsic::amdgcn_cubeid:
9943     case Intrinsic::amdgcn_frexp_mant:
9944     case Intrinsic::amdgcn_fdot2:
9945     case Intrinsic::amdgcn_rcp:
9946     case Intrinsic::amdgcn_rsq:
9947     case Intrinsic::amdgcn_rsq_clamp:
9948     case Intrinsic::amdgcn_rcp_legacy:
9949     case Intrinsic::amdgcn_rsq_legacy:
9950     case Intrinsic::amdgcn_trig_preop:
9951       return true;
9952     default:
9953       break;
9954     }
9955 
9956     LLVM_FALLTHROUGH;
9957   }
9958   default:
9959     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9960            DAG.isKnownNeverSNaN(Op);
9961   }
9962 
9963   llvm_unreachable("invalid operation");
9964 }
9965 
9966 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9967                                        unsigned MaxDepth) const {
9968   MachineRegisterInfo &MRI = MF.getRegInfo();
9969   MachineInstr *MI = MRI.getVRegDef(Reg);
9970   unsigned Opcode = MI->getOpcode();
9971 
9972   if (Opcode == AMDGPU::G_FCANONICALIZE)
9973     return true;
9974 
9975   Optional<FPValueAndVReg> FCR;
9976   // Constant splat (can be padded with undef) or scalar constant.
9977   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9978     if (FCR->Value.isSignaling())
9979       return false;
9980     return !FCR->Value.isDenormal() ||
9981            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9982   }
9983 
9984   if (MaxDepth == 0)
9985     return false;
9986 
9987   switch (Opcode) {
9988   case AMDGPU::G_FMINNUM_IEEE:
9989   case AMDGPU::G_FMAXNUM_IEEE: {
9990     if (Subtarget->supportsMinMaxDenormModes() ||
9991         denormalsEnabledForType(MRI.getType(Reg), MF))
9992       return true;
9993     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9994       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9995         return false;
9996     return true;
9997   }
9998   default:
9999     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10000            isKnownNeverSNaN(Reg, MRI);
10001   }
10002 
10003   llvm_unreachable("invalid operation");
10004 }
10005 
10006 // Constant fold canonicalize.
10007 SDValue SITargetLowering::getCanonicalConstantFP(
10008   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10009   // Flush denormals to 0 if not enabled.
10010   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10011     return DAG.getConstantFP(0.0, SL, VT);
10012 
10013   if (C.isNaN()) {
10014     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10015     if (C.isSignaling()) {
10016       // Quiet a signaling NaN.
10017       // FIXME: Is this supposed to preserve payload bits?
10018       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10019     }
10020 
10021     // Make sure it is the canonical NaN bitpattern.
10022     //
10023     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10024     // immediate?
10025     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10026       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10027   }
10028 
10029   // Already canonical.
10030   return DAG.getConstantFP(C, SL, VT);
10031 }
10032 
10033 static bool vectorEltWillFoldAway(SDValue Op) {
10034   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10035 }
10036 
10037 SDValue SITargetLowering::performFCanonicalizeCombine(
10038   SDNode *N,
10039   DAGCombinerInfo &DCI) const {
10040   SelectionDAG &DAG = DCI.DAG;
10041   SDValue N0 = N->getOperand(0);
10042   EVT VT = N->getValueType(0);
10043 
10044   // fcanonicalize undef -> qnan
10045   if (N0.isUndef()) {
10046     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10047     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10048   }
10049 
10050   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10051     EVT VT = N->getValueType(0);
10052     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10053   }
10054 
10055   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10056   //                                                   (fcanonicalize k)
10057   //
10058   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10059 
10060   // TODO: This could be better with wider vectors that will be split to v2f16,
10061   // and to consider uses since there aren't that many packed operations.
10062   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10063       isTypeLegal(MVT::v2f16)) {
10064     SDLoc SL(N);
10065     SDValue NewElts[2];
10066     SDValue Lo = N0.getOperand(0);
10067     SDValue Hi = N0.getOperand(1);
10068     EVT EltVT = Lo.getValueType();
10069 
10070     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10071       for (unsigned I = 0; I != 2; ++I) {
10072         SDValue Op = N0.getOperand(I);
10073         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10074           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10075                                               CFP->getValueAPF());
10076         } else if (Op.isUndef()) {
10077           // Handled below based on what the other operand is.
10078           NewElts[I] = Op;
10079         } else {
10080           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10081         }
10082       }
10083 
10084       // If one half is undef, and one is constant, prefer a splat vector rather
10085       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10086       // cheaper to use and may be free with a packed operation.
10087       if (NewElts[0].isUndef()) {
10088         if (isa<ConstantFPSDNode>(NewElts[1]))
10089           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10090             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10091       }
10092 
10093       if (NewElts[1].isUndef()) {
10094         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10095           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10096       }
10097 
10098       return DAG.getBuildVector(VT, SL, NewElts);
10099     }
10100   }
10101 
10102   unsigned SrcOpc = N0.getOpcode();
10103 
10104   // If it's free to do so, push canonicalizes further up the source, which may
10105   // find a canonical source.
10106   //
10107   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10108   // sNaNs.
10109   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10110     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10111     if (CRHS && N0.hasOneUse()) {
10112       SDLoc SL(N);
10113       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10114                                    N0.getOperand(0));
10115       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10116       DCI.AddToWorklist(Canon0.getNode());
10117 
10118       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10119     }
10120   }
10121 
10122   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10123 }
10124 
10125 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10126   switch (Opc) {
10127   case ISD::FMAXNUM:
10128   case ISD::FMAXNUM_IEEE:
10129     return AMDGPUISD::FMAX3;
10130   case ISD::SMAX:
10131     return AMDGPUISD::SMAX3;
10132   case ISD::UMAX:
10133     return AMDGPUISD::UMAX3;
10134   case ISD::FMINNUM:
10135   case ISD::FMINNUM_IEEE:
10136     return AMDGPUISD::FMIN3;
10137   case ISD::SMIN:
10138     return AMDGPUISD::SMIN3;
10139   case ISD::UMIN:
10140     return AMDGPUISD::UMIN3;
10141   default:
10142     llvm_unreachable("Not a min/max opcode");
10143   }
10144 }
10145 
10146 SDValue SITargetLowering::performIntMed3ImmCombine(
10147   SelectionDAG &DAG, const SDLoc &SL,
10148   SDValue Op0, SDValue Op1, bool Signed) const {
10149   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10150   if (!K1)
10151     return SDValue();
10152 
10153   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10154   if (!K0)
10155     return SDValue();
10156 
10157   if (Signed) {
10158     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10159       return SDValue();
10160   } else {
10161     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10162       return SDValue();
10163   }
10164 
10165   EVT VT = K0->getValueType(0);
10166   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10167   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10168     return DAG.getNode(Med3Opc, SL, VT,
10169                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10170   }
10171 
10172   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10173   if (VT == MVT::i16) {
10174     MVT NVT = MVT::i32;
10175     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10176 
10177     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10178     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10179     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10180 
10181     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10182     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10183   }
10184 
10185   return SDValue();
10186 }
10187 
10188 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10189   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10190     return C;
10191 
10192   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10193     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10194       return C;
10195   }
10196 
10197   return nullptr;
10198 }
10199 
10200 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10201                                                   const SDLoc &SL,
10202                                                   SDValue Op0,
10203                                                   SDValue Op1) const {
10204   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10205   if (!K1)
10206     return SDValue();
10207 
10208   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10209   if (!K0)
10210     return SDValue();
10211 
10212   // Ordered >= (although NaN inputs should have folded away by now).
10213   if (K0->getValueAPF() > K1->getValueAPF())
10214     return SDValue();
10215 
10216   const MachineFunction &MF = DAG.getMachineFunction();
10217   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10218 
10219   // TODO: Check IEEE bit enabled?
10220   EVT VT = Op0.getValueType();
10221   if (Info->getMode().DX10Clamp) {
10222     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10223     // hardware fmed3 behavior converting to a min.
10224     // FIXME: Should this be allowing -0.0?
10225     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10226       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10227   }
10228 
10229   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10230   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10231     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10232     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10233     // then give the other result, which is different from med3 with a NaN
10234     // input.
10235     SDValue Var = Op0.getOperand(0);
10236     if (!DAG.isKnownNeverSNaN(Var))
10237       return SDValue();
10238 
10239     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10240 
10241     if ((!K0->hasOneUse() ||
10242          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10243         (!K1->hasOneUse() ||
10244          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10245       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10246                          Var, SDValue(K0, 0), SDValue(K1, 0));
10247     }
10248   }
10249 
10250   return SDValue();
10251 }
10252 
10253 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10254                                                DAGCombinerInfo &DCI) const {
10255   SelectionDAG &DAG = DCI.DAG;
10256 
10257   EVT VT = N->getValueType(0);
10258   unsigned Opc = N->getOpcode();
10259   SDValue Op0 = N->getOperand(0);
10260   SDValue Op1 = N->getOperand(1);
10261 
10262   // Only do this if the inner op has one use since this will just increases
10263   // register pressure for no benefit.
10264 
10265   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10266       !VT.isVector() &&
10267       (VT == MVT::i32 || VT == MVT::f32 ||
10268        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10269     // max(max(a, b), c) -> max3(a, b, c)
10270     // min(min(a, b), c) -> min3(a, b, c)
10271     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10272       SDLoc DL(N);
10273       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10274                          DL,
10275                          N->getValueType(0),
10276                          Op0.getOperand(0),
10277                          Op0.getOperand(1),
10278                          Op1);
10279     }
10280 
10281     // Try commuted.
10282     // max(a, max(b, c)) -> max3(a, b, c)
10283     // min(a, min(b, c)) -> min3(a, b, c)
10284     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10285       SDLoc DL(N);
10286       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10287                          DL,
10288                          N->getValueType(0),
10289                          Op0,
10290                          Op1.getOperand(0),
10291                          Op1.getOperand(1));
10292     }
10293   }
10294 
10295   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10296   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10297     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10298       return Med3;
10299   }
10300 
10301   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10302     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10303       return Med3;
10304   }
10305 
10306   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10307   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10308        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10309        (Opc == AMDGPUISD::FMIN_LEGACY &&
10310         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10311       (VT == MVT::f32 || VT == MVT::f64 ||
10312        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10313        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10314       Op0.hasOneUse()) {
10315     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10316       return Res;
10317   }
10318 
10319   return SDValue();
10320 }
10321 
10322 static bool isClampZeroToOne(SDValue A, SDValue B) {
10323   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10324     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10325       // FIXME: Should this be allowing -0.0?
10326       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10327              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10328     }
10329   }
10330 
10331   return false;
10332 }
10333 
10334 // FIXME: Should only worry about snans for version with chain.
10335 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10336                                               DAGCombinerInfo &DCI) const {
10337   EVT VT = N->getValueType(0);
10338   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10339   // NaNs. With a NaN input, the order of the operands may change the result.
10340 
10341   SelectionDAG &DAG = DCI.DAG;
10342   SDLoc SL(N);
10343 
10344   SDValue Src0 = N->getOperand(0);
10345   SDValue Src1 = N->getOperand(1);
10346   SDValue Src2 = N->getOperand(2);
10347 
10348   if (isClampZeroToOne(Src0, Src1)) {
10349     // const_a, const_b, x -> clamp is safe in all cases including signaling
10350     // nans.
10351     // FIXME: Should this be allowing -0.0?
10352     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10353   }
10354 
10355   const MachineFunction &MF = DAG.getMachineFunction();
10356   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10357 
10358   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10359   // handling no dx10-clamp?
10360   if (Info->getMode().DX10Clamp) {
10361     // If NaNs is clamped to 0, we are free to reorder the inputs.
10362 
10363     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10364       std::swap(Src0, Src1);
10365 
10366     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10367       std::swap(Src1, Src2);
10368 
10369     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10370       std::swap(Src0, Src1);
10371 
10372     if (isClampZeroToOne(Src1, Src2))
10373       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10374   }
10375 
10376   return SDValue();
10377 }
10378 
10379 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10380                                                  DAGCombinerInfo &DCI) const {
10381   SDValue Src0 = N->getOperand(0);
10382   SDValue Src1 = N->getOperand(1);
10383   if (Src0.isUndef() && Src1.isUndef())
10384     return DCI.DAG.getUNDEF(N->getValueType(0));
10385   return SDValue();
10386 }
10387 
10388 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10389 // expanded into a set of cmp/select instructions.
10390 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10391                                                 unsigned NumElem,
10392                                                 bool IsDivergentIdx) {
10393   if (UseDivergentRegisterIndexing)
10394     return false;
10395 
10396   unsigned VecSize = EltSize * NumElem;
10397 
10398   // Sub-dword vectors of size 2 dword or less have better implementation.
10399   if (VecSize <= 64 && EltSize < 32)
10400     return false;
10401 
10402   // Always expand the rest of sub-dword instructions, otherwise it will be
10403   // lowered via memory.
10404   if (EltSize < 32)
10405     return true;
10406 
10407   // Always do this if var-idx is divergent, otherwise it will become a loop.
10408   if (IsDivergentIdx)
10409     return true;
10410 
10411   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10412   unsigned NumInsts = NumElem /* Number of compares */ +
10413                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10414   return NumInsts <= 16;
10415 }
10416 
10417 static bool shouldExpandVectorDynExt(SDNode *N) {
10418   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10419   if (isa<ConstantSDNode>(Idx))
10420     return false;
10421 
10422   SDValue Vec = N->getOperand(0);
10423   EVT VecVT = Vec.getValueType();
10424   EVT EltVT = VecVT.getVectorElementType();
10425   unsigned EltSize = EltVT.getSizeInBits();
10426   unsigned NumElem = VecVT.getVectorNumElements();
10427 
10428   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10429                                                     Idx->isDivergent());
10430 }
10431 
10432 SDValue SITargetLowering::performExtractVectorEltCombine(
10433   SDNode *N, DAGCombinerInfo &DCI) const {
10434   SDValue Vec = N->getOperand(0);
10435   SelectionDAG &DAG = DCI.DAG;
10436 
10437   EVT VecVT = Vec.getValueType();
10438   EVT EltVT = VecVT.getVectorElementType();
10439 
10440   if ((Vec.getOpcode() == ISD::FNEG ||
10441        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10442     SDLoc SL(N);
10443     EVT EltVT = N->getValueType(0);
10444     SDValue Idx = N->getOperand(1);
10445     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10446                               Vec.getOperand(0), Idx);
10447     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10448   }
10449 
10450   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10451   //    =>
10452   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10453   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10454   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10455   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10456     SDLoc SL(N);
10457     EVT EltVT = N->getValueType(0);
10458     SDValue Idx = N->getOperand(1);
10459     unsigned Opc = Vec.getOpcode();
10460 
10461     switch(Opc) {
10462     default:
10463       break;
10464       // TODO: Support other binary operations.
10465     case ISD::FADD:
10466     case ISD::FSUB:
10467     case ISD::FMUL:
10468     case ISD::ADD:
10469     case ISD::UMIN:
10470     case ISD::UMAX:
10471     case ISD::SMIN:
10472     case ISD::SMAX:
10473     case ISD::FMAXNUM:
10474     case ISD::FMINNUM:
10475     case ISD::FMAXNUM_IEEE:
10476     case ISD::FMINNUM_IEEE: {
10477       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10478                                  Vec.getOperand(0), Idx);
10479       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10480                                  Vec.getOperand(1), Idx);
10481 
10482       DCI.AddToWorklist(Elt0.getNode());
10483       DCI.AddToWorklist(Elt1.getNode());
10484       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10485     }
10486     }
10487   }
10488 
10489   unsigned VecSize = VecVT.getSizeInBits();
10490   unsigned EltSize = EltVT.getSizeInBits();
10491 
10492   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10493   if (::shouldExpandVectorDynExt(N)) {
10494     SDLoc SL(N);
10495     SDValue Idx = N->getOperand(1);
10496     SDValue V;
10497     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10498       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10499       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10500       if (I == 0)
10501         V = Elt;
10502       else
10503         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10504     }
10505     return V;
10506   }
10507 
10508   if (!DCI.isBeforeLegalize())
10509     return SDValue();
10510 
10511   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10512   // elements. This exposes more load reduction opportunities by replacing
10513   // multiple small extract_vector_elements with a single 32-bit extract.
10514   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10515   if (isa<MemSDNode>(Vec) &&
10516       EltSize <= 16 &&
10517       EltVT.isByteSized() &&
10518       VecSize > 32 &&
10519       VecSize % 32 == 0 &&
10520       Idx) {
10521     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10522 
10523     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10524     unsigned EltIdx = BitIndex / 32;
10525     unsigned LeftoverBitIdx = BitIndex % 32;
10526     SDLoc SL(N);
10527 
10528     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10529     DCI.AddToWorklist(Cast.getNode());
10530 
10531     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10532                               DAG.getConstant(EltIdx, SL, MVT::i32));
10533     DCI.AddToWorklist(Elt.getNode());
10534     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10535                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10536     DCI.AddToWorklist(Srl.getNode());
10537 
10538     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10539     DCI.AddToWorklist(Trunc.getNode());
10540     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10541   }
10542 
10543   return SDValue();
10544 }
10545 
10546 SDValue
10547 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10548                                                 DAGCombinerInfo &DCI) const {
10549   SDValue Vec = N->getOperand(0);
10550   SDValue Idx = N->getOperand(2);
10551   EVT VecVT = Vec.getValueType();
10552   EVT EltVT = VecVT.getVectorElementType();
10553 
10554   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10555   // => BUILD_VECTOR n x select (e, const-idx)
10556   if (!::shouldExpandVectorDynExt(N))
10557     return SDValue();
10558 
10559   SelectionDAG &DAG = DCI.DAG;
10560   SDLoc SL(N);
10561   SDValue Ins = N->getOperand(1);
10562   EVT IdxVT = Idx.getValueType();
10563 
10564   SmallVector<SDValue, 16> Ops;
10565   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10566     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10567     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10568     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10569     Ops.push_back(V);
10570   }
10571 
10572   return DAG.getBuildVector(VecVT, SL, Ops);
10573 }
10574 
10575 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10576                                           const SDNode *N0,
10577                                           const SDNode *N1) const {
10578   EVT VT = N0->getValueType(0);
10579 
10580   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10581   // support denormals ever.
10582   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10583        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10584         getSubtarget()->hasMadF16())) &&
10585        isOperationLegal(ISD::FMAD, VT))
10586     return ISD::FMAD;
10587 
10588   const TargetOptions &Options = DAG.getTarget().Options;
10589   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10590        (N0->getFlags().hasAllowContract() &&
10591         N1->getFlags().hasAllowContract())) &&
10592       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10593     return ISD::FMA;
10594   }
10595 
10596   return 0;
10597 }
10598 
10599 // For a reassociatable opcode perform:
10600 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10601 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10602                                                SelectionDAG &DAG) const {
10603   EVT VT = N->getValueType(0);
10604   if (VT != MVT::i32 && VT != MVT::i64)
10605     return SDValue();
10606 
10607   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10608     return SDValue();
10609 
10610   unsigned Opc = N->getOpcode();
10611   SDValue Op0 = N->getOperand(0);
10612   SDValue Op1 = N->getOperand(1);
10613 
10614   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10615     return SDValue();
10616 
10617   if (Op0->isDivergent())
10618     std::swap(Op0, Op1);
10619 
10620   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10621     return SDValue();
10622 
10623   SDValue Op2 = Op1.getOperand(1);
10624   Op1 = Op1.getOperand(0);
10625   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10626     return SDValue();
10627 
10628   if (Op1->isDivergent())
10629     std::swap(Op1, Op2);
10630 
10631   SDLoc SL(N);
10632   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10633   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10634 }
10635 
10636 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10637                            EVT VT,
10638                            SDValue N0, SDValue N1, SDValue N2,
10639                            bool Signed) {
10640   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10641   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10642   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10643   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10644 }
10645 
10646 SDValue SITargetLowering::performAddCombine(SDNode *N,
10647                                             DAGCombinerInfo &DCI) const {
10648   SelectionDAG &DAG = DCI.DAG;
10649   EVT VT = N->getValueType(0);
10650   SDLoc SL(N);
10651   SDValue LHS = N->getOperand(0);
10652   SDValue RHS = N->getOperand(1);
10653 
10654   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10655       && Subtarget->hasMad64_32() &&
10656       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10657       VT.getScalarSizeInBits() <= 64) {
10658     if (LHS.getOpcode() != ISD::MUL)
10659       std::swap(LHS, RHS);
10660 
10661     SDValue MulLHS = LHS.getOperand(0);
10662     SDValue MulRHS = LHS.getOperand(1);
10663     SDValue AddRHS = RHS;
10664 
10665     // TODO: Maybe restrict if SGPR inputs.
10666     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10667         numBitsUnsigned(MulRHS, DAG) <= 32) {
10668       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10669       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10670       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10671       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10672     }
10673 
10674     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10675       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10676       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10677       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10678       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10679     }
10680 
10681     return SDValue();
10682   }
10683 
10684   if (SDValue V = reassociateScalarOps(N, DAG)) {
10685     return V;
10686   }
10687 
10688   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10689     return SDValue();
10690 
10691   // add x, zext (setcc) => addcarry x, 0, setcc
10692   // add x, sext (setcc) => subcarry x, 0, setcc
10693   unsigned Opc = LHS.getOpcode();
10694   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10695       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10696     std::swap(RHS, LHS);
10697 
10698   Opc = RHS.getOpcode();
10699   switch (Opc) {
10700   default: break;
10701   case ISD::ZERO_EXTEND:
10702   case ISD::SIGN_EXTEND:
10703   case ISD::ANY_EXTEND: {
10704     auto Cond = RHS.getOperand(0);
10705     // If this won't be a real VOPC output, we would still need to insert an
10706     // extra instruction anyway.
10707     if (!isBoolSGPR(Cond))
10708       break;
10709     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10710     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10711     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10712     return DAG.getNode(Opc, SL, VTList, Args);
10713   }
10714   case ISD::ADDCARRY: {
10715     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10716     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10717     if (!C || C->getZExtValue() != 0) break;
10718     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10719     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10720   }
10721   }
10722   return SDValue();
10723 }
10724 
10725 SDValue SITargetLowering::performSubCombine(SDNode *N,
10726                                             DAGCombinerInfo &DCI) const {
10727   SelectionDAG &DAG = DCI.DAG;
10728   EVT VT = N->getValueType(0);
10729 
10730   if (VT != MVT::i32)
10731     return SDValue();
10732 
10733   SDLoc SL(N);
10734   SDValue LHS = N->getOperand(0);
10735   SDValue RHS = N->getOperand(1);
10736 
10737   // sub x, zext (setcc) => subcarry x, 0, setcc
10738   // sub x, sext (setcc) => addcarry x, 0, setcc
10739   unsigned Opc = RHS.getOpcode();
10740   switch (Opc) {
10741   default: break;
10742   case ISD::ZERO_EXTEND:
10743   case ISD::SIGN_EXTEND:
10744   case ISD::ANY_EXTEND: {
10745     auto Cond = RHS.getOperand(0);
10746     // If this won't be a real VOPC output, we would still need to insert an
10747     // extra instruction anyway.
10748     if (!isBoolSGPR(Cond))
10749       break;
10750     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10751     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10752     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10753     return DAG.getNode(Opc, SL, VTList, Args);
10754   }
10755   }
10756 
10757   if (LHS.getOpcode() == ISD::SUBCARRY) {
10758     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10759     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10760     if (!C || !C->isZero())
10761       return SDValue();
10762     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10763     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10764   }
10765   return SDValue();
10766 }
10767 
10768 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10769   DAGCombinerInfo &DCI) const {
10770 
10771   if (N->getValueType(0) != MVT::i32)
10772     return SDValue();
10773 
10774   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10775   if (!C || C->getZExtValue() != 0)
10776     return SDValue();
10777 
10778   SelectionDAG &DAG = DCI.DAG;
10779   SDValue LHS = N->getOperand(0);
10780 
10781   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10782   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10783   unsigned LHSOpc = LHS.getOpcode();
10784   unsigned Opc = N->getOpcode();
10785   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10786       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10787     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10788     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10789   }
10790   return SDValue();
10791 }
10792 
10793 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10794                                              DAGCombinerInfo &DCI) const {
10795   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10796     return SDValue();
10797 
10798   SelectionDAG &DAG = DCI.DAG;
10799   EVT VT = N->getValueType(0);
10800 
10801   SDLoc SL(N);
10802   SDValue LHS = N->getOperand(0);
10803   SDValue RHS = N->getOperand(1);
10804 
10805   // These should really be instruction patterns, but writing patterns with
10806   // source modifiers is a pain.
10807 
10808   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10809   if (LHS.getOpcode() == ISD::FADD) {
10810     SDValue A = LHS.getOperand(0);
10811     if (A == LHS.getOperand(1)) {
10812       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10813       if (FusedOp != 0) {
10814         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10815         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10816       }
10817     }
10818   }
10819 
10820   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10821   if (RHS.getOpcode() == ISD::FADD) {
10822     SDValue A = RHS.getOperand(0);
10823     if (A == RHS.getOperand(1)) {
10824       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10825       if (FusedOp != 0) {
10826         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10827         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10828       }
10829     }
10830   }
10831 
10832   return SDValue();
10833 }
10834 
10835 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10836                                              DAGCombinerInfo &DCI) const {
10837   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10838     return SDValue();
10839 
10840   SelectionDAG &DAG = DCI.DAG;
10841   SDLoc SL(N);
10842   EVT VT = N->getValueType(0);
10843   assert(!VT.isVector());
10844 
10845   // Try to get the fneg to fold into the source modifier. This undoes generic
10846   // DAG combines and folds them into the mad.
10847   //
10848   // Only do this if we are not trying to support denormals. v_mad_f32 does
10849   // not support denormals ever.
10850   SDValue LHS = N->getOperand(0);
10851   SDValue RHS = N->getOperand(1);
10852   if (LHS.getOpcode() == ISD::FADD) {
10853     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10854     SDValue A = LHS.getOperand(0);
10855     if (A == LHS.getOperand(1)) {
10856       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10857       if (FusedOp != 0){
10858         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10859         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10860 
10861         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10862       }
10863     }
10864   }
10865 
10866   if (RHS.getOpcode() == ISD::FADD) {
10867     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10868 
10869     SDValue A = RHS.getOperand(0);
10870     if (A == RHS.getOperand(1)) {
10871       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10872       if (FusedOp != 0){
10873         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10874         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10875       }
10876     }
10877   }
10878 
10879   return SDValue();
10880 }
10881 
10882 SDValue SITargetLowering::performFMACombine(SDNode *N,
10883                                             DAGCombinerInfo &DCI) const {
10884   SelectionDAG &DAG = DCI.DAG;
10885   EVT VT = N->getValueType(0);
10886   SDLoc SL(N);
10887 
10888   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10889     return SDValue();
10890 
10891   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10892   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10893   SDValue Op1 = N->getOperand(0);
10894   SDValue Op2 = N->getOperand(1);
10895   SDValue FMA = N->getOperand(2);
10896 
10897   if (FMA.getOpcode() != ISD::FMA ||
10898       Op1.getOpcode() != ISD::FP_EXTEND ||
10899       Op2.getOpcode() != ISD::FP_EXTEND)
10900     return SDValue();
10901 
10902   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10903   // regardless of the denorm mode setting. Therefore,
10904   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10905   const TargetOptions &Options = DAG.getTarget().Options;
10906   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10907       (N->getFlags().hasAllowContract() &&
10908        FMA->getFlags().hasAllowContract())) {
10909     Op1 = Op1.getOperand(0);
10910     Op2 = Op2.getOperand(0);
10911     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10912         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10913       return SDValue();
10914 
10915     SDValue Vec1 = Op1.getOperand(0);
10916     SDValue Idx1 = Op1.getOperand(1);
10917     SDValue Vec2 = Op2.getOperand(0);
10918 
10919     SDValue FMAOp1 = FMA.getOperand(0);
10920     SDValue FMAOp2 = FMA.getOperand(1);
10921     SDValue FMAAcc = FMA.getOperand(2);
10922 
10923     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10924         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10925       return SDValue();
10926 
10927     FMAOp1 = FMAOp1.getOperand(0);
10928     FMAOp2 = FMAOp2.getOperand(0);
10929     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10930         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10931       return SDValue();
10932 
10933     SDValue Vec3 = FMAOp1.getOperand(0);
10934     SDValue Vec4 = FMAOp2.getOperand(0);
10935     SDValue Idx2 = FMAOp1.getOperand(1);
10936 
10937     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10938         // Idx1 and Idx2 cannot be the same.
10939         Idx1 == Idx2)
10940       return SDValue();
10941 
10942     if (Vec1 == Vec2 || Vec3 == Vec4)
10943       return SDValue();
10944 
10945     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10946       return SDValue();
10947 
10948     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10949         (Vec1 == Vec4 && Vec2 == Vec3)) {
10950       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10951                          DAG.getTargetConstant(0, SL, MVT::i1));
10952     }
10953   }
10954   return SDValue();
10955 }
10956 
10957 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10958                                               DAGCombinerInfo &DCI) const {
10959   SelectionDAG &DAG = DCI.DAG;
10960   SDLoc SL(N);
10961 
10962   SDValue LHS = N->getOperand(0);
10963   SDValue RHS = N->getOperand(1);
10964   EVT VT = LHS.getValueType();
10965   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10966 
10967   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10968   if (!CRHS) {
10969     CRHS = dyn_cast<ConstantSDNode>(LHS);
10970     if (CRHS) {
10971       std::swap(LHS, RHS);
10972       CC = getSetCCSwappedOperands(CC);
10973     }
10974   }
10975 
10976   if (CRHS) {
10977     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10978         isBoolSGPR(LHS.getOperand(0))) {
10979       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10980       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10981       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10982       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10983       if ((CRHS->isAllOnes() &&
10984            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10985           (CRHS->isZero() &&
10986            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10987         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10988                            DAG.getConstant(-1, SL, MVT::i1));
10989       if ((CRHS->isAllOnes() &&
10990            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10991           (CRHS->isZero() &&
10992            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10993         return LHS.getOperand(0);
10994     }
10995 
10996     const APInt &CRHSVal = CRHS->getAPIntValue();
10997     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10998         LHS.getOpcode() == ISD::SELECT &&
10999         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11000         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11001         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11002         isBoolSGPR(LHS.getOperand(0))) {
11003       // Given CT != FT:
11004       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11005       // setcc (select cc, CT, CF), CF, ne => cc
11006       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11007       // setcc (select cc, CT, CF), CT, eq => cc
11008       const APInt &CT = LHS.getConstantOperandAPInt(1);
11009       const APInt &CF = LHS.getConstantOperandAPInt(2);
11010 
11011       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11012           (CT == CRHSVal && CC == ISD::SETNE))
11013         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11014                            DAG.getConstant(-1, SL, MVT::i1));
11015       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11016           (CT == CRHSVal && CC == ISD::SETEQ))
11017         return LHS.getOperand(0);
11018     }
11019   }
11020 
11021   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11022                                            VT != MVT::f16))
11023     return SDValue();
11024 
11025   // Match isinf/isfinite pattern
11026   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11027   // (fcmp one (fabs x), inf) -> (fp_class x,
11028   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11029   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11030     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11031     if (!CRHS)
11032       return SDValue();
11033 
11034     const APFloat &APF = CRHS->getValueAPF();
11035     if (APF.isInfinity() && !APF.isNegative()) {
11036       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11037                                  SIInstrFlags::N_INFINITY;
11038       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11039                                     SIInstrFlags::P_ZERO |
11040                                     SIInstrFlags::N_NORMAL |
11041                                     SIInstrFlags::P_NORMAL |
11042                                     SIInstrFlags::N_SUBNORMAL |
11043                                     SIInstrFlags::P_SUBNORMAL;
11044       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11045       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11046                          DAG.getConstant(Mask, SL, MVT::i32));
11047     }
11048   }
11049 
11050   return SDValue();
11051 }
11052 
11053 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11054                                                      DAGCombinerInfo &DCI) const {
11055   SelectionDAG &DAG = DCI.DAG;
11056   SDLoc SL(N);
11057   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11058 
11059   SDValue Src = N->getOperand(0);
11060   SDValue Shift = N->getOperand(0);
11061 
11062   // TODO: Extend type shouldn't matter (assuming legal types).
11063   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11064     Shift = Shift.getOperand(0);
11065 
11066   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11067     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11068     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11069     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11070     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11071     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11072     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11073       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11074                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11075 
11076       unsigned ShiftOffset = 8 * Offset;
11077       if (Shift.getOpcode() == ISD::SHL)
11078         ShiftOffset -= C->getZExtValue();
11079       else
11080         ShiftOffset += C->getZExtValue();
11081 
11082       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11083         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11084                            MVT::f32, Shifted);
11085       }
11086     }
11087   }
11088 
11089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11090   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11091   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11092     // We simplified Src. If this node is not dead, visit it again so it is
11093     // folded properly.
11094     if (N->getOpcode() != ISD::DELETED_NODE)
11095       DCI.AddToWorklist(N);
11096     return SDValue(N, 0);
11097   }
11098 
11099   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11100   if (SDValue DemandedSrc =
11101           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11102     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11103 
11104   return SDValue();
11105 }
11106 
11107 SDValue SITargetLowering::performClampCombine(SDNode *N,
11108                                               DAGCombinerInfo &DCI) const {
11109   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11110   if (!CSrc)
11111     return SDValue();
11112 
11113   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11114   const APFloat &F = CSrc->getValueAPF();
11115   APFloat Zero = APFloat::getZero(F.getSemantics());
11116   if (F < Zero ||
11117       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11118     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11119   }
11120 
11121   APFloat One(F.getSemantics(), "1.0");
11122   if (F > One)
11123     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11124 
11125   return SDValue(CSrc, 0);
11126 }
11127 
11128 
11129 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11130                                             DAGCombinerInfo &DCI) const {
11131   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11132     return SDValue();
11133   switch (N->getOpcode()) {
11134   case ISD::ADD:
11135     return performAddCombine(N, DCI);
11136   case ISD::SUB:
11137     return performSubCombine(N, DCI);
11138   case ISD::ADDCARRY:
11139   case ISD::SUBCARRY:
11140     return performAddCarrySubCarryCombine(N, DCI);
11141   case ISD::FADD:
11142     return performFAddCombine(N, DCI);
11143   case ISD::FSUB:
11144     return performFSubCombine(N, DCI);
11145   case ISD::SETCC:
11146     return performSetCCCombine(N, DCI);
11147   case ISD::FMAXNUM:
11148   case ISD::FMINNUM:
11149   case ISD::FMAXNUM_IEEE:
11150   case ISD::FMINNUM_IEEE:
11151   case ISD::SMAX:
11152   case ISD::SMIN:
11153   case ISD::UMAX:
11154   case ISD::UMIN:
11155   case AMDGPUISD::FMIN_LEGACY:
11156   case AMDGPUISD::FMAX_LEGACY:
11157     return performMinMaxCombine(N, DCI);
11158   case ISD::FMA:
11159     return performFMACombine(N, DCI);
11160   case ISD::AND:
11161     return performAndCombine(N, DCI);
11162   case ISD::OR:
11163     return performOrCombine(N, DCI);
11164   case ISD::XOR:
11165     return performXorCombine(N, DCI);
11166   case ISD::ZERO_EXTEND:
11167     return performZeroExtendCombine(N, DCI);
11168   case ISD::SIGN_EXTEND_INREG:
11169     return performSignExtendInRegCombine(N , DCI);
11170   case AMDGPUISD::FP_CLASS:
11171     return performClassCombine(N, DCI);
11172   case ISD::FCANONICALIZE:
11173     return performFCanonicalizeCombine(N, DCI);
11174   case AMDGPUISD::RCP:
11175     return performRcpCombine(N, DCI);
11176   case AMDGPUISD::FRACT:
11177   case AMDGPUISD::RSQ:
11178   case AMDGPUISD::RCP_LEGACY:
11179   case AMDGPUISD::RCP_IFLAG:
11180   case AMDGPUISD::RSQ_CLAMP:
11181   case AMDGPUISD::LDEXP: {
11182     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11183     SDValue Src = N->getOperand(0);
11184     if (Src.isUndef())
11185       return Src;
11186     break;
11187   }
11188   case ISD::SINT_TO_FP:
11189   case ISD::UINT_TO_FP:
11190     return performUCharToFloatCombine(N, DCI);
11191   case AMDGPUISD::CVT_F32_UBYTE0:
11192   case AMDGPUISD::CVT_F32_UBYTE1:
11193   case AMDGPUISD::CVT_F32_UBYTE2:
11194   case AMDGPUISD::CVT_F32_UBYTE3:
11195     return performCvtF32UByteNCombine(N, DCI);
11196   case AMDGPUISD::FMED3:
11197     return performFMed3Combine(N, DCI);
11198   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11199     return performCvtPkRTZCombine(N, DCI);
11200   case AMDGPUISD::CLAMP:
11201     return performClampCombine(N, DCI);
11202   case ISD::SCALAR_TO_VECTOR: {
11203     SelectionDAG &DAG = DCI.DAG;
11204     EVT VT = N->getValueType(0);
11205 
11206     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11207     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11208       SDLoc SL(N);
11209       SDValue Src = N->getOperand(0);
11210       EVT EltVT = Src.getValueType();
11211       if (EltVT == MVT::f16)
11212         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11213 
11214       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11215       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11216     }
11217 
11218     break;
11219   }
11220   case ISD::EXTRACT_VECTOR_ELT:
11221     return performExtractVectorEltCombine(N, DCI);
11222   case ISD::INSERT_VECTOR_ELT:
11223     return performInsertVectorEltCombine(N, DCI);
11224   case ISD::LOAD: {
11225     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11226       return Widended;
11227     LLVM_FALLTHROUGH;
11228   }
11229   default: {
11230     if (!DCI.isBeforeLegalize()) {
11231       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11232         return performMemSDNodeCombine(MemNode, DCI);
11233     }
11234 
11235     break;
11236   }
11237   }
11238 
11239   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11240 }
11241 
11242 /// Helper function for adjustWritemask
11243 static unsigned SubIdx2Lane(unsigned Idx) {
11244   switch (Idx) {
11245   default: return ~0u;
11246   case AMDGPU::sub0: return 0;
11247   case AMDGPU::sub1: return 1;
11248   case AMDGPU::sub2: return 2;
11249   case AMDGPU::sub3: return 3;
11250   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11251   }
11252 }
11253 
11254 /// Adjust the writemask of MIMG instructions
11255 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11256                                           SelectionDAG &DAG) const {
11257   unsigned Opcode = Node->getMachineOpcode();
11258 
11259   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11260   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11261   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11262     return Node; // not implemented for D16
11263 
11264   SDNode *Users[5] = { nullptr };
11265   unsigned Lane = 0;
11266   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11267   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11268   unsigned NewDmask = 0;
11269   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11270   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11271   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11272                   Node->getConstantOperandVal(LWEIdx))
11273                      ? true
11274                      : false;
11275   unsigned TFCLane = 0;
11276   bool HasChain = Node->getNumValues() > 1;
11277 
11278   if (OldDmask == 0) {
11279     // These are folded out, but on the chance it happens don't assert.
11280     return Node;
11281   }
11282 
11283   unsigned OldBitsSet = countPopulation(OldDmask);
11284   // Work out which is the TFE/LWE lane if that is enabled.
11285   if (UsesTFC) {
11286     TFCLane = OldBitsSet;
11287   }
11288 
11289   // Try to figure out the used register components
11290   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11291        I != E; ++I) {
11292 
11293     // Don't look at users of the chain.
11294     if (I.getUse().getResNo() != 0)
11295       continue;
11296 
11297     // Abort if we can't understand the usage
11298     if (!I->isMachineOpcode() ||
11299         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11300       return Node;
11301 
11302     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11303     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11304     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11305     // set, etc.
11306     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11307     if (Lane == ~0u)
11308       return Node;
11309 
11310     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11311     if (UsesTFC && Lane == TFCLane) {
11312       Users[Lane] = *I;
11313     } else {
11314       // Set which texture component corresponds to the lane.
11315       unsigned Comp;
11316       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11317         Comp = countTrailingZeros(Dmask);
11318         Dmask &= ~(1 << Comp);
11319       }
11320 
11321       // Abort if we have more than one user per component.
11322       if (Users[Lane])
11323         return Node;
11324 
11325       Users[Lane] = *I;
11326       NewDmask |= 1 << Comp;
11327     }
11328   }
11329 
11330   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11331   bool NoChannels = !NewDmask;
11332   if (NoChannels) {
11333     if (!UsesTFC) {
11334       // No uses of the result and not using TFC. Then do nothing.
11335       return Node;
11336     }
11337     // If the original dmask has one channel - then nothing to do
11338     if (OldBitsSet == 1)
11339       return Node;
11340     // Use an arbitrary dmask - required for the instruction to work
11341     NewDmask = 1;
11342   }
11343   // Abort if there's no change
11344   if (NewDmask == OldDmask)
11345     return Node;
11346 
11347   unsigned BitsSet = countPopulation(NewDmask);
11348 
11349   // Check for TFE or LWE - increase the number of channels by one to account
11350   // for the extra return value
11351   // This will need adjustment for D16 if this is also included in
11352   // adjustWriteMask (this function) but at present D16 are excluded.
11353   unsigned NewChannels = BitsSet + UsesTFC;
11354 
11355   int NewOpcode =
11356       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11357   assert(NewOpcode != -1 &&
11358          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11359          "failed to find equivalent MIMG op");
11360 
11361   // Adjust the writemask in the node
11362   SmallVector<SDValue, 12> Ops;
11363   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11364   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11365   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11366 
11367   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11368 
11369   MVT ResultVT = NewChannels == 1 ?
11370     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11371                            NewChannels == 5 ? 8 : NewChannels);
11372   SDVTList NewVTList = HasChain ?
11373     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11374 
11375 
11376   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11377                                               NewVTList, Ops);
11378 
11379   if (HasChain) {
11380     // Update chain.
11381     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11382     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11383   }
11384 
11385   if (NewChannels == 1) {
11386     assert(Node->hasNUsesOfValue(1, 0));
11387     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11388                                       SDLoc(Node), Users[Lane]->getValueType(0),
11389                                       SDValue(NewNode, 0));
11390     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11391     return nullptr;
11392   }
11393 
11394   // Update the users of the node with the new indices
11395   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11396     SDNode *User = Users[i];
11397     if (!User) {
11398       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11399       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11400       if (i || !NoChannels)
11401         continue;
11402     } else {
11403       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11404       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11405     }
11406 
11407     switch (Idx) {
11408     default: break;
11409     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11410     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11411     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11412     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11413     }
11414   }
11415 
11416   DAG.RemoveDeadNode(Node);
11417   return nullptr;
11418 }
11419 
11420 static bool isFrameIndexOp(SDValue Op) {
11421   if (Op.getOpcode() == ISD::AssertZext)
11422     Op = Op.getOperand(0);
11423 
11424   return isa<FrameIndexSDNode>(Op);
11425 }
11426 
11427 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11428 /// with frame index operands.
11429 /// LLVM assumes that inputs are to these instructions are registers.
11430 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11431                                                         SelectionDAG &DAG) const {
11432   if (Node->getOpcode() == ISD::CopyToReg) {
11433     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11434     SDValue SrcVal = Node->getOperand(2);
11435 
11436     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11437     // to try understanding copies to physical registers.
11438     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11439       SDLoc SL(Node);
11440       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11441       SDValue VReg = DAG.getRegister(
11442         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11443 
11444       SDNode *Glued = Node->getGluedNode();
11445       SDValue ToVReg
11446         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11447                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11448       SDValue ToResultReg
11449         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11450                            VReg, ToVReg.getValue(1));
11451       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11452       DAG.RemoveDeadNode(Node);
11453       return ToResultReg.getNode();
11454     }
11455   }
11456 
11457   SmallVector<SDValue, 8> Ops;
11458   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11459     if (!isFrameIndexOp(Node->getOperand(i))) {
11460       Ops.push_back(Node->getOperand(i));
11461       continue;
11462     }
11463 
11464     SDLoc DL(Node);
11465     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11466                                      Node->getOperand(i).getValueType(),
11467                                      Node->getOperand(i)), 0));
11468   }
11469 
11470   return DAG.UpdateNodeOperands(Node, Ops);
11471 }
11472 
11473 /// Fold the instructions after selecting them.
11474 /// Returns null if users were already updated.
11475 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11476                                           SelectionDAG &DAG) const {
11477   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11478   unsigned Opcode = Node->getMachineOpcode();
11479 
11480   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11481       !TII->isGather4(Opcode) &&
11482       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11483     return adjustWritemask(Node, DAG);
11484   }
11485 
11486   if (Opcode == AMDGPU::INSERT_SUBREG ||
11487       Opcode == AMDGPU::REG_SEQUENCE) {
11488     legalizeTargetIndependentNode(Node, DAG);
11489     return Node;
11490   }
11491 
11492   switch (Opcode) {
11493   case AMDGPU::V_DIV_SCALE_F32_e64:
11494   case AMDGPU::V_DIV_SCALE_F64_e64: {
11495     // Satisfy the operand register constraint when one of the inputs is
11496     // undefined. Ordinarily each undef value will have its own implicit_def of
11497     // a vreg, so force these to use a single register.
11498     SDValue Src0 = Node->getOperand(1);
11499     SDValue Src1 = Node->getOperand(3);
11500     SDValue Src2 = Node->getOperand(5);
11501 
11502     if ((Src0.isMachineOpcode() &&
11503          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11504         (Src0 == Src1 || Src0 == Src2))
11505       break;
11506 
11507     MVT VT = Src0.getValueType().getSimpleVT();
11508     const TargetRegisterClass *RC =
11509         getRegClassFor(VT, Src0.getNode()->isDivergent());
11510 
11511     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11512     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11513 
11514     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11515                                       UndefReg, Src0, SDValue());
11516 
11517     // src0 must be the same register as src1 or src2, even if the value is
11518     // undefined, so make sure we don't violate this constraint.
11519     if (Src0.isMachineOpcode() &&
11520         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11521       if (Src1.isMachineOpcode() &&
11522           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11523         Src0 = Src1;
11524       else if (Src2.isMachineOpcode() &&
11525                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11526         Src0 = Src2;
11527       else {
11528         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11529         Src0 = UndefReg;
11530         Src1 = UndefReg;
11531       }
11532     } else
11533       break;
11534 
11535     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11536     Ops[1] = Src0;
11537     Ops[3] = Src1;
11538     Ops[5] = Src2;
11539     Ops.push_back(ImpDef.getValue(1));
11540     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11541   }
11542   default:
11543     break;
11544   }
11545 
11546   return Node;
11547 }
11548 
11549 // Any MIMG instructions that use tfe or lwe require an initialization of the
11550 // result register that will be written in the case of a memory access failure.
11551 // The required code is also added to tie this init code to the result of the
11552 // img instruction.
11553 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11554   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11555   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11556   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11557   MachineBasicBlock &MBB = *MI.getParent();
11558 
11559   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11560   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11561   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11562 
11563   if (!TFE && !LWE) // intersect_ray
11564     return;
11565 
11566   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11567   unsigned LWEVal = LWE->getImm();
11568   unsigned D16Val = D16 ? D16->getImm() : 0;
11569 
11570   if (!TFEVal && !LWEVal)
11571     return;
11572 
11573   // At least one of TFE or LWE are non-zero
11574   // We have to insert a suitable initialization of the result value and
11575   // tie this to the dest of the image instruction.
11576 
11577   const DebugLoc &DL = MI.getDebugLoc();
11578 
11579   int DstIdx =
11580       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11581 
11582   // Calculate which dword we have to initialize to 0.
11583   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11584 
11585   // check that dmask operand is found.
11586   assert(MO_Dmask && "Expected dmask operand in instruction");
11587 
11588   unsigned dmask = MO_Dmask->getImm();
11589   // Determine the number of active lanes taking into account the
11590   // Gather4 special case
11591   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11592 
11593   bool Packed = !Subtarget->hasUnpackedD16VMem();
11594 
11595   unsigned InitIdx =
11596       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11597 
11598   // Abandon attempt if the dst size isn't large enough
11599   // - this is in fact an error but this is picked up elsewhere and
11600   // reported correctly.
11601   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11602   if (DstSize < InitIdx)
11603     return;
11604 
11605   // Create a register for the initialization value.
11606   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11607   unsigned NewDst = 0; // Final initialized value will be in here
11608 
11609   // If PRTStrictNull feature is enabled (the default) then initialize
11610   // all the result registers to 0, otherwise just the error indication
11611   // register (VGPRn+1)
11612   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11613   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11614 
11615   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11616   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11617     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11618     // Initialize dword
11619     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11620     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11621       .addImm(0);
11622     // Insert into the super-reg
11623     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11624       .addReg(PrevDst)
11625       .addReg(SubReg)
11626       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11627 
11628     PrevDst = NewDst;
11629   }
11630 
11631   // Add as an implicit operand
11632   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11633 
11634   // Tie the just added implicit operand to the dst
11635   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11636 }
11637 
11638 /// Assign the register class depending on the number of
11639 /// bits set in the writemask
11640 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11641                                                      SDNode *Node) const {
11642   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11643 
11644   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11645 
11646   if (TII->isVOP3(MI.getOpcode())) {
11647     // Make sure constant bus requirements are respected.
11648     TII->legalizeOperandsVOP3(MRI, MI);
11649 
11650     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11651     // This saves a chain-copy of registers and better balance register
11652     // use between vgpr and agpr as agpr tuples tend to be big.
11653     if (MI.getDesc().OpInfo) {
11654       unsigned Opc = MI.getOpcode();
11655       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11656       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11657                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11658         if (I == -1)
11659           break;
11660         MachineOperand &Op = MI.getOperand(I);
11661         if (!Op.isReg() || !Op.getReg().isVirtual())
11662           continue;
11663         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11664         if (!TRI->hasAGPRs(RC))
11665           continue;
11666         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11667         if (!Src || !Src->isCopy() ||
11668             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11669           continue;
11670         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11671         // All uses of agpr64 and agpr32 can also accept vgpr except for
11672         // v_accvgpr_read, but we do not produce agpr reads during selection,
11673         // so no use checks are needed.
11674         MRI.setRegClass(Op.getReg(), NewRC);
11675       }
11676 
11677       // Resolve the rest of AV operands to AGPRs.
11678       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11679         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11680           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11681           if (TRI->isVectorSuperClass(RC)) {
11682             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11683             MRI.setRegClass(Src2->getReg(), NewRC);
11684             if (Src2->isTied())
11685               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11686           }
11687         }
11688       }
11689     }
11690 
11691     return;
11692   }
11693 
11694   // Replace unused atomics with the no return version.
11695   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11696   if (NoRetAtomicOp != -1) {
11697     if (!Node->hasAnyUseOfValue(0)) {
11698       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11699                                                AMDGPU::OpName::cpol);
11700       if (CPolIdx != -1) {
11701         MachineOperand &CPol = MI.getOperand(CPolIdx);
11702         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11703       }
11704       MI.removeOperand(0);
11705       MI.setDesc(TII->get(NoRetAtomicOp));
11706       return;
11707     }
11708 
11709     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11710     // instruction, because the return type of these instructions is a vec2 of
11711     // the memory type, so it can be tied to the input operand.
11712     // This means these instructions always have a use, so we need to add a
11713     // special case to check if the atomic has only one extract_subreg use,
11714     // which itself has no uses.
11715     if ((Node->hasNUsesOfValue(1, 0) &&
11716          Node->use_begin()->isMachineOpcode() &&
11717          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11718          !Node->use_begin()->hasAnyUseOfValue(0))) {
11719       Register Def = MI.getOperand(0).getReg();
11720 
11721       // Change this into a noret atomic.
11722       MI.setDesc(TII->get(NoRetAtomicOp));
11723       MI.removeOperand(0);
11724 
11725       // If we only remove the def operand from the atomic instruction, the
11726       // extract_subreg will be left with a use of a vreg without a def.
11727       // So we need to insert an implicit_def to avoid machine verifier
11728       // errors.
11729       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11730               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11731     }
11732     return;
11733   }
11734 
11735   if (TII->isMIMG(MI) && !MI.mayStore())
11736     AddIMGInit(MI);
11737 }
11738 
11739 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11740                               uint64_t Val) {
11741   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11742   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11743 }
11744 
11745 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11746                                                 const SDLoc &DL,
11747                                                 SDValue Ptr) const {
11748   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11749 
11750   // Build the half of the subregister with the constants before building the
11751   // full 128-bit register. If we are building multiple resource descriptors,
11752   // this will allow CSEing of the 2-component register.
11753   const SDValue Ops0[] = {
11754     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11755     buildSMovImm32(DAG, DL, 0),
11756     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11757     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11758     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11759   };
11760 
11761   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11762                                                 MVT::v2i32, Ops0), 0);
11763 
11764   // Combine the constants and the pointer.
11765   const SDValue Ops1[] = {
11766     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11767     Ptr,
11768     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11769     SubRegHi,
11770     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11771   };
11772 
11773   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11774 }
11775 
11776 /// Return a resource descriptor with the 'Add TID' bit enabled
11777 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11778 ///        of the resource descriptor) to create an offset, which is added to
11779 ///        the resource pointer.
11780 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11781                                            SDValue Ptr, uint32_t RsrcDword1,
11782                                            uint64_t RsrcDword2And3) const {
11783   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11784   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11785   if (RsrcDword1) {
11786     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11787                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11788                     0);
11789   }
11790 
11791   SDValue DataLo = buildSMovImm32(DAG, DL,
11792                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11793   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11794 
11795   const SDValue Ops[] = {
11796     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11797     PtrLo,
11798     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11799     PtrHi,
11800     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11801     DataLo,
11802     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11803     DataHi,
11804     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11805   };
11806 
11807   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11808 }
11809 
11810 //===----------------------------------------------------------------------===//
11811 //                         SI Inline Assembly Support
11812 //===----------------------------------------------------------------------===//
11813 
11814 std::pair<unsigned, const TargetRegisterClass *>
11815 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11816                                                StringRef Constraint,
11817                                                MVT VT) const {
11818   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11819 
11820   const TargetRegisterClass *RC = nullptr;
11821   if (Constraint.size() == 1) {
11822     const unsigned BitWidth = VT.getSizeInBits();
11823     switch (Constraint[0]) {
11824     default:
11825       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11826     case 's':
11827     case 'r':
11828       switch (BitWidth) {
11829       case 16:
11830         RC = &AMDGPU::SReg_32RegClass;
11831         break;
11832       case 64:
11833         RC = &AMDGPU::SGPR_64RegClass;
11834         break;
11835       default:
11836         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11837         if (!RC)
11838           return std::make_pair(0U, nullptr);
11839         break;
11840       }
11841       break;
11842     case 'v':
11843       switch (BitWidth) {
11844       case 16:
11845         RC = &AMDGPU::VGPR_32RegClass;
11846         break;
11847       default:
11848         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11849         if (!RC)
11850           return std::make_pair(0U, nullptr);
11851         break;
11852       }
11853       break;
11854     case 'a':
11855       if (!Subtarget->hasMAIInsts())
11856         break;
11857       switch (BitWidth) {
11858       case 16:
11859         RC = &AMDGPU::AGPR_32RegClass;
11860         break;
11861       default:
11862         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11863         if (!RC)
11864           return std::make_pair(0U, nullptr);
11865         break;
11866       }
11867       break;
11868     }
11869     // We actually support i128, i16 and f16 as inline parameters
11870     // even if they are not reported as legal
11871     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11872                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11873       return std::make_pair(0U, RC);
11874   }
11875 
11876   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11877     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11878     if (RegName.consume_front("v")) {
11879       RC = &AMDGPU::VGPR_32RegClass;
11880     } else if (RegName.consume_front("s")) {
11881       RC = &AMDGPU::SGPR_32RegClass;
11882     } else if (RegName.consume_front("a")) {
11883       RC = &AMDGPU::AGPR_32RegClass;
11884     }
11885 
11886     if (RC) {
11887       uint32_t Idx;
11888       if (RegName.consume_front("[")) {
11889         uint32_t End;
11890         bool Failed = RegName.consumeInteger(10, Idx);
11891         Failed |= !RegName.consume_front(":");
11892         Failed |= RegName.consumeInteger(10, End);
11893         Failed |= !RegName.consume_back("]");
11894         if (!Failed) {
11895           uint32_t Width = (End - Idx + 1) * 32;
11896           MCRegister Reg = RC->getRegister(Idx);
11897           if (SIRegisterInfo::isVGPRClass(RC))
11898             RC = TRI->getVGPRClassForBitWidth(Width);
11899           else if (SIRegisterInfo::isSGPRClass(RC))
11900             RC = TRI->getSGPRClassForBitWidth(Width);
11901           else if (SIRegisterInfo::isAGPRClass(RC))
11902             RC = TRI->getAGPRClassForBitWidth(Width);
11903           if (RC) {
11904             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11905             return std::make_pair(Reg, RC);
11906           }
11907         }
11908       } else {
11909         bool Failed = RegName.getAsInteger(10, Idx);
11910         if (!Failed && Idx < RC->getNumRegs())
11911           return std::make_pair(RC->getRegister(Idx), RC);
11912       }
11913     }
11914   }
11915 
11916   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11917   if (Ret.first)
11918     Ret.second = TRI->getPhysRegClass(Ret.first);
11919 
11920   return Ret;
11921 }
11922 
11923 static bool isImmConstraint(StringRef Constraint) {
11924   if (Constraint.size() == 1) {
11925     switch (Constraint[0]) {
11926     default: break;
11927     case 'I':
11928     case 'J':
11929     case 'A':
11930     case 'B':
11931     case 'C':
11932       return true;
11933     }
11934   } else if (Constraint == "DA" ||
11935              Constraint == "DB") {
11936     return true;
11937   }
11938   return false;
11939 }
11940 
11941 SITargetLowering::ConstraintType
11942 SITargetLowering::getConstraintType(StringRef Constraint) const {
11943   if (Constraint.size() == 1) {
11944     switch (Constraint[0]) {
11945     default: break;
11946     case 's':
11947     case 'v':
11948     case 'a':
11949       return C_RegisterClass;
11950     }
11951   }
11952   if (isImmConstraint(Constraint)) {
11953     return C_Other;
11954   }
11955   return TargetLowering::getConstraintType(Constraint);
11956 }
11957 
11958 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11959   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11960     Val = Val & maskTrailingOnes<uint64_t>(Size);
11961   }
11962   return Val;
11963 }
11964 
11965 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11966                                                     std::string &Constraint,
11967                                                     std::vector<SDValue> &Ops,
11968                                                     SelectionDAG &DAG) const {
11969   if (isImmConstraint(Constraint)) {
11970     uint64_t Val;
11971     if (getAsmOperandConstVal(Op, Val) &&
11972         checkAsmConstraintVal(Op, Constraint, Val)) {
11973       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11974       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11975     }
11976   } else {
11977     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11978   }
11979 }
11980 
11981 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11982   unsigned Size = Op.getScalarValueSizeInBits();
11983   if (Size > 64)
11984     return false;
11985 
11986   if (Size == 16 && !Subtarget->has16BitInsts())
11987     return false;
11988 
11989   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11990     Val = C->getSExtValue();
11991     return true;
11992   }
11993   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11994     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11995     return true;
11996   }
11997   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11998     if (Size != 16 || Op.getNumOperands() != 2)
11999       return false;
12000     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12001       return false;
12002     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12003       Val = C->getSExtValue();
12004       return true;
12005     }
12006     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12007       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12008       return true;
12009     }
12010   }
12011 
12012   return false;
12013 }
12014 
12015 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12016                                              const std::string &Constraint,
12017                                              uint64_t Val) const {
12018   if (Constraint.size() == 1) {
12019     switch (Constraint[0]) {
12020     case 'I':
12021       return AMDGPU::isInlinableIntLiteral(Val);
12022     case 'J':
12023       return isInt<16>(Val);
12024     case 'A':
12025       return checkAsmConstraintValA(Op, Val);
12026     case 'B':
12027       return isInt<32>(Val);
12028     case 'C':
12029       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12030              AMDGPU::isInlinableIntLiteral(Val);
12031     default:
12032       break;
12033     }
12034   } else if (Constraint.size() == 2) {
12035     if (Constraint == "DA") {
12036       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12037       int64_t LoBits = static_cast<int32_t>(Val);
12038       return checkAsmConstraintValA(Op, HiBits, 32) &&
12039              checkAsmConstraintValA(Op, LoBits, 32);
12040     }
12041     if (Constraint == "DB") {
12042       return true;
12043     }
12044   }
12045   llvm_unreachable("Invalid asm constraint");
12046 }
12047 
12048 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12049                                               uint64_t Val,
12050                                               unsigned MaxSize) const {
12051   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12052   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12053   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12054       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12055       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12056     return true;
12057   }
12058   return false;
12059 }
12060 
12061 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12062   switch (UnalignedClassID) {
12063   case AMDGPU::VReg_64RegClassID:
12064     return AMDGPU::VReg_64_Align2RegClassID;
12065   case AMDGPU::VReg_96RegClassID:
12066     return AMDGPU::VReg_96_Align2RegClassID;
12067   case AMDGPU::VReg_128RegClassID:
12068     return AMDGPU::VReg_128_Align2RegClassID;
12069   case AMDGPU::VReg_160RegClassID:
12070     return AMDGPU::VReg_160_Align2RegClassID;
12071   case AMDGPU::VReg_192RegClassID:
12072     return AMDGPU::VReg_192_Align2RegClassID;
12073   case AMDGPU::VReg_224RegClassID:
12074     return AMDGPU::VReg_224_Align2RegClassID;
12075   case AMDGPU::VReg_256RegClassID:
12076     return AMDGPU::VReg_256_Align2RegClassID;
12077   case AMDGPU::VReg_512RegClassID:
12078     return AMDGPU::VReg_512_Align2RegClassID;
12079   case AMDGPU::VReg_1024RegClassID:
12080     return AMDGPU::VReg_1024_Align2RegClassID;
12081   case AMDGPU::AReg_64RegClassID:
12082     return AMDGPU::AReg_64_Align2RegClassID;
12083   case AMDGPU::AReg_96RegClassID:
12084     return AMDGPU::AReg_96_Align2RegClassID;
12085   case AMDGPU::AReg_128RegClassID:
12086     return AMDGPU::AReg_128_Align2RegClassID;
12087   case AMDGPU::AReg_160RegClassID:
12088     return AMDGPU::AReg_160_Align2RegClassID;
12089   case AMDGPU::AReg_192RegClassID:
12090     return AMDGPU::AReg_192_Align2RegClassID;
12091   case AMDGPU::AReg_256RegClassID:
12092     return AMDGPU::AReg_256_Align2RegClassID;
12093   case AMDGPU::AReg_512RegClassID:
12094     return AMDGPU::AReg_512_Align2RegClassID;
12095   case AMDGPU::AReg_1024RegClassID:
12096     return AMDGPU::AReg_1024_Align2RegClassID;
12097   default:
12098     return -1;
12099   }
12100 }
12101 
12102 // Figure out which registers should be reserved for stack access. Only after
12103 // the function is legalized do we know all of the non-spill stack objects or if
12104 // calls are present.
12105 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12106   MachineRegisterInfo &MRI = MF.getRegInfo();
12107   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12108   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12109   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12110   const SIInstrInfo *TII = ST.getInstrInfo();
12111 
12112   if (Info->isEntryFunction()) {
12113     // Callable functions have fixed registers used for stack access.
12114     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12115   }
12116 
12117   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12118                              Info->getStackPtrOffsetReg()));
12119   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12120     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12121 
12122   // We need to worry about replacing the default register with itself in case
12123   // of MIR testcases missing the MFI.
12124   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12125     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12126 
12127   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12128     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12129 
12130   Info->limitOccupancy(MF);
12131 
12132   if (ST.isWave32() && !MF.empty()) {
12133     for (auto &MBB : MF) {
12134       for (auto &MI : MBB) {
12135         TII->fixImplicitOperands(MI);
12136       }
12137     }
12138   }
12139 
12140   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12141   // classes if required. Ideally the register class constraints would differ
12142   // per-subtarget, but there's no easy way to achieve that right now. This is
12143   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12144   // from using them as the register class for legal types.
12145   if (ST.needsAlignedVGPRs()) {
12146     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12147       const Register Reg = Register::index2VirtReg(I);
12148       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12149       if (!RC)
12150         continue;
12151       int NewClassID = getAlignedAGPRClassID(RC->getID());
12152       if (NewClassID != -1)
12153         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12154     }
12155   }
12156 
12157   TargetLoweringBase::finalizeLowering(MF);
12158 }
12159 
12160 void SITargetLowering::computeKnownBitsForFrameIndex(
12161   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12162   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12163 
12164   // Set the high bits to zero based on the maximum allowed scratch size per
12165   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12166   // calculation won't overflow, so assume the sign bit is never set.
12167   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12168 }
12169 
12170 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12171                                    KnownBits &Known, unsigned Dim) {
12172   unsigned MaxValue =
12173       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12174   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12175 }
12176 
12177 void SITargetLowering::computeKnownBitsForTargetInstr(
12178     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12179     const MachineRegisterInfo &MRI, unsigned Depth) const {
12180   const MachineInstr *MI = MRI.getVRegDef(R);
12181   switch (MI->getOpcode()) {
12182   case AMDGPU::G_INTRINSIC: {
12183     switch (MI->getIntrinsicID()) {
12184     case Intrinsic::amdgcn_workitem_id_x:
12185       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12186       break;
12187     case Intrinsic::amdgcn_workitem_id_y:
12188       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12189       break;
12190     case Intrinsic::amdgcn_workitem_id_z:
12191       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12192       break;
12193     case Intrinsic::amdgcn_mbcnt_lo:
12194     case Intrinsic::amdgcn_mbcnt_hi: {
12195       // These return at most the wavefront size - 1.
12196       unsigned Size = MRI.getType(R).getSizeInBits();
12197       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12198       break;
12199     }
12200     case Intrinsic::amdgcn_groupstaticsize: {
12201       // We can report everything over the maximum size as 0. We can't report
12202       // based on the actual size because we don't know if it's accurate or not
12203       // at any given point.
12204       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12205       break;
12206     }
12207     }
12208     break;
12209   }
12210   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12211     Known.Zero.setHighBits(24);
12212     break;
12213   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12214     Known.Zero.setHighBits(16);
12215     break;
12216   }
12217 }
12218 
12219 Align SITargetLowering::computeKnownAlignForTargetInstr(
12220   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12221   unsigned Depth) const {
12222   const MachineInstr *MI = MRI.getVRegDef(R);
12223   switch (MI->getOpcode()) {
12224   case AMDGPU::G_INTRINSIC:
12225   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12226     // FIXME: Can this move to generic code? What about the case where the call
12227     // site specifies a lower alignment?
12228     Intrinsic::ID IID = MI->getIntrinsicID();
12229     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12230     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12231     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12232       return *RetAlign;
12233     return Align(1);
12234   }
12235   default:
12236     return Align(1);
12237   }
12238 }
12239 
12240 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12241   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12242   const Align CacheLineAlign = Align(64);
12243 
12244   // Pre-GFX10 target did not benefit from loop alignment
12245   if (!ML || DisableLoopAlignment ||
12246       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12247       getSubtarget()->hasInstFwdPrefetchBug())
12248     return PrefAlign;
12249 
12250   // On GFX10 I$ is 4 x 64 bytes cache lines.
12251   // By default prefetcher keeps one cache line behind and reads two ahead.
12252   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12253   // behind and one ahead.
12254   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12255   // If loop fits 64 bytes it always spans no more than two cache lines and
12256   // does not need an alignment.
12257   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12258   // Else if loop is less or equal 192 bytes we need two lines behind.
12259 
12260   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12261   const MachineBasicBlock *Header = ML->getHeader();
12262   if (Header->getAlignment() != PrefAlign)
12263     return Header->getAlignment(); // Already processed.
12264 
12265   unsigned LoopSize = 0;
12266   for (const MachineBasicBlock *MBB : ML->blocks()) {
12267     // If inner loop block is aligned assume in average half of the alignment
12268     // size to be added as nops.
12269     if (MBB != Header)
12270       LoopSize += MBB->getAlignment().value() / 2;
12271 
12272     for (const MachineInstr &MI : *MBB) {
12273       LoopSize += TII->getInstSizeInBytes(MI);
12274       if (LoopSize > 192)
12275         return PrefAlign;
12276     }
12277   }
12278 
12279   if (LoopSize <= 64)
12280     return PrefAlign;
12281 
12282   if (LoopSize <= 128)
12283     return CacheLineAlign;
12284 
12285   // If any of parent loops is surrounded by prefetch instructions do not
12286   // insert new for inner loop, which would reset parent's settings.
12287   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12288     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12289       auto I = Exit->getFirstNonDebugInstr();
12290       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12291         return CacheLineAlign;
12292     }
12293   }
12294 
12295   MachineBasicBlock *Pre = ML->getLoopPreheader();
12296   MachineBasicBlock *Exit = ML->getExitBlock();
12297 
12298   if (Pre && Exit) {
12299     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12300             TII->get(AMDGPU::S_INST_PREFETCH))
12301       .addImm(1); // prefetch 2 lines behind PC
12302 
12303     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12304             TII->get(AMDGPU::S_INST_PREFETCH))
12305       .addImm(2); // prefetch 1 line behind PC
12306   }
12307 
12308   return CacheLineAlign;
12309 }
12310 
12311 LLVM_ATTRIBUTE_UNUSED
12312 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12313   assert(N->getOpcode() == ISD::CopyFromReg);
12314   do {
12315     // Follow the chain until we find an INLINEASM node.
12316     N = N->getOperand(0).getNode();
12317     if (N->getOpcode() == ISD::INLINEASM ||
12318         N->getOpcode() == ISD::INLINEASM_BR)
12319       return true;
12320   } while (N->getOpcode() == ISD::CopyFromReg);
12321   return false;
12322 }
12323 
12324 bool SITargetLowering::isSDNodeSourceOfDivergence(
12325     const SDNode *N, FunctionLoweringInfo *FLI,
12326     LegacyDivergenceAnalysis *KDA) const {
12327   switch (N->getOpcode()) {
12328   case ISD::CopyFromReg: {
12329     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12330     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12331     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12332     Register Reg = R->getReg();
12333 
12334     // FIXME: Why does this need to consider isLiveIn?
12335     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12336       return !TRI->isSGPRReg(MRI, Reg);
12337 
12338     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12339       return KDA->isDivergent(V);
12340 
12341     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12342     return !TRI->isSGPRReg(MRI, Reg);
12343   }
12344   case ISD::LOAD: {
12345     const LoadSDNode *L = cast<LoadSDNode>(N);
12346     unsigned AS = L->getAddressSpace();
12347     // A flat load may access private memory.
12348     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12349   }
12350   case ISD::CALLSEQ_END:
12351     return true;
12352   case ISD::INTRINSIC_WO_CHAIN:
12353     return AMDGPU::isIntrinsicSourceOfDivergence(
12354         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12355   case ISD::INTRINSIC_W_CHAIN:
12356     return AMDGPU::isIntrinsicSourceOfDivergence(
12357         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12358   case AMDGPUISD::ATOMIC_CMP_SWAP:
12359   case AMDGPUISD::ATOMIC_INC:
12360   case AMDGPUISD::ATOMIC_DEC:
12361   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12362   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12363   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12364   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12365   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12366   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12367   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12368   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12369   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12370   case AMDGPUISD::BUFFER_ATOMIC_AND:
12371   case AMDGPUISD::BUFFER_ATOMIC_OR:
12372   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12373   case AMDGPUISD::BUFFER_ATOMIC_INC:
12374   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12375   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12376   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12377   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12378   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12379   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12380     // Target-specific read-modify-write atomics are sources of divergence.
12381     return true;
12382   default:
12383     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12384       // Generic read-modify-write atomics are sources of divergence.
12385       return A->readMem() && A->writeMem();
12386     }
12387     return false;
12388   }
12389 }
12390 
12391 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12392                                                EVT VT) const {
12393   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12394   case MVT::f32:
12395     return hasFP32Denormals(DAG.getMachineFunction());
12396   case MVT::f64:
12397   case MVT::f16:
12398     return hasFP64FP16Denormals(DAG.getMachineFunction());
12399   default:
12400     return false;
12401   }
12402 }
12403 
12404 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12405                                                MachineFunction &MF) const {
12406   switch (Ty.getScalarSizeInBits()) {
12407   case 32:
12408     return hasFP32Denormals(MF);
12409   case 64:
12410   case 16:
12411     return hasFP64FP16Denormals(MF);
12412   default:
12413     return false;
12414   }
12415 }
12416 
12417 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12418                                                     const SelectionDAG &DAG,
12419                                                     bool SNaN,
12420                                                     unsigned Depth) const {
12421   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12422     const MachineFunction &MF = DAG.getMachineFunction();
12423     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12424 
12425     if (Info->getMode().DX10Clamp)
12426       return true; // Clamped to 0.
12427     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12428   }
12429 
12430   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12431                                                             SNaN, Depth);
12432 }
12433 
12434 // Global FP atomic instructions have a hardcoded FP mode and do not support
12435 // FP32 denormals, and only support v2f16 denormals.
12436 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12437   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12438   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12439   if (&Flt == &APFloat::IEEEsingle())
12440     return DenormMode == DenormalMode::getPreserveSign();
12441   return DenormMode == DenormalMode::getIEEE();
12442 }
12443 
12444 TargetLowering::AtomicExpansionKind
12445 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12446   unsigned AS = RMW->getPointerAddressSpace();
12447   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12448     return AtomicExpansionKind::NotAtomic;
12449 
12450   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12451     OptimizationRemarkEmitter ORE(RMW->getFunction());
12452     LLVMContext &Ctx = RMW->getFunction()->getContext();
12453     SmallVector<StringRef> SSNs;
12454     Ctx.getSyncScopeNames(SSNs);
12455     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12456                         ? "system"
12457                         : SSNs[RMW->getSyncScopeID()];
12458     ORE.emit([&]() {
12459       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12460              << "Hardware instruction generated for atomic "
12461              << RMW->getOperationName(RMW->getOperation())
12462              << " operation at memory scope " << MemScope
12463              << " due to an unsafe request.";
12464     });
12465     return Kind;
12466   };
12467 
12468   switch (RMW->getOperation()) {
12469   case AtomicRMWInst::FAdd: {
12470     Type *Ty = RMW->getType();
12471 
12472     // We don't have a way to support 16-bit atomics now, so just leave them
12473     // as-is.
12474     if (Ty->isHalfTy())
12475       return AtomicExpansionKind::None;
12476 
12477     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12478       return AtomicExpansionKind::CmpXChg;
12479 
12480     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12481          Subtarget->hasAtomicFaddInsts()) {
12482       if (Subtarget->hasGFX940Insts())
12483         return AtomicExpansionKind::None;
12484 
12485       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12486       // floating point atomic instructions. May generate more efficient code,
12487       // but may not respect rounding and denormal modes, and may give incorrect
12488       // results for certain memory destinations.
12489       if (RMW->getFunction()
12490               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12491               .getValueAsString() != "true")
12492         return AtomicExpansionKind::CmpXChg;
12493 
12494       if (Subtarget->hasGFX90AInsts()) {
12495         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12496           return AtomicExpansionKind::CmpXChg;
12497 
12498         auto SSID = RMW->getSyncScopeID();
12499         if (SSID == SyncScope::System ||
12500             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12501           return AtomicExpansionKind::CmpXChg;
12502 
12503         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12504       }
12505 
12506       if (AS == AMDGPUAS::FLAT_ADDRESS)
12507         return AtomicExpansionKind::CmpXChg;
12508 
12509       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12510                               : AtomicExpansionKind::CmpXChg;
12511     }
12512 
12513     // DS FP atomics do respect the denormal mode, but the rounding mode is
12514     // fixed to round-to-nearest-even.
12515     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12516     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12517       if (!Ty->isDoubleTy())
12518         return AtomicExpansionKind::None;
12519 
12520       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12521         return AtomicExpansionKind::None;
12522 
12523       return RMW->getFunction()
12524                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12525                          .getValueAsString() == "true"
12526                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12527                  : AtomicExpansionKind::CmpXChg;
12528     }
12529 
12530     return AtomicExpansionKind::CmpXChg;
12531   }
12532   default:
12533     break;
12534   }
12535 
12536   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12537 }
12538 
12539 TargetLowering::AtomicExpansionKind
12540 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12541   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12542              ? AtomicExpansionKind::NotAtomic
12543              : AtomicExpansionKind::None;
12544 }
12545 
12546 TargetLowering::AtomicExpansionKind
12547 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12548   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12549              ? AtomicExpansionKind::NotAtomic
12550              : AtomicExpansionKind::None;
12551 }
12552 
12553 TargetLowering::AtomicExpansionKind
12554 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12555   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12556              ? AtomicExpansionKind::NotAtomic
12557              : AtomicExpansionKind::None;
12558 }
12559 
12560 const TargetRegisterClass *
12561 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12562   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12563   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12564   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12565     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12566                                                : &AMDGPU::SReg_32RegClass;
12567   if (!TRI->isSGPRClass(RC) && !isDivergent)
12568     return TRI->getEquivalentSGPRClass(RC);
12569   else if (TRI->isSGPRClass(RC) && isDivergent)
12570     return TRI->getEquivalentVGPRClass(RC);
12571 
12572   return RC;
12573 }
12574 
12575 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12576 // uniform values (as produced by the mask results of control flow intrinsics)
12577 // used outside of divergent blocks. The phi users need to also be treated as
12578 // always uniform.
12579 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12580                       unsigned WaveSize) {
12581   // FIXME: We assume we never cast the mask results of a control flow
12582   // intrinsic.
12583   // Early exit if the type won't be consistent as a compile time hack.
12584   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12585   if (!IT || IT->getBitWidth() != WaveSize)
12586     return false;
12587 
12588   if (!isa<Instruction>(V))
12589     return false;
12590   if (!Visited.insert(V).second)
12591     return false;
12592   bool Result = false;
12593   for (auto U : V->users()) {
12594     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12595       if (V == U->getOperand(1)) {
12596         switch (Intrinsic->getIntrinsicID()) {
12597         default:
12598           Result = false;
12599           break;
12600         case Intrinsic::amdgcn_if_break:
12601         case Intrinsic::amdgcn_if:
12602         case Intrinsic::amdgcn_else:
12603           Result = true;
12604           break;
12605         }
12606       }
12607       if (V == U->getOperand(0)) {
12608         switch (Intrinsic->getIntrinsicID()) {
12609         default:
12610           Result = false;
12611           break;
12612         case Intrinsic::amdgcn_end_cf:
12613         case Intrinsic::amdgcn_loop:
12614           Result = true;
12615           break;
12616         }
12617       }
12618     } else {
12619       Result = hasCFUser(U, Visited, WaveSize);
12620     }
12621     if (Result)
12622       break;
12623   }
12624   return Result;
12625 }
12626 
12627 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12628                                                const Value *V) const {
12629   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12630     if (CI->isInlineAsm()) {
12631       // FIXME: This cannot give a correct answer. This should only trigger in
12632       // the case where inline asm returns mixed SGPR and VGPR results, used
12633       // outside the defining block. We don't have a specific result to
12634       // consider, so this assumes if any value is SGPR, the overall register
12635       // also needs to be SGPR.
12636       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12637       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12638           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12639       for (auto &TC : TargetConstraints) {
12640         if (TC.Type == InlineAsm::isOutput) {
12641           ComputeConstraintToUse(TC, SDValue());
12642           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12643               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12644           if (RC && SIRI->isSGPRClass(RC))
12645             return true;
12646         }
12647       }
12648     }
12649   }
12650   SmallPtrSet<const Value *, 16> Visited;
12651   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12652 }
12653 
12654 std::pair<InstructionCost, MVT>
12655 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12656                                           Type *Ty) const {
12657   std::pair<InstructionCost, MVT> Cost =
12658       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12659   auto Size = DL.getTypeSizeInBits(Ty);
12660   // Maximum load or store can handle 8 dwords for scalar and 4 for
12661   // vector ALU. Let's assume anything above 8 dwords is expensive
12662   // even if legal.
12663   if (Size <= 256)
12664     return Cost;
12665 
12666   Cost.first += (Size + 255) / 256;
12667   return Cost;
12668 }
12669 
12670 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12671   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12672   for (; I != E; ++I) {
12673     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12674       if (getBasePtrIndex(M) == I.getOperandNo())
12675         return true;
12676     }
12677   }
12678   return false;
12679 }
12680 
12681 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12682                                            SDValue N1) const {
12683   if (!N0.hasOneUse())
12684     return false;
12685   // Take care of the opportunity to keep N0 uniform
12686   if (N0->isDivergent() || !N1->isDivergent())
12687     return true;
12688   // Check if we have a good chance to form the memory access pattern with the
12689   // base and offset
12690   return (DAG.isBaseWithConstantOffset(N0) &&
12691           hasMemSDNodeUser(*N0->use_begin()));
12692 }
12693 
12694 MachineMemOperand::Flags
12695 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12696   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12697   if (I.getMetadata("amdgpu.noclobber"))
12698     return MONoClobber;
12699   return MachineMemOperand::MONone;
12700 }
12701