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     // Check if alignment requirements for ds_read/write instructions are
1520     // disabled.
1521     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1522       return false;
1523 
1524     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1525     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1526         Alignment < RequiredAlignment)
1527       return false;
1528 
1529     // Either, the alignment requirements are "enabled", or there is an
1530     // unaligned LDS access related hardware bug though alignment requirements
1531     // are "disabled". In either case, we need to check for proper alignment
1532     // requirements.
1533     //
1534     switch (Size) {
1535     case 64:
1536       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1537       // address is negative, then the instruction is incorrectly treated as
1538       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1539       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1540       // load later in the SILoadStoreOptimizer.
1541       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1542         return false;
1543 
1544       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1545       // can do a 4 byte aligned, 8 byte access in a single operation using
1546       // ds_read2/write2_b32 with adjacent offsets.
1547       RequiredAlignment = Align(4);
1548       break;
1549     case 96:
1550       if (!Subtarget->hasDS96AndDS128())
1551         return false;
1552 
1553       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1554       // gfx8 and older.
1555       RequiredAlignment = Align(16);
1556 
1557       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1558         // Naturally aligned access is fastest. However, also report it is Fast
1559         // if memory is aligned less than DWORD. A narrow load or store will be
1560         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1561         // be more of them, so overall we will pay less penalty issuing a single
1562         // instruction.
1563         if (IsFast)
1564           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1565         return true;
1566       }
1567 
1568       break;
1569     case 128:
1570       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1571         return false;
1572 
1573       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1574       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1575       // single operation using ds_read2/write2_b64.
1576       RequiredAlignment = Align(8);
1577 
1578       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1579         // Naturally aligned access is fastest. However, also report it is Fast
1580         // if memory is aligned less than DWORD. A narrow load or store will be
1581         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1582         // will be more of them, so overall we will pay less penalty issuing a
1583         // single instruction.
1584         if (IsFast)
1585           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1586         return true;
1587       }
1588 
1589       break;
1590     default:
1591       if (Size > 32)
1592         return false;
1593 
1594       break;
1595     }
1596 
1597     if (IsFast) {
1598       // FIXME: Lie it is fast if +unaligned-access-mode is passed so that
1599       // DS accesses get vectorized. Do this only for sizes below 96 as
1600       // b96 and b128 cases already properly handled.
1601       // Remove Subtarget check once all sizes properly handled.
1602       *IsFast = Alignment >= RequiredAlignment ||
1603                 (Subtarget->hasUnalignedDSAccessEnabled() && Size < 96);
1604     }
1605 
1606     return Alignment >= RequiredAlignment ||
1607            Subtarget->hasUnalignedDSAccessEnabled();
1608   }
1609 
1610   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1611     bool AlignedBy4 = Alignment >= Align(4);
1612     if (IsFast)
1613       *IsFast = AlignedBy4;
1614 
1615     return AlignedBy4 ||
1616            Subtarget->enableFlatScratch() ||
1617            Subtarget->hasUnalignedScratchAccess();
1618   }
1619 
1620   // FIXME: We have to be conservative here and assume that flat operations
1621   // will access scratch.  If we had access to the IR function, then we
1622   // could determine if any private memory was used in the function.
1623   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1624       !Subtarget->hasUnalignedScratchAccess()) {
1625     bool AlignedBy4 = Alignment >= Align(4);
1626     if (IsFast)
1627       *IsFast = AlignedBy4;
1628 
1629     return AlignedBy4;
1630   }
1631 
1632   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1633     // If we have a uniform constant load, it still requires using a slow
1634     // buffer instruction if unaligned.
1635     if (IsFast) {
1636       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1637       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1638       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1639                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1640         Alignment >= Align(4) : Alignment != Align(2);
1641     }
1642 
1643     return true;
1644   }
1645 
1646   // Smaller than dword value must be aligned.
1647   if (Size < 32)
1648     return false;
1649 
1650   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1651   // byte-address are ignored, thus forcing Dword alignment.
1652   // This applies to private, global, and constant memory.
1653   if (IsFast)
1654     *IsFast = true;
1655 
1656   return Size >= 32 && Alignment >= Align(4);
1657 }
1658 
1659 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1660     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1661     bool *IsFast) const {
1662   if (IsFast)
1663     *IsFast = false;
1664 
1665   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1666   // which isn't a simple VT.
1667   // Until MVT is extended to handle this, simply check for the size and
1668   // rely on the condition below: allow accesses if the size is a multiple of 4.
1669   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1670                            VT.getStoreSize() > 16)) {
1671     return false;
1672   }
1673 
1674   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1675                                                   Alignment, Flags, IsFast);
1676 
1677   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1678       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1679        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1680     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1681     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1682     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1683     // which would be equally misaligned.
1684     // This is only used by the common passes, selection always calls the
1685     // allowsMisalignedMemoryAccessesImpl version.
1686     *IsFast = true;
1687   }
1688 
1689   return Allow;
1690 }
1691 
1692 EVT SITargetLowering::getOptimalMemOpType(
1693     const MemOp &Op, const AttributeList &FuncAttributes) const {
1694   // FIXME: Should account for address space here.
1695 
1696   // The default fallback uses the private pointer size as a guess for a type to
1697   // use. Make sure we switch these to 64-bit accesses.
1698 
1699   if (Op.size() >= 16 &&
1700       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1701     return MVT::v4i32;
1702 
1703   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1704     return MVT::v2i32;
1705 
1706   // Use the default.
1707   return MVT::Other;
1708 }
1709 
1710 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1711   const MemSDNode *MemNode = cast<MemSDNode>(N);
1712   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1713 }
1714 
1715 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1716   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1717          AS == AMDGPUAS::PRIVATE_ADDRESS;
1718 }
1719 
1720 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1721                                            unsigned DestAS) const {
1722   // Flat -> private/local is a simple truncate.
1723   // Flat -> global is no-op
1724   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1725     return true;
1726 
1727   const GCNTargetMachine &TM =
1728       static_cast<const GCNTargetMachine &>(getTargetMachine());
1729   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1730 }
1731 
1732 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1733   const MemSDNode *MemNode = cast<MemSDNode>(N);
1734 
1735   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1736 }
1737 
1738 TargetLoweringBase::LegalizeTypeAction
1739 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1740   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1741       VT.getScalarType().bitsLE(MVT::i16))
1742     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1743   return TargetLoweringBase::getPreferredVectorAction(VT);
1744 }
1745 
1746 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1747                                                          Type *Ty) const {
1748   // FIXME: Could be smarter if called for vector constants.
1749   return true;
1750 }
1751 
1752 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1753   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1754     switch (Op) {
1755     case ISD::LOAD:
1756     case ISD::STORE:
1757 
1758     // These operations are done with 32-bit instructions anyway.
1759     case ISD::AND:
1760     case ISD::OR:
1761     case ISD::XOR:
1762     case ISD::SELECT:
1763       // TODO: Extensions?
1764       return true;
1765     default:
1766       return false;
1767     }
1768   }
1769 
1770   // SimplifySetCC uses this function to determine whether or not it should
1771   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1772   if (VT == MVT::i1 && Op == ISD::SETCC)
1773     return false;
1774 
1775   return TargetLowering::isTypeDesirableForOp(Op, VT);
1776 }
1777 
1778 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1779                                                    const SDLoc &SL,
1780                                                    SDValue Chain,
1781                                                    uint64_t Offset) const {
1782   const DataLayout &DL = DAG.getDataLayout();
1783   MachineFunction &MF = DAG.getMachineFunction();
1784   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1785 
1786   const ArgDescriptor *InputPtrReg;
1787   const TargetRegisterClass *RC;
1788   LLT ArgTy;
1789   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1790 
1791   std::tie(InputPtrReg, RC, ArgTy) =
1792       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1793 
1794   // We may not have the kernarg segment argument if we have no kernel
1795   // arguments.
1796   if (!InputPtrReg)
1797     return DAG.getConstant(0, SL, PtrVT);
1798 
1799   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1800   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1801     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1802 
1803   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1804 }
1805 
1806 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1807                                             const SDLoc &SL) const {
1808   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1809                                                FIRST_IMPLICIT);
1810   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1811 }
1812 
1813 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1814                                          const SDLoc &SL, SDValue Val,
1815                                          bool Signed,
1816                                          const ISD::InputArg *Arg) const {
1817   // First, if it is a widened vector, narrow it.
1818   if (VT.isVector() &&
1819       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1820     EVT NarrowedVT =
1821         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1822                          VT.getVectorNumElements());
1823     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1824                       DAG.getConstant(0, SL, MVT::i32));
1825   }
1826 
1827   // Then convert the vector elements or scalar value.
1828   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1829       VT.bitsLT(MemVT)) {
1830     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1831     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1832   }
1833 
1834   if (MemVT.isFloatingPoint())
1835     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1836   else if (Signed)
1837     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1838   else
1839     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1840 
1841   return Val;
1842 }
1843 
1844 SDValue SITargetLowering::lowerKernargMemParameter(
1845     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1846     uint64_t Offset, Align Alignment, bool Signed,
1847     const ISD::InputArg *Arg) const {
1848   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1849 
1850   // Try to avoid using an extload by loading earlier than the argument address,
1851   // and extracting the relevant bits. The load should hopefully be merged with
1852   // the previous argument.
1853   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1854     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1855     int64_t AlignDownOffset = alignDown(Offset, 4);
1856     int64_t OffsetDiff = Offset - AlignDownOffset;
1857 
1858     EVT IntVT = MemVT.changeTypeToInteger();
1859 
1860     // TODO: If we passed in the base kernel offset we could have a better
1861     // alignment than 4, but we don't really need it.
1862     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1863     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1864                                MachineMemOperand::MODereferenceable |
1865                                    MachineMemOperand::MOInvariant);
1866 
1867     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1868     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1869 
1870     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1871     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1872     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1873 
1874 
1875     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1876   }
1877 
1878   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1879   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1880                              MachineMemOperand::MODereferenceable |
1881                                  MachineMemOperand::MOInvariant);
1882 
1883   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1884   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1885 }
1886 
1887 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1888                                               const SDLoc &SL, SDValue Chain,
1889                                               const ISD::InputArg &Arg) const {
1890   MachineFunction &MF = DAG.getMachineFunction();
1891   MachineFrameInfo &MFI = MF.getFrameInfo();
1892 
1893   if (Arg.Flags.isByVal()) {
1894     unsigned Size = Arg.Flags.getByValSize();
1895     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1896     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1897   }
1898 
1899   unsigned ArgOffset = VA.getLocMemOffset();
1900   unsigned ArgSize = VA.getValVT().getStoreSize();
1901 
1902   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1903 
1904   // Create load nodes to retrieve arguments from the stack.
1905   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1906   SDValue ArgValue;
1907 
1908   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1909   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1910   MVT MemVT = VA.getValVT();
1911 
1912   switch (VA.getLocInfo()) {
1913   default:
1914     break;
1915   case CCValAssign::BCvt:
1916     MemVT = VA.getLocVT();
1917     break;
1918   case CCValAssign::SExt:
1919     ExtType = ISD::SEXTLOAD;
1920     break;
1921   case CCValAssign::ZExt:
1922     ExtType = ISD::ZEXTLOAD;
1923     break;
1924   case CCValAssign::AExt:
1925     ExtType = ISD::EXTLOAD;
1926     break;
1927   }
1928 
1929   ArgValue = DAG.getExtLoad(
1930     ExtType, SL, VA.getLocVT(), Chain, FIN,
1931     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1932     MemVT);
1933   return ArgValue;
1934 }
1935 
1936 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1937   const SIMachineFunctionInfo &MFI,
1938   EVT VT,
1939   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1940   const ArgDescriptor *Reg;
1941   const TargetRegisterClass *RC;
1942   LLT Ty;
1943 
1944   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1945   if (!Reg) {
1946     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1947       // It's possible for a kernarg intrinsic call to appear in a kernel with
1948       // no allocated segment, in which case we do not add the user sgpr
1949       // argument, so just return null.
1950       return DAG.getConstant(0, SDLoc(), VT);
1951     }
1952 
1953     // It's undefined behavior if a function marked with the amdgpu-no-*
1954     // attributes uses the corresponding intrinsic.
1955     return DAG.getUNDEF(VT);
1956   }
1957 
1958   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1959 }
1960 
1961 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1962                                CallingConv::ID CallConv,
1963                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1964                                FunctionType *FType,
1965                                SIMachineFunctionInfo *Info) {
1966   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1967     const ISD::InputArg *Arg = &Ins[I];
1968 
1969     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1970            "vector type argument should have been split");
1971 
1972     // First check if it's a PS input addr.
1973     if (CallConv == CallingConv::AMDGPU_PS &&
1974         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1975       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1976 
1977       // Inconveniently only the first part of the split is marked as isSplit,
1978       // so skip to the end. We only want to increment PSInputNum once for the
1979       // entire split argument.
1980       if (Arg->Flags.isSplit()) {
1981         while (!Arg->Flags.isSplitEnd()) {
1982           assert((!Arg->VT.isVector() ||
1983                   Arg->VT.getScalarSizeInBits() == 16) &&
1984                  "unexpected vector split in ps argument type");
1985           if (!SkipArg)
1986             Splits.push_back(*Arg);
1987           Arg = &Ins[++I];
1988         }
1989       }
1990 
1991       if (SkipArg) {
1992         // We can safely skip PS inputs.
1993         Skipped.set(Arg->getOrigArgIndex());
1994         ++PSInputNum;
1995         continue;
1996       }
1997 
1998       Info->markPSInputAllocated(PSInputNum);
1999       if (Arg->Used)
2000         Info->markPSInputEnabled(PSInputNum);
2001 
2002       ++PSInputNum;
2003     }
2004 
2005     Splits.push_back(*Arg);
2006   }
2007 }
2008 
2009 // Allocate special inputs passed in VGPRs.
2010 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
2011                                                       MachineFunction &MF,
2012                                                       const SIRegisterInfo &TRI,
2013                                                       SIMachineFunctionInfo &Info) const {
2014   const LLT S32 = LLT::scalar(32);
2015   MachineRegisterInfo &MRI = MF.getRegInfo();
2016 
2017   if (Info.hasWorkItemIDX()) {
2018     Register Reg = AMDGPU::VGPR0;
2019     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2020 
2021     CCInfo.AllocateReg(Reg);
2022     unsigned Mask = (Subtarget->hasPackedTID() &&
2023                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2024     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2025   }
2026 
2027   if (Info.hasWorkItemIDY()) {
2028     assert(Info.hasWorkItemIDX());
2029     if (Subtarget->hasPackedTID()) {
2030       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2031                                                         0x3ff << 10));
2032     } else {
2033       unsigned Reg = AMDGPU::VGPR1;
2034       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2035 
2036       CCInfo.AllocateReg(Reg);
2037       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2038     }
2039   }
2040 
2041   if (Info.hasWorkItemIDZ()) {
2042     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2043     if (Subtarget->hasPackedTID()) {
2044       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2045                                                         0x3ff << 20));
2046     } else {
2047       unsigned Reg = AMDGPU::VGPR2;
2048       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2049 
2050       CCInfo.AllocateReg(Reg);
2051       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2052     }
2053   }
2054 }
2055 
2056 // Try to allocate a VGPR at the end of the argument list, or if no argument
2057 // VGPRs are left allocating a stack slot.
2058 // If \p Mask is is given it indicates bitfield position in the register.
2059 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2060 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2061                                          ArgDescriptor Arg = ArgDescriptor()) {
2062   if (Arg.isSet())
2063     return ArgDescriptor::createArg(Arg, Mask);
2064 
2065   ArrayRef<MCPhysReg> ArgVGPRs
2066     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2067   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2068   if (RegIdx == ArgVGPRs.size()) {
2069     // Spill to stack required.
2070     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2071 
2072     return ArgDescriptor::createStack(Offset, Mask);
2073   }
2074 
2075   unsigned Reg = ArgVGPRs[RegIdx];
2076   Reg = CCInfo.AllocateReg(Reg);
2077   assert(Reg != AMDGPU::NoRegister);
2078 
2079   MachineFunction &MF = CCInfo.getMachineFunction();
2080   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2081   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2082   return ArgDescriptor::createRegister(Reg, Mask);
2083 }
2084 
2085 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2086                                              const TargetRegisterClass *RC,
2087                                              unsigned NumArgRegs) {
2088   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2089   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2090   if (RegIdx == ArgSGPRs.size())
2091     report_fatal_error("ran out of SGPRs for arguments");
2092 
2093   unsigned Reg = ArgSGPRs[RegIdx];
2094   Reg = CCInfo.AllocateReg(Reg);
2095   assert(Reg != AMDGPU::NoRegister);
2096 
2097   MachineFunction &MF = CCInfo.getMachineFunction();
2098   MF.addLiveIn(Reg, RC);
2099   return ArgDescriptor::createRegister(Reg);
2100 }
2101 
2102 // If this has a fixed position, we still should allocate the register in the
2103 // CCInfo state. Technically we could get away with this for values passed
2104 // outside of the normal argument range.
2105 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2106                                        const TargetRegisterClass *RC,
2107                                        MCRegister Reg) {
2108   Reg = CCInfo.AllocateReg(Reg);
2109   assert(Reg != AMDGPU::NoRegister);
2110   MachineFunction &MF = CCInfo.getMachineFunction();
2111   MF.addLiveIn(Reg, RC);
2112 }
2113 
2114 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2115   if (Arg) {
2116     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2117                                Arg.getRegister());
2118   } else
2119     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2120 }
2121 
2122 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2123   if (Arg) {
2124     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2125                                Arg.getRegister());
2126   } else
2127     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2128 }
2129 
2130 /// Allocate implicit function VGPR arguments at the end of allocated user
2131 /// arguments.
2132 void SITargetLowering::allocateSpecialInputVGPRs(
2133   CCState &CCInfo, MachineFunction &MF,
2134   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2135   const unsigned Mask = 0x3ff;
2136   ArgDescriptor Arg;
2137 
2138   if (Info.hasWorkItemIDX()) {
2139     Arg = allocateVGPR32Input(CCInfo, Mask);
2140     Info.setWorkItemIDX(Arg);
2141   }
2142 
2143   if (Info.hasWorkItemIDY()) {
2144     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2145     Info.setWorkItemIDY(Arg);
2146   }
2147 
2148   if (Info.hasWorkItemIDZ())
2149     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2150 }
2151 
2152 /// Allocate implicit function VGPR arguments in fixed registers.
2153 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2154   CCState &CCInfo, MachineFunction &MF,
2155   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2156   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2157   if (!Reg)
2158     report_fatal_error("failed to allocated VGPR for implicit arguments");
2159 
2160   const unsigned Mask = 0x3ff;
2161   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2162   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2163   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2164 }
2165 
2166 void SITargetLowering::allocateSpecialInputSGPRs(
2167   CCState &CCInfo,
2168   MachineFunction &MF,
2169   const SIRegisterInfo &TRI,
2170   SIMachineFunctionInfo &Info) const {
2171   auto &ArgInfo = Info.getArgInfo();
2172 
2173   // TODO: Unify handling with private memory pointers.
2174   if (Info.hasDispatchPtr())
2175     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2176 
2177   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2178     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2179 
2180   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2181   // constant offset from the kernarg segment.
2182   if (Info.hasImplicitArgPtr())
2183     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2184 
2185   if (Info.hasDispatchID())
2186     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2187 
2188   // flat_scratch_init is not applicable for non-kernel functions.
2189 
2190   if (Info.hasWorkGroupIDX())
2191     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2192 
2193   if (Info.hasWorkGroupIDY())
2194     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2195 
2196   if (Info.hasWorkGroupIDZ())
2197     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2198 }
2199 
2200 // Allocate special inputs passed in user SGPRs.
2201 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2202                                             MachineFunction &MF,
2203                                             const SIRegisterInfo &TRI,
2204                                             SIMachineFunctionInfo &Info) const {
2205   if (Info.hasImplicitBufferPtr()) {
2206     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2207     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2208     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2209   }
2210 
2211   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2212   if (Info.hasPrivateSegmentBuffer()) {
2213     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2214     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2215     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2216   }
2217 
2218   if (Info.hasDispatchPtr()) {
2219     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2220     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2221     CCInfo.AllocateReg(DispatchPtrReg);
2222   }
2223 
2224   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2225     Register QueuePtrReg = Info.addQueuePtr(TRI);
2226     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2227     CCInfo.AllocateReg(QueuePtrReg);
2228   }
2229 
2230   if (Info.hasKernargSegmentPtr()) {
2231     MachineRegisterInfo &MRI = MF.getRegInfo();
2232     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2233     CCInfo.AllocateReg(InputPtrReg);
2234 
2235     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2236     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2237   }
2238 
2239   if (Info.hasDispatchID()) {
2240     Register DispatchIDReg = Info.addDispatchID(TRI);
2241     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2242     CCInfo.AllocateReg(DispatchIDReg);
2243   }
2244 
2245   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2246     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2247     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2248     CCInfo.AllocateReg(FlatScratchInitReg);
2249   }
2250 
2251   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2252   // these from the dispatch pointer.
2253 }
2254 
2255 // Allocate special input registers that are initialized per-wave.
2256 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2257                                            MachineFunction &MF,
2258                                            SIMachineFunctionInfo &Info,
2259                                            CallingConv::ID CallConv,
2260                                            bool IsShader) const {
2261   if (Info.hasWorkGroupIDX()) {
2262     Register Reg = Info.addWorkGroupIDX();
2263     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2264     CCInfo.AllocateReg(Reg);
2265   }
2266 
2267   if (Info.hasWorkGroupIDY()) {
2268     Register Reg = Info.addWorkGroupIDY();
2269     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2270     CCInfo.AllocateReg(Reg);
2271   }
2272 
2273   if (Info.hasWorkGroupIDZ()) {
2274     Register Reg = Info.addWorkGroupIDZ();
2275     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2276     CCInfo.AllocateReg(Reg);
2277   }
2278 
2279   if (Info.hasWorkGroupInfo()) {
2280     Register Reg = Info.addWorkGroupInfo();
2281     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2282     CCInfo.AllocateReg(Reg);
2283   }
2284 
2285   if (Info.hasPrivateSegmentWaveByteOffset()) {
2286     // Scratch wave offset passed in system SGPR.
2287     unsigned PrivateSegmentWaveByteOffsetReg;
2288 
2289     if (IsShader) {
2290       PrivateSegmentWaveByteOffsetReg =
2291         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2292 
2293       // This is true if the scratch wave byte offset doesn't have a fixed
2294       // location.
2295       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2296         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2297         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2298       }
2299     } else
2300       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2301 
2302     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2303     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2304   }
2305 }
2306 
2307 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2308                                      MachineFunction &MF,
2309                                      const SIRegisterInfo &TRI,
2310                                      SIMachineFunctionInfo &Info) {
2311   // Now that we've figured out where the scratch register inputs are, see if
2312   // should reserve the arguments and use them directly.
2313   MachineFrameInfo &MFI = MF.getFrameInfo();
2314   bool HasStackObjects = MFI.hasStackObjects();
2315   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2316 
2317   // Record that we know we have non-spill stack objects so we don't need to
2318   // check all stack objects later.
2319   if (HasStackObjects)
2320     Info.setHasNonSpillStackObjects(true);
2321 
2322   // Everything live out of a block is spilled with fast regalloc, so it's
2323   // almost certain that spilling will be required.
2324   if (TM.getOptLevel() == CodeGenOpt::None)
2325     HasStackObjects = true;
2326 
2327   // For now assume stack access is needed in any callee functions, so we need
2328   // the scratch registers to pass in.
2329   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2330 
2331   if (!ST.enableFlatScratch()) {
2332     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2333       // If we have stack objects, we unquestionably need the private buffer
2334       // resource. For the Code Object V2 ABI, this will be the first 4 user
2335       // SGPR inputs. We can reserve those and use them directly.
2336 
2337       Register PrivateSegmentBufferReg =
2338           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2339       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2340     } else {
2341       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2342       // We tentatively reserve the last registers (skipping the last registers
2343       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2344       // we'll replace these with the ones immediately after those which were
2345       // really allocated. In the prologue copies will be inserted from the
2346       // argument to these reserved registers.
2347 
2348       // Without HSA, relocations are used for the scratch pointer and the
2349       // buffer resource setup is always inserted in the prologue. Scratch wave
2350       // offset is still in an input SGPR.
2351       Info.setScratchRSrcReg(ReservedBufferReg);
2352     }
2353   }
2354 
2355   MachineRegisterInfo &MRI = MF.getRegInfo();
2356 
2357   // For entry functions we have to set up the stack pointer if we use it,
2358   // whereas non-entry functions get this "for free". This means there is no
2359   // intrinsic advantage to using S32 over S34 in cases where we do not have
2360   // calls but do need a frame pointer (i.e. if we are requested to have one
2361   // because frame pointer elimination is disabled). To keep things simple we
2362   // only ever use S32 as the call ABI stack pointer, and so using it does not
2363   // imply we need a separate frame pointer.
2364   //
2365   // Try to use s32 as the SP, but move it if it would interfere with input
2366   // arguments. This won't work with calls though.
2367   //
2368   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2369   // registers.
2370   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2371     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2372   } else {
2373     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2374 
2375     if (MFI.hasCalls())
2376       report_fatal_error("call in graphics shader with too many input SGPRs");
2377 
2378     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2379       if (!MRI.isLiveIn(Reg)) {
2380         Info.setStackPtrOffsetReg(Reg);
2381         break;
2382       }
2383     }
2384 
2385     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2386       report_fatal_error("failed to find register for SP");
2387   }
2388 
2389   // hasFP should be accurate for entry functions even before the frame is
2390   // finalized, because it does not rely on the known stack size, only
2391   // properties like whether variable sized objects are present.
2392   if (ST.getFrameLowering()->hasFP(MF)) {
2393     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2394   }
2395 }
2396 
2397 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2398   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2399   return !Info->isEntryFunction();
2400 }
2401 
2402 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2403 
2404 }
2405 
2406 void SITargetLowering::insertCopiesSplitCSR(
2407   MachineBasicBlock *Entry,
2408   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2409   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2410 
2411   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2412   if (!IStart)
2413     return;
2414 
2415   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2416   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2417   MachineBasicBlock::iterator MBBI = Entry->begin();
2418   for (const MCPhysReg *I = IStart; *I; ++I) {
2419     const TargetRegisterClass *RC = nullptr;
2420     if (AMDGPU::SReg_64RegClass.contains(*I))
2421       RC = &AMDGPU::SGPR_64RegClass;
2422     else if (AMDGPU::SReg_32RegClass.contains(*I))
2423       RC = &AMDGPU::SGPR_32RegClass;
2424     else
2425       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2426 
2427     Register NewVR = MRI->createVirtualRegister(RC);
2428     // Create copy from CSR to a virtual register.
2429     Entry->addLiveIn(*I);
2430     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2431       .addReg(*I);
2432 
2433     // Insert the copy-back instructions right before the terminator.
2434     for (auto *Exit : Exits)
2435       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2436               TII->get(TargetOpcode::COPY), *I)
2437         .addReg(NewVR);
2438   }
2439 }
2440 
2441 SDValue SITargetLowering::LowerFormalArguments(
2442     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2443     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2444     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2445   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2446 
2447   MachineFunction &MF = DAG.getMachineFunction();
2448   const Function &Fn = MF.getFunction();
2449   FunctionType *FType = MF.getFunction().getFunctionType();
2450   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2451 
2452   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2453     DiagnosticInfoUnsupported NoGraphicsHSA(
2454         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2455     DAG.getContext()->diagnose(NoGraphicsHSA);
2456     return DAG.getEntryNode();
2457   }
2458 
2459   Info->allocateModuleLDSGlobal(Fn.getParent());
2460 
2461   SmallVector<ISD::InputArg, 16> Splits;
2462   SmallVector<CCValAssign, 16> ArgLocs;
2463   BitVector Skipped(Ins.size());
2464   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2465                  *DAG.getContext());
2466 
2467   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2468   bool IsKernel = AMDGPU::isKernel(CallConv);
2469   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2470 
2471   if (IsGraphics) {
2472     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2473            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2474            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2475            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2476            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2477            !Info->hasWorkItemIDZ());
2478   }
2479 
2480   if (CallConv == CallingConv::AMDGPU_PS) {
2481     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2482 
2483     // At least one interpolation mode must be enabled or else the GPU will
2484     // hang.
2485     //
2486     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2487     // set PSInputAddr, the user wants to enable some bits after the compilation
2488     // based on run-time states. Since we can't know what the final PSInputEna
2489     // will look like, so we shouldn't do anything here and the user should take
2490     // responsibility for the correct programming.
2491     //
2492     // Otherwise, the following restrictions apply:
2493     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2494     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2495     //   enabled too.
2496     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2497         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2498       CCInfo.AllocateReg(AMDGPU::VGPR0);
2499       CCInfo.AllocateReg(AMDGPU::VGPR1);
2500       Info->markPSInputAllocated(0);
2501       Info->markPSInputEnabled(0);
2502     }
2503     if (Subtarget->isAmdPalOS()) {
2504       // For isAmdPalOS, the user does not enable some bits after compilation
2505       // based on run-time states; the register values being generated here are
2506       // the final ones set in hardware. Therefore we need to apply the
2507       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2508       // a bit is set in PSInputAddr but not PSInputEnable is where the
2509       // frontend set up an input arg for a particular interpolation mode, but
2510       // nothing uses that input arg. Really we should have an earlier pass
2511       // that removes such an arg.)
2512       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2513       if ((PsInputBits & 0x7F) == 0 ||
2514           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2515         Info->markPSInputEnabled(
2516             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2517     }
2518   } else if (IsKernel) {
2519     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2520   } else {
2521     Splits.append(Ins.begin(), Ins.end());
2522   }
2523 
2524   if (IsEntryFunc) {
2525     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2526     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2527   } else if (!IsGraphics) {
2528     // For the fixed ABI, pass workitem IDs in the last argument register.
2529     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2530   }
2531 
2532   if (IsKernel) {
2533     analyzeFormalArgumentsCompute(CCInfo, Ins);
2534   } else {
2535     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2536     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2537   }
2538 
2539   SmallVector<SDValue, 16> Chains;
2540 
2541   // FIXME: This is the minimum kernel argument alignment. We should improve
2542   // this to the maximum alignment of the arguments.
2543   //
2544   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2545   // kern arg offset.
2546   const Align KernelArgBaseAlign = Align(16);
2547 
2548   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2549     const ISD::InputArg &Arg = Ins[i];
2550     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2551       InVals.push_back(DAG.getUNDEF(Arg.VT));
2552       continue;
2553     }
2554 
2555     CCValAssign &VA = ArgLocs[ArgIdx++];
2556     MVT VT = VA.getLocVT();
2557 
2558     if (IsEntryFunc && VA.isMemLoc()) {
2559       VT = Ins[i].VT;
2560       EVT MemVT = VA.getLocVT();
2561 
2562       const uint64_t Offset = VA.getLocMemOffset();
2563       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2564 
2565       if (Arg.Flags.isByRef()) {
2566         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2567 
2568         const GCNTargetMachine &TM =
2569             static_cast<const GCNTargetMachine &>(getTargetMachine());
2570         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2571                                     Arg.Flags.getPointerAddrSpace())) {
2572           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2573                                      Arg.Flags.getPointerAddrSpace());
2574         }
2575 
2576         InVals.push_back(Ptr);
2577         continue;
2578       }
2579 
2580       SDValue Arg = lowerKernargMemParameter(
2581         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2582       Chains.push_back(Arg.getValue(1));
2583 
2584       auto *ParamTy =
2585         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2586       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2587           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2588                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2589         // On SI local pointers are just offsets into LDS, so they are always
2590         // less than 16-bits.  On CI and newer they could potentially be
2591         // real pointers, so we can't guarantee their size.
2592         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2593                           DAG.getValueType(MVT::i16));
2594       }
2595 
2596       InVals.push_back(Arg);
2597       continue;
2598     } else if (!IsEntryFunc && VA.isMemLoc()) {
2599       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2600       InVals.push_back(Val);
2601       if (!Arg.Flags.isByVal())
2602         Chains.push_back(Val.getValue(1));
2603       continue;
2604     }
2605 
2606     assert(VA.isRegLoc() && "Parameter must be in a register!");
2607 
2608     Register Reg = VA.getLocReg();
2609     const TargetRegisterClass *RC = nullptr;
2610     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2611       RC = &AMDGPU::VGPR_32RegClass;
2612     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2613       RC = &AMDGPU::SGPR_32RegClass;
2614     else
2615       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2616     EVT ValVT = VA.getValVT();
2617 
2618     Reg = MF.addLiveIn(Reg, RC);
2619     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2620 
2621     if (Arg.Flags.isSRet()) {
2622       // The return object should be reasonably addressable.
2623 
2624       // FIXME: This helps when the return is a real sret. If it is a
2625       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2626       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2627       unsigned NumBits
2628         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2629       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2630         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2631     }
2632 
2633     // If this is an 8 or 16-bit value, it is really passed promoted
2634     // to 32 bits. Insert an assert[sz]ext to capture this, then
2635     // truncate to the right size.
2636     switch (VA.getLocInfo()) {
2637     case CCValAssign::Full:
2638       break;
2639     case CCValAssign::BCvt:
2640       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2641       break;
2642     case CCValAssign::SExt:
2643       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2644                         DAG.getValueType(ValVT));
2645       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2646       break;
2647     case CCValAssign::ZExt:
2648       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2649                         DAG.getValueType(ValVT));
2650       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2651       break;
2652     case CCValAssign::AExt:
2653       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2654       break;
2655     default:
2656       llvm_unreachable("Unknown loc info!");
2657     }
2658 
2659     InVals.push_back(Val);
2660   }
2661 
2662   // Start adding system SGPRs.
2663   if (IsEntryFunc) {
2664     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2665   } else {
2666     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2667     if (!IsGraphics)
2668       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2669   }
2670 
2671   auto &ArgUsageInfo =
2672     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2673   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2674 
2675   unsigned StackArgSize = CCInfo.getNextStackOffset();
2676   Info->setBytesInStackArgArea(StackArgSize);
2677 
2678   return Chains.empty() ? Chain :
2679     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2680 }
2681 
2682 // TODO: If return values can't fit in registers, we should return as many as
2683 // possible in registers before passing on stack.
2684 bool SITargetLowering::CanLowerReturn(
2685   CallingConv::ID CallConv,
2686   MachineFunction &MF, bool IsVarArg,
2687   const SmallVectorImpl<ISD::OutputArg> &Outs,
2688   LLVMContext &Context) const {
2689   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2690   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2691   // for shaders. Vector types should be explicitly handled by CC.
2692   if (AMDGPU::isEntryFunctionCC(CallConv))
2693     return true;
2694 
2695   SmallVector<CCValAssign, 16> RVLocs;
2696   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2697   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2698 }
2699 
2700 SDValue
2701 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2702                               bool isVarArg,
2703                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2704                               const SmallVectorImpl<SDValue> &OutVals,
2705                               const SDLoc &DL, SelectionDAG &DAG) const {
2706   MachineFunction &MF = DAG.getMachineFunction();
2707   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2708 
2709   if (AMDGPU::isKernel(CallConv)) {
2710     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2711                                              OutVals, DL, DAG);
2712   }
2713 
2714   bool IsShader = AMDGPU::isShader(CallConv);
2715 
2716   Info->setIfReturnsVoid(Outs.empty());
2717   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2718 
2719   // CCValAssign - represent the assignment of the return value to a location.
2720   SmallVector<CCValAssign, 48> RVLocs;
2721   SmallVector<ISD::OutputArg, 48> Splits;
2722 
2723   // CCState - Info about the registers and stack slots.
2724   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2725                  *DAG.getContext());
2726 
2727   // Analyze outgoing return values.
2728   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2729 
2730   SDValue Flag;
2731   SmallVector<SDValue, 48> RetOps;
2732   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2733 
2734   // Copy the result values into the output registers.
2735   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2736        ++I, ++RealRVLocIdx) {
2737     CCValAssign &VA = RVLocs[I];
2738     assert(VA.isRegLoc() && "Can only return in registers!");
2739     // TODO: Partially return in registers if return values don't fit.
2740     SDValue Arg = OutVals[RealRVLocIdx];
2741 
2742     // Copied from other backends.
2743     switch (VA.getLocInfo()) {
2744     case CCValAssign::Full:
2745       break;
2746     case CCValAssign::BCvt:
2747       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2748       break;
2749     case CCValAssign::SExt:
2750       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2751       break;
2752     case CCValAssign::ZExt:
2753       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2754       break;
2755     case CCValAssign::AExt:
2756       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2757       break;
2758     default:
2759       llvm_unreachable("Unknown loc info!");
2760     }
2761 
2762     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2763     Flag = Chain.getValue(1);
2764     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2765   }
2766 
2767   // FIXME: Does sret work properly?
2768   if (!Info->isEntryFunction()) {
2769     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2770     const MCPhysReg *I =
2771       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2772     if (I) {
2773       for (; *I; ++I) {
2774         if (AMDGPU::SReg_64RegClass.contains(*I))
2775           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2776         else if (AMDGPU::SReg_32RegClass.contains(*I))
2777           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2778         else
2779           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2780       }
2781     }
2782   }
2783 
2784   // Update chain and glue.
2785   RetOps[0] = Chain;
2786   if (Flag.getNode())
2787     RetOps.push_back(Flag);
2788 
2789   unsigned Opc = AMDGPUISD::ENDPGM;
2790   if (!IsWaveEnd)
2791     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2792   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2793 }
2794 
2795 SDValue SITargetLowering::LowerCallResult(
2796     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2797     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2798     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2799     SDValue ThisVal) const {
2800   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2801 
2802   // Assign locations to each value returned by this call.
2803   SmallVector<CCValAssign, 16> RVLocs;
2804   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2805                  *DAG.getContext());
2806   CCInfo.AnalyzeCallResult(Ins, RetCC);
2807 
2808   // Copy all of the result registers out of their specified physreg.
2809   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2810     CCValAssign VA = RVLocs[i];
2811     SDValue Val;
2812 
2813     if (VA.isRegLoc()) {
2814       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2815       Chain = Val.getValue(1);
2816       InFlag = Val.getValue(2);
2817     } else if (VA.isMemLoc()) {
2818       report_fatal_error("TODO: return values in memory");
2819     } else
2820       llvm_unreachable("unknown argument location type");
2821 
2822     switch (VA.getLocInfo()) {
2823     case CCValAssign::Full:
2824       break;
2825     case CCValAssign::BCvt:
2826       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2827       break;
2828     case CCValAssign::ZExt:
2829       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2830                         DAG.getValueType(VA.getValVT()));
2831       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2832       break;
2833     case CCValAssign::SExt:
2834       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2835                         DAG.getValueType(VA.getValVT()));
2836       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2837       break;
2838     case CCValAssign::AExt:
2839       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2840       break;
2841     default:
2842       llvm_unreachable("Unknown loc info!");
2843     }
2844 
2845     InVals.push_back(Val);
2846   }
2847 
2848   return Chain;
2849 }
2850 
2851 // Add code to pass special inputs required depending on used features separate
2852 // from the explicit user arguments present in the IR.
2853 void SITargetLowering::passSpecialInputs(
2854     CallLoweringInfo &CLI,
2855     CCState &CCInfo,
2856     const SIMachineFunctionInfo &Info,
2857     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2858     SmallVectorImpl<SDValue> &MemOpChains,
2859     SDValue Chain) const {
2860   // If we don't have a call site, this was a call inserted by
2861   // legalization. These can never use special inputs.
2862   if (!CLI.CB)
2863     return;
2864 
2865   SelectionDAG &DAG = CLI.DAG;
2866   const SDLoc &DL = CLI.DL;
2867   const Function &F = DAG.getMachineFunction().getFunction();
2868 
2869   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2870   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2871 
2872   const AMDGPUFunctionArgInfo *CalleeArgInfo
2873     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2874   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2875     auto &ArgUsageInfo =
2876       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2877     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2878   }
2879 
2880   // TODO: Unify with private memory register handling. This is complicated by
2881   // the fact that at least in kernels, the input argument is not necessarily
2882   // in the same location as the input.
2883   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2884                              StringLiteral> ImplicitAttrs[] = {
2885     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2886     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2887     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2888     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2889     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2890     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2891     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2892   };
2893 
2894   for (auto Attr : ImplicitAttrs) {
2895     const ArgDescriptor *OutgoingArg;
2896     const TargetRegisterClass *ArgRC;
2897     LLT ArgTy;
2898 
2899     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2900 
2901     // If the callee does not use the attribute value, skip copying the value.
2902     if (CLI.CB->hasFnAttr(Attr.second))
2903       continue;
2904 
2905     std::tie(OutgoingArg, ArgRC, ArgTy) =
2906         CalleeArgInfo->getPreloadedValue(InputID);
2907     if (!OutgoingArg)
2908       continue;
2909 
2910     const ArgDescriptor *IncomingArg;
2911     const TargetRegisterClass *IncomingArgRC;
2912     LLT Ty;
2913     std::tie(IncomingArg, IncomingArgRC, Ty) =
2914         CallerArgInfo.getPreloadedValue(InputID);
2915     assert(IncomingArgRC == ArgRC);
2916 
2917     // All special arguments are ints for now.
2918     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2919     SDValue InputReg;
2920 
2921     if (IncomingArg) {
2922       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2923     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2924       // The implicit arg ptr is special because it doesn't have a corresponding
2925       // input for kernels, and is computed from the kernarg segment pointer.
2926       InputReg = getImplicitArgPtr(DAG, DL);
2927     } else {
2928       // We may have proven the input wasn't needed, although the ABI is
2929       // requiring it. We just need to allocate the register appropriately.
2930       InputReg = DAG.getUNDEF(ArgVT);
2931     }
2932 
2933     if (OutgoingArg->isRegister()) {
2934       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2935       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2936         report_fatal_error("failed to allocate implicit input argument");
2937     } else {
2938       unsigned SpecialArgOffset =
2939           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2940       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2941                                               SpecialArgOffset);
2942       MemOpChains.push_back(ArgStore);
2943     }
2944   }
2945 
2946   // Pack workitem IDs into a single register or pass it as is if already
2947   // packed.
2948   const ArgDescriptor *OutgoingArg;
2949   const TargetRegisterClass *ArgRC;
2950   LLT Ty;
2951 
2952   std::tie(OutgoingArg, ArgRC, Ty) =
2953       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2954   if (!OutgoingArg)
2955     std::tie(OutgoingArg, ArgRC, Ty) =
2956         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2957   if (!OutgoingArg)
2958     std::tie(OutgoingArg, ArgRC, Ty) =
2959         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2960   if (!OutgoingArg)
2961     return;
2962 
2963   const ArgDescriptor *IncomingArgX = std::get<0>(
2964       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2965   const ArgDescriptor *IncomingArgY = std::get<0>(
2966       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2967   const ArgDescriptor *IncomingArgZ = std::get<0>(
2968       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2969 
2970   SDValue InputReg;
2971   SDLoc SL;
2972 
2973   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2974   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2975   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2976 
2977   // If incoming ids are not packed we need to pack them.
2978   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2979       NeedWorkItemIDX) {
2980     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2981       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2982     } else {
2983       InputReg = DAG.getConstant(0, DL, MVT::i32);
2984     }
2985   }
2986 
2987   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2988       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2989     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2990     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2991                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2992     InputReg = InputReg.getNode() ?
2993                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2994   }
2995 
2996   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2997       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2998     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2999     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
3000                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
3001     InputReg = InputReg.getNode() ?
3002                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
3003   }
3004 
3005   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
3006     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
3007       // We're in a situation where the outgoing function requires the workitem
3008       // ID, but the calling function does not have it (e.g a graphics function
3009       // calling a C calling convention function). This is illegal, but we need
3010       // to produce something.
3011       InputReg = DAG.getUNDEF(MVT::i32);
3012     } else {
3013       // Workitem ids are already packed, any of present incoming arguments
3014       // will carry all required fields.
3015       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
3016         IncomingArgX ? *IncomingArgX :
3017         IncomingArgY ? *IncomingArgY :
3018         *IncomingArgZ, ~0u);
3019       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3020     }
3021   }
3022 
3023   if (OutgoingArg->isRegister()) {
3024     if (InputReg)
3025       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3026 
3027     CCInfo.AllocateReg(OutgoingArg->getRegister());
3028   } else {
3029     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3030     if (InputReg) {
3031       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3032                                               SpecialArgOffset);
3033       MemOpChains.push_back(ArgStore);
3034     }
3035   }
3036 }
3037 
3038 static bool canGuaranteeTCO(CallingConv::ID CC) {
3039   return CC == CallingConv::Fast;
3040 }
3041 
3042 /// Return true if we might ever do TCO for calls with this calling convention.
3043 static bool mayTailCallThisCC(CallingConv::ID CC) {
3044   switch (CC) {
3045   case CallingConv::C:
3046   case CallingConv::AMDGPU_Gfx:
3047     return true;
3048   default:
3049     return canGuaranteeTCO(CC);
3050   }
3051 }
3052 
3053 bool SITargetLowering::isEligibleForTailCallOptimization(
3054     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3055     const SmallVectorImpl<ISD::OutputArg> &Outs,
3056     const SmallVectorImpl<SDValue> &OutVals,
3057     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3058   if (!mayTailCallThisCC(CalleeCC))
3059     return false;
3060 
3061   // For a divergent call target, we need to do a waterfall loop over the
3062   // possible callees which precludes us from using a simple jump.
3063   if (Callee->isDivergent())
3064     return false;
3065 
3066   MachineFunction &MF = DAG.getMachineFunction();
3067   const Function &CallerF = MF.getFunction();
3068   CallingConv::ID CallerCC = CallerF.getCallingConv();
3069   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3070   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3071 
3072   // Kernels aren't callable, and don't have a live in return address so it
3073   // doesn't make sense to do a tail call with entry functions.
3074   if (!CallerPreserved)
3075     return false;
3076 
3077   bool CCMatch = CallerCC == CalleeCC;
3078 
3079   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3080     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3081       return true;
3082     return false;
3083   }
3084 
3085   // TODO: Can we handle var args?
3086   if (IsVarArg)
3087     return false;
3088 
3089   for (const Argument &Arg : CallerF.args()) {
3090     if (Arg.hasByValAttr())
3091       return false;
3092   }
3093 
3094   LLVMContext &Ctx = *DAG.getContext();
3095 
3096   // Check that the call results are passed in the same way.
3097   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3098                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3099                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3100     return false;
3101 
3102   // The callee has to preserve all registers the caller needs to preserve.
3103   if (!CCMatch) {
3104     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3105     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3106       return false;
3107   }
3108 
3109   // Nothing more to check if the callee is taking no arguments.
3110   if (Outs.empty())
3111     return true;
3112 
3113   SmallVector<CCValAssign, 16> ArgLocs;
3114   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3115 
3116   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3117 
3118   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3119   // If the stack arguments for this call do not fit into our own save area then
3120   // the call cannot be made tail.
3121   // TODO: Is this really necessary?
3122   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3123     return false;
3124 
3125   const MachineRegisterInfo &MRI = MF.getRegInfo();
3126   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3127 }
3128 
3129 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3130   if (!CI->isTailCall())
3131     return false;
3132 
3133   const Function *ParentFn = CI->getParent()->getParent();
3134   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3135     return false;
3136   return true;
3137 }
3138 
3139 // The wave scratch offset register is used as the global base pointer.
3140 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3141                                     SmallVectorImpl<SDValue> &InVals) const {
3142   SelectionDAG &DAG = CLI.DAG;
3143   const SDLoc &DL = CLI.DL;
3144   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3145   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3146   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3147   SDValue Chain = CLI.Chain;
3148   SDValue Callee = CLI.Callee;
3149   bool &IsTailCall = CLI.IsTailCall;
3150   CallingConv::ID CallConv = CLI.CallConv;
3151   bool IsVarArg = CLI.IsVarArg;
3152   bool IsSibCall = false;
3153   bool IsThisReturn = false;
3154   MachineFunction &MF = DAG.getMachineFunction();
3155 
3156   if (Callee.isUndef() || isNullConstant(Callee)) {
3157     if (!CLI.IsTailCall) {
3158       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3159         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3160     }
3161 
3162     return Chain;
3163   }
3164 
3165   if (IsVarArg) {
3166     return lowerUnhandledCall(CLI, InVals,
3167                               "unsupported call to variadic function ");
3168   }
3169 
3170   if (!CLI.CB)
3171     report_fatal_error("unsupported libcall legalization");
3172 
3173   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3174     return lowerUnhandledCall(CLI, InVals,
3175                               "unsupported required tail call to function ");
3176   }
3177 
3178   if (AMDGPU::isShader(CallConv)) {
3179     // Note the issue is with the CC of the called function, not of the call
3180     // itself.
3181     return lowerUnhandledCall(CLI, InVals,
3182                               "unsupported call to a shader function ");
3183   }
3184 
3185   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3186       CallConv != CallingConv::AMDGPU_Gfx) {
3187     // Only allow calls with specific calling conventions.
3188     return lowerUnhandledCall(CLI, InVals,
3189                               "unsupported calling convention for call from "
3190                               "graphics shader of function ");
3191   }
3192 
3193   if (IsTailCall) {
3194     IsTailCall = isEligibleForTailCallOptimization(
3195       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3196     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3197       report_fatal_error("failed to perform tail call elimination on a call "
3198                          "site marked musttail");
3199     }
3200 
3201     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3202 
3203     // A sibling call is one where we're under the usual C ABI and not planning
3204     // to change that but can still do a tail call:
3205     if (!TailCallOpt && IsTailCall)
3206       IsSibCall = true;
3207 
3208     if (IsTailCall)
3209       ++NumTailCalls;
3210   }
3211 
3212   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3213   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3214   SmallVector<SDValue, 8> MemOpChains;
3215 
3216   // Analyze operands of the call, assigning locations to each operand.
3217   SmallVector<CCValAssign, 16> ArgLocs;
3218   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3219   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3220 
3221   if (CallConv != CallingConv::AMDGPU_Gfx) {
3222     // With a fixed ABI, allocate fixed registers before user arguments.
3223     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3224   }
3225 
3226   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3227 
3228   // Get a count of how many bytes are to be pushed on the stack.
3229   unsigned NumBytes = CCInfo.getNextStackOffset();
3230 
3231   if (IsSibCall) {
3232     // Since we're not changing the ABI to make this a tail call, the memory
3233     // operands are already available in the caller's incoming argument space.
3234     NumBytes = 0;
3235   }
3236 
3237   // FPDiff is the byte offset of the call's argument area from the callee's.
3238   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3239   // by this amount for a tail call. In a sibling call it must be 0 because the
3240   // caller will deallocate the entire stack and the callee still expects its
3241   // arguments to begin at SP+0. Completely unused for non-tail calls.
3242   int32_t FPDiff = 0;
3243   MachineFrameInfo &MFI = MF.getFrameInfo();
3244 
3245   // Adjust the stack pointer for the new arguments...
3246   // These operations are automatically eliminated by the prolog/epilog pass
3247   if (!IsSibCall) {
3248     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3249 
3250     if (!Subtarget->enableFlatScratch()) {
3251       SmallVector<SDValue, 4> CopyFromChains;
3252 
3253       // In the HSA case, this should be an identity copy.
3254       SDValue ScratchRSrcReg
3255         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3256       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3257       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3258       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3259     }
3260   }
3261 
3262   MVT PtrVT = MVT::i32;
3263 
3264   // Walk the register/memloc assignments, inserting copies/loads.
3265   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3266     CCValAssign &VA = ArgLocs[i];
3267     SDValue Arg = OutVals[i];
3268 
3269     // Promote the value if needed.
3270     switch (VA.getLocInfo()) {
3271     case CCValAssign::Full:
3272       break;
3273     case CCValAssign::BCvt:
3274       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3275       break;
3276     case CCValAssign::ZExt:
3277       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3278       break;
3279     case CCValAssign::SExt:
3280       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3281       break;
3282     case CCValAssign::AExt:
3283       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3284       break;
3285     case CCValAssign::FPExt:
3286       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3287       break;
3288     default:
3289       llvm_unreachable("Unknown loc info!");
3290     }
3291 
3292     if (VA.isRegLoc()) {
3293       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3294     } else {
3295       assert(VA.isMemLoc());
3296 
3297       SDValue DstAddr;
3298       MachinePointerInfo DstInfo;
3299 
3300       unsigned LocMemOffset = VA.getLocMemOffset();
3301       int32_t Offset = LocMemOffset;
3302 
3303       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3304       MaybeAlign Alignment;
3305 
3306       if (IsTailCall) {
3307         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3308         unsigned OpSize = Flags.isByVal() ?
3309           Flags.getByValSize() : VA.getValVT().getStoreSize();
3310 
3311         // FIXME: We can have better than the minimum byval required alignment.
3312         Alignment =
3313             Flags.isByVal()
3314                 ? Flags.getNonZeroByValAlign()
3315                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3316 
3317         Offset = Offset + FPDiff;
3318         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3319 
3320         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3321         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3322 
3323         // Make sure any stack arguments overlapping with where we're storing
3324         // are loaded before this eventual operation. Otherwise they'll be
3325         // clobbered.
3326 
3327         // FIXME: Why is this really necessary? This seems to just result in a
3328         // lot of code to copy the stack and write them back to the same
3329         // locations, which are supposed to be immutable?
3330         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3331       } else {
3332         // Stores to the argument stack area are relative to the stack pointer.
3333         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3334                                         MVT::i32);
3335         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3336         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3337         Alignment =
3338             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3339       }
3340 
3341       if (Outs[i].Flags.isByVal()) {
3342         SDValue SizeNode =
3343             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3344         SDValue Cpy =
3345             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3346                           Outs[i].Flags.getNonZeroByValAlign(),
3347                           /*isVol = */ false, /*AlwaysInline = */ true,
3348                           /*isTailCall = */ false, DstInfo,
3349                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3350 
3351         MemOpChains.push_back(Cpy);
3352       } else {
3353         SDValue Store =
3354             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3355         MemOpChains.push_back(Store);
3356       }
3357     }
3358   }
3359 
3360   if (!MemOpChains.empty())
3361     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3362 
3363   // Build a sequence of copy-to-reg nodes chained together with token chain
3364   // and flag operands which copy the outgoing args into the appropriate regs.
3365   SDValue InFlag;
3366   for (auto &RegToPass : RegsToPass) {
3367     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3368                              RegToPass.second, InFlag);
3369     InFlag = Chain.getValue(1);
3370   }
3371 
3372 
3373   // We don't usually want to end the call-sequence here because we would tidy
3374   // the frame up *after* the call, however in the ABI-changing tail-call case
3375   // we've carefully laid out the parameters so that when sp is reset they'll be
3376   // in the correct location.
3377   if (IsTailCall && !IsSibCall) {
3378     Chain = DAG.getCALLSEQ_END(Chain,
3379                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3380                                DAG.getTargetConstant(0, DL, MVT::i32),
3381                                InFlag, DL);
3382     InFlag = Chain.getValue(1);
3383   }
3384 
3385   std::vector<SDValue> Ops;
3386   Ops.push_back(Chain);
3387   Ops.push_back(Callee);
3388   // Add a redundant copy of the callee global which will not be legalized, as
3389   // we need direct access to the callee later.
3390   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3391     const GlobalValue *GV = GSD->getGlobal();
3392     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3393   } else {
3394     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3395   }
3396 
3397   if (IsTailCall) {
3398     // Each tail call may have to adjust the stack by a different amount, so
3399     // this information must travel along with the operation for eventual
3400     // consumption by emitEpilogue.
3401     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3402   }
3403 
3404   // Add argument registers to the end of the list so that they are known live
3405   // into the call.
3406   for (auto &RegToPass : RegsToPass) {
3407     Ops.push_back(DAG.getRegister(RegToPass.first,
3408                                   RegToPass.second.getValueType()));
3409   }
3410 
3411   // Add a register mask operand representing the call-preserved registers.
3412 
3413   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3414   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3415   assert(Mask && "Missing call preserved mask for calling convention");
3416   Ops.push_back(DAG.getRegisterMask(Mask));
3417 
3418   if (InFlag.getNode())
3419     Ops.push_back(InFlag);
3420 
3421   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3422 
3423   // If we're doing a tall call, use a TC_RETURN here rather than an
3424   // actual call instruction.
3425   if (IsTailCall) {
3426     MFI.setHasTailCall();
3427     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3428   }
3429 
3430   // Returns a chain and a flag for retval copy to use.
3431   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3432   Chain = Call.getValue(0);
3433   InFlag = Call.getValue(1);
3434 
3435   uint64_t CalleePopBytes = NumBytes;
3436   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3437                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3438                              InFlag, DL);
3439   if (!Ins.empty())
3440     InFlag = Chain.getValue(1);
3441 
3442   // Handle result values, copying them out of physregs into vregs that we
3443   // return.
3444   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3445                          InVals, IsThisReturn,
3446                          IsThisReturn ? OutVals[0] : SDValue());
3447 }
3448 
3449 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3450 // except for applying the wave size scale to the increment amount.
3451 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3452     SDValue Op, SelectionDAG &DAG) const {
3453   const MachineFunction &MF = DAG.getMachineFunction();
3454   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3455 
3456   SDLoc dl(Op);
3457   EVT VT = Op.getValueType();
3458   SDValue Tmp1 = Op;
3459   SDValue Tmp2 = Op.getValue(1);
3460   SDValue Tmp3 = Op.getOperand(2);
3461   SDValue Chain = Tmp1.getOperand(0);
3462 
3463   Register SPReg = Info->getStackPtrOffsetReg();
3464 
3465   // Chain the dynamic stack allocation so that it doesn't modify the stack
3466   // pointer when other instructions are using the stack.
3467   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3468 
3469   SDValue Size  = Tmp2.getOperand(1);
3470   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3471   Chain = SP.getValue(1);
3472   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3473   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3474   const TargetFrameLowering *TFL = ST.getFrameLowering();
3475   unsigned Opc =
3476     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3477     ISD::ADD : ISD::SUB;
3478 
3479   SDValue ScaledSize = DAG.getNode(
3480       ISD::SHL, dl, VT, Size,
3481       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3482 
3483   Align StackAlign = TFL->getStackAlign();
3484   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3485   if (Alignment && *Alignment > StackAlign) {
3486     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3487                        DAG.getConstant(-(uint64_t)Alignment->value()
3488                                            << ST.getWavefrontSizeLog2(),
3489                                        dl, VT));
3490   }
3491 
3492   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3493   Tmp2 = DAG.getCALLSEQ_END(
3494       Chain, DAG.getIntPtrConstant(0, dl, true),
3495       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3496 
3497   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3498 }
3499 
3500 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3501                                                   SelectionDAG &DAG) const {
3502   // We only handle constant sizes here to allow non-entry block, static sized
3503   // allocas. A truly dynamic value is more difficult to support because we
3504   // don't know if the size value is uniform or not. If the size isn't uniform,
3505   // we would need to do a wave reduction to get the maximum size to know how
3506   // much to increment the uniform stack pointer.
3507   SDValue Size = Op.getOperand(1);
3508   if (isa<ConstantSDNode>(Size))
3509       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3510 
3511   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3512 }
3513 
3514 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3515                                              const MachineFunction &MF) const {
3516   Register Reg = StringSwitch<Register>(RegName)
3517     .Case("m0", AMDGPU::M0)
3518     .Case("exec", AMDGPU::EXEC)
3519     .Case("exec_lo", AMDGPU::EXEC_LO)
3520     .Case("exec_hi", AMDGPU::EXEC_HI)
3521     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3522     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3523     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3524     .Default(Register());
3525 
3526   if (Reg == AMDGPU::NoRegister) {
3527     report_fatal_error(Twine("invalid register name \""
3528                              + StringRef(RegName)  + "\"."));
3529 
3530   }
3531 
3532   if (!Subtarget->hasFlatScrRegister() &&
3533        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3534     report_fatal_error(Twine("invalid register \""
3535                              + StringRef(RegName)  + "\" for subtarget."));
3536   }
3537 
3538   switch (Reg) {
3539   case AMDGPU::M0:
3540   case AMDGPU::EXEC_LO:
3541   case AMDGPU::EXEC_HI:
3542   case AMDGPU::FLAT_SCR_LO:
3543   case AMDGPU::FLAT_SCR_HI:
3544     if (VT.getSizeInBits() == 32)
3545       return Reg;
3546     break;
3547   case AMDGPU::EXEC:
3548   case AMDGPU::FLAT_SCR:
3549     if (VT.getSizeInBits() == 64)
3550       return Reg;
3551     break;
3552   default:
3553     llvm_unreachable("missing register type checking");
3554   }
3555 
3556   report_fatal_error(Twine("invalid type for register \""
3557                            + StringRef(RegName) + "\"."));
3558 }
3559 
3560 // If kill is not the last instruction, split the block so kill is always a
3561 // proper terminator.
3562 MachineBasicBlock *
3563 SITargetLowering::splitKillBlock(MachineInstr &MI,
3564                                  MachineBasicBlock *BB) const {
3565   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3566   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3567   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3568   return SplitBB;
3569 }
3570 
3571 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3572 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3573 // be the first instruction in the remainder block.
3574 //
3575 /// \returns { LoopBody, Remainder }
3576 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3577 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3578   MachineFunction *MF = MBB.getParent();
3579   MachineBasicBlock::iterator I(&MI);
3580 
3581   // To insert the loop we need to split the block. Move everything after this
3582   // point to a new block, and insert a new empty block between the two.
3583   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3584   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3585   MachineFunction::iterator MBBI(MBB);
3586   ++MBBI;
3587 
3588   MF->insert(MBBI, LoopBB);
3589   MF->insert(MBBI, RemainderBB);
3590 
3591   LoopBB->addSuccessor(LoopBB);
3592   LoopBB->addSuccessor(RemainderBB);
3593 
3594   // Move the rest of the block into a new block.
3595   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3596 
3597   if (InstInLoop) {
3598     auto Next = std::next(I);
3599 
3600     // Move instruction to loop body.
3601     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3602 
3603     // Move the rest of the block.
3604     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3605   } else {
3606     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3607   }
3608 
3609   MBB.addSuccessor(LoopBB);
3610 
3611   return std::make_pair(LoopBB, RemainderBB);
3612 }
3613 
3614 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3615 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3616   MachineBasicBlock *MBB = MI.getParent();
3617   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3618   auto I = MI.getIterator();
3619   auto E = std::next(I);
3620 
3621   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3622     .addImm(0);
3623 
3624   MIBundleBuilder Bundler(*MBB, I, E);
3625   finalizeBundle(*MBB, Bundler.begin());
3626 }
3627 
3628 MachineBasicBlock *
3629 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3630                                          MachineBasicBlock *BB) const {
3631   const DebugLoc &DL = MI.getDebugLoc();
3632 
3633   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3634 
3635   MachineBasicBlock *LoopBB;
3636   MachineBasicBlock *RemainderBB;
3637   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3638 
3639   // Apparently kill flags are only valid if the def is in the same block?
3640   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3641     Src->setIsKill(false);
3642 
3643   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3644 
3645   MachineBasicBlock::iterator I = LoopBB->end();
3646 
3647   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3648     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3649 
3650   // Clear TRAP_STS.MEM_VIOL
3651   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3652     .addImm(0)
3653     .addImm(EncodedReg);
3654 
3655   bundleInstWithWaitcnt(MI);
3656 
3657   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3658 
3659   // Load and check TRAP_STS.MEM_VIOL
3660   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3661     .addImm(EncodedReg);
3662 
3663   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3664   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3665     .addReg(Reg, RegState::Kill)
3666     .addImm(0);
3667   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3668     .addMBB(LoopBB);
3669 
3670   return RemainderBB;
3671 }
3672 
3673 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3674 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3675 // will only do one iteration. In the worst case, this will loop 64 times.
3676 //
3677 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3678 static MachineBasicBlock::iterator
3679 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3680                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3681                        const DebugLoc &DL, const MachineOperand &Idx,
3682                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3683                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3684                        Register &SGPRIdxReg) {
3685 
3686   MachineFunction *MF = OrigBB.getParent();
3687   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3688   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3689   MachineBasicBlock::iterator I = LoopBB.begin();
3690 
3691   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3692   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3693   Register NewExec = MRI.createVirtualRegister(BoolRC);
3694   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3695   Register CondReg = MRI.createVirtualRegister(BoolRC);
3696 
3697   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3698     .addReg(InitReg)
3699     .addMBB(&OrigBB)
3700     .addReg(ResultReg)
3701     .addMBB(&LoopBB);
3702 
3703   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3704     .addReg(InitSaveExecReg)
3705     .addMBB(&OrigBB)
3706     .addReg(NewExec)
3707     .addMBB(&LoopBB);
3708 
3709   // Read the next variant <- also loop target.
3710   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3711       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3712 
3713   // Compare the just read M0 value to all possible Idx values.
3714   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3715       .addReg(CurrentIdxReg)
3716       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3717 
3718   // Update EXEC, save the original EXEC value to VCC.
3719   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3720                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3721           NewExec)
3722     .addReg(CondReg, RegState::Kill);
3723 
3724   MRI.setSimpleHint(NewExec, CondReg);
3725 
3726   if (UseGPRIdxMode) {
3727     if (Offset == 0) {
3728       SGPRIdxReg = CurrentIdxReg;
3729     } else {
3730       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3731       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3732           .addReg(CurrentIdxReg, RegState::Kill)
3733           .addImm(Offset);
3734     }
3735   } else {
3736     // Move index from VCC into M0
3737     if (Offset == 0) {
3738       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3739         .addReg(CurrentIdxReg, RegState::Kill);
3740     } else {
3741       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3742         .addReg(CurrentIdxReg, RegState::Kill)
3743         .addImm(Offset);
3744     }
3745   }
3746 
3747   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3748   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3749   MachineInstr *InsertPt =
3750     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3751                                                   : AMDGPU::S_XOR_B64_term), Exec)
3752       .addReg(Exec)
3753       .addReg(NewExec);
3754 
3755   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3756   // s_cbranch_scc0?
3757 
3758   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3759   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3760     .addMBB(&LoopBB);
3761 
3762   return InsertPt->getIterator();
3763 }
3764 
3765 // This has slightly sub-optimal regalloc when the source vector is killed by
3766 // the read. The register allocator does not understand that the kill is
3767 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3768 // subregister from it, using 1 more VGPR than necessary. This was saved when
3769 // this was expanded after register allocation.
3770 static MachineBasicBlock::iterator
3771 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3772                unsigned InitResultReg, unsigned PhiReg, int Offset,
3773                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3774   MachineFunction *MF = MBB.getParent();
3775   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3776   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3777   MachineRegisterInfo &MRI = MF->getRegInfo();
3778   const DebugLoc &DL = MI.getDebugLoc();
3779   MachineBasicBlock::iterator I(&MI);
3780 
3781   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3782   Register DstReg = MI.getOperand(0).getReg();
3783   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3784   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3785   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3786   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3787 
3788   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3789 
3790   // Save the EXEC mask
3791   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3792     .addReg(Exec);
3793 
3794   MachineBasicBlock *LoopBB;
3795   MachineBasicBlock *RemainderBB;
3796   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3797 
3798   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3799 
3800   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3801                                       InitResultReg, DstReg, PhiReg, TmpExec,
3802                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3803 
3804   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3805   MachineFunction::iterator MBBI(LoopBB);
3806   ++MBBI;
3807   MF->insert(MBBI, LandingPad);
3808   LoopBB->removeSuccessor(RemainderBB);
3809   LandingPad->addSuccessor(RemainderBB);
3810   LoopBB->addSuccessor(LandingPad);
3811   MachineBasicBlock::iterator First = LandingPad->begin();
3812   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3813     .addReg(SaveExec);
3814 
3815   return InsPt;
3816 }
3817 
3818 // Returns subreg index, offset
3819 static std::pair<unsigned, int>
3820 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3821                             const TargetRegisterClass *SuperRC,
3822                             unsigned VecReg,
3823                             int Offset) {
3824   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3825 
3826   // Skip out of bounds offsets, or else we would end up using an undefined
3827   // register.
3828   if (Offset >= NumElts || Offset < 0)
3829     return std::make_pair(AMDGPU::sub0, Offset);
3830 
3831   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3832 }
3833 
3834 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3835                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3836                                  int Offset) {
3837   MachineBasicBlock *MBB = MI.getParent();
3838   const DebugLoc &DL = MI.getDebugLoc();
3839   MachineBasicBlock::iterator I(&MI);
3840 
3841   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3842 
3843   assert(Idx->getReg() != AMDGPU::NoRegister);
3844 
3845   if (Offset == 0) {
3846     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3847   } else {
3848     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3849         .add(*Idx)
3850         .addImm(Offset);
3851   }
3852 }
3853 
3854 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3855                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3856                                    int Offset) {
3857   MachineBasicBlock *MBB = MI.getParent();
3858   const DebugLoc &DL = MI.getDebugLoc();
3859   MachineBasicBlock::iterator I(&MI);
3860 
3861   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3862 
3863   if (Offset == 0)
3864     return Idx->getReg();
3865 
3866   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3867   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3868       .add(*Idx)
3869       .addImm(Offset);
3870   return Tmp;
3871 }
3872 
3873 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3874                                           MachineBasicBlock &MBB,
3875                                           const GCNSubtarget &ST) {
3876   const SIInstrInfo *TII = ST.getInstrInfo();
3877   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3878   MachineFunction *MF = MBB.getParent();
3879   MachineRegisterInfo &MRI = MF->getRegInfo();
3880 
3881   Register Dst = MI.getOperand(0).getReg();
3882   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3883   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3884   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3885 
3886   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3887   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3888 
3889   unsigned SubReg;
3890   std::tie(SubReg, Offset)
3891     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3892 
3893   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3894 
3895   // Check for a SGPR index.
3896   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3897     MachineBasicBlock::iterator I(&MI);
3898     const DebugLoc &DL = MI.getDebugLoc();
3899 
3900     if (UseGPRIdxMode) {
3901       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3902       // to avoid interfering with other uses, so probably requires a new
3903       // optimization pass.
3904       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3905 
3906       const MCInstrDesc &GPRIDXDesc =
3907           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3908       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3909           .addReg(SrcReg)
3910           .addReg(Idx)
3911           .addImm(SubReg);
3912     } else {
3913       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3914 
3915       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3916         .addReg(SrcReg, 0, SubReg)
3917         .addReg(SrcReg, RegState::Implicit);
3918     }
3919 
3920     MI.eraseFromParent();
3921 
3922     return &MBB;
3923   }
3924 
3925   // Control flow needs to be inserted if indexing with a VGPR.
3926   const DebugLoc &DL = MI.getDebugLoc();
3927   MachineBasicBlock::iterator I(&MI);
3928 
3929   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3930   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3931 
3932   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3933 
3934   Register SGPRIdxReg;
3935   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3936                               UseGPRIdxMode, SGPRIdxReg);
3937 
3938   MachineBasicBlock *LoopBB = InsPt->getParent();
3939 
3940   if (UseGPRIdxMode) {
3941     const MCInstrDesc &GPRIDXDesc =
3942         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3943 
3944     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3945         .addReg(SrcReg)
3946         .addReg(SGPRIdxReg)
3947         .addImm(SubReg);
3948   } else {
3949     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3950       .addReg(SrcReg, 0, SubReg)
3951       .addReg(SrcReg, RegState::Implicit);
3952   }
3953 
3954   MI.eraseFromParent();
3955 
3956   return LoopBB;
3957 }
3958 
3959 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3960                                           MachineBasicBlock &MBB,
3961                                           const GCNSubtarget &ST) {
3962   const SIInstrInfo *TII = ST.getInstrInfo();
3963   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3964   MachineFunction *MF = MBB.getParent();
3965   MachineRegisterInfo &MRI = MF->getRegInfo();
3966 
3967   Register Dst = MI.getOperand(0).getReg();
3968   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3969   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3970   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3971   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3972   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3973   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3974 
3975   // This can be an immediate, but will be folded later.
3976   assert(Val->getReg());
3977 
3978   unsigned SubReg;
3979   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3980                                                          SrcVec->getReg(),
3981                                                          Offset);
3982   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3983 
3984   if (Idx->getReg() == AMDGPU::NoRegister) {
3985     MachineBasicBlock::iterator I(&MI);
3986     const DebugLoc &DL = MI.getDebugLoc();
3987 
3988     assert(Offset == 0);
3989 
3990     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3991         .add(*SrcVec)
3992         .add(*Val)
3993         .addImm(SubReg);
3994 
3995     MI.eraseFromParent();
3996     return &MBB;
3997   }
3998 
3999   // Check for a SGPR index.
4000   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
4001     MachineBasicBlock::iterator I(&MI);
4002     const DebugLoc &DL = MI.getDebugLoc();
4003 
4004     if (UseGPRIdxMode) {
4005       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
4006 
4007       const MCInstrDesc &GPRIDXDesc =
4008           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4009       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4010           .addReg(SrcVec->getReg())
4011           .add(*Val)
4012           .addReg(Idx)
4013           .addImm(SubReg);
4014     } else {
4015       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4016 
4017       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4018           TRI.getRegSizeInBits(*VecRC), 32, false);
4019       BuildMI(MBB, I, DL, MovRelDesc, Dst)
4020           .addReg(SrcVec->getReg())
4021           .add(*Val)
4022           .addImm(SubReg);
4023     }
4024     MI.eraseFromParent();
4025     return &MBB;
4026   }
4027 
4028   // Control flow needs to be inserted if indexing with a VGPR.
4029   if (Val->isReg())
4030     MRI.clearKillFlags(Val->getReg());
4031 
4032   const DebugLoc &DL = MI.getDebugLoc();
4033 
4034   Register PhiReg = MRI.createVirtualRegister(VecRC);
4035 
4036   Register SGPRIdxReg;
4037   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4038                               UseGPRIdxMode, SGPRIdxReg);
4039   MachineBasicBlock *LoopBB = InsPt->getParent();
4040 
4041   if (UseGPRIdxMode) {
4042     const MCInstrDesc &GPRIDXDesc =
4043         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4044 
4045     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4046         .addReg(PhiReg)
4047         .add(*Val)
4048         .addReg(SGPRIdxReg)
4049         .addImm(AMDGPU::sub0);
4050   } else {
4051     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4052         TRI.getRegSizeInBits(*VecRC), 32, false);
4053     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4054         .addReg(PhiReg)
4055         .add(*Val)
4056         .addImm(AMDGPU::sub0);
4057   }
4058 
4059   MI.eraseFromParent();
4060   return LoopBB;
4061 }
4062 
4063 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4064   MachineInstr &MI, MachineBasicBlock *BB) const {
4065 
4066   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4067   MachineFunction *MF = BB->getParent();
4068   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4069 
4070   switch (MI.getOpcode()) {
4071   case AMDGPU::S_UADDO_PSEUDO:
4072   case AMDGPU::S_USUBO_PSEUDO: {
4073     const DebugLoc &DL = MI.getDebugLoc();
4074     MachineOperand &Dest0 = MI.getOperand(0);
4075     MachineOperand &Dest1 = MI.getOperand(1);
4076     MachineOperand &Src0 = MI.getOperand(2);
4077     MachineOperand &Src1 = MI.getOperand(3);
4078 
4079     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4080                        ? AMDGPU::S_ADD_I32
4081                        : AMDGPU::S_SUB_I32;
4082     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4083 
4084     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4085         .addImm(1)
4086         .addImm(0);
4087 
4088     MI.eraseFromParent();
4089     return BB;
4090   }
4091   case AMDGPU::S_ADD_U64_PSEUDO:
4092   case AMDGPU::S_SUB_U64_PSEUDO: {
4093     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4094     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4095     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4096     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4097     const DebugLoc &DL = MI.getDebugLoc();
4098 
4099     MachineOperand &Dest = MI.getOperand(0);
4100     MachineOperand &Src0 = MI.getOperand(1);
4101     MachineOperand &Src1 = MI.getOperand(2);
4102 
4103     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4104     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4105 
4106     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4107         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4108     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4109         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4110 
4111     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4112         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4113     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4114         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4115 
4116     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4117 
4118     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4119     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4120     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4121     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4122     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4123         .addReg(DestSub0)
4124         .addImm(AMDGPU::sub0)
4125         .addReg(DestSub1)
4126         .addImm(AMDGPU::sub1);
4127     MI.eraseFromParent();
4128     return BB;
4129   }
4130   case AMDGPU::V_ADD_U64_PSEUDO:
4131   case AMDGPU::V_SUB_U64_PSEUDO: {
4132     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4133     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4134     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4135     const DebugLoc &DL = MI.getDebugLoc();
4136 
4137     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4138 
4139     MachineOperand &Dest = MI.getOperand(0);
4140     MachineOperand &Src0 = MI.getOperand(1);
4141     MachineOperand &Src1 = MI.getOperand(2);
4142 
4143     if (IsAdd && ST.hasLshlAddB64()) {
4144       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4145                          Dest.getReg())
4146                      .add(Src0)
4147                      .addImm(0)
4148                      .add(Src1);
4149       TII->legalizeOperands(*Add);
4150       MI.eraseFromParent();
4151       return BB;
4152     }
4153 
4154     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4155 
4156     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4157     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4158 
4159     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4160     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4161 
4162     const TargetRegisterClass *Src0RC = Src0.isReg()
4163                                             ? MRI.getRegClass(Src0.getReg())
4164                                             : &AMDGPU::VReg_64RegClass;
4165     const TargetRegisterClass *Src1RC = Src1.isReg()
4166                                             ? MRI.getRegClass(Src1.getReg())
4167                                             : &AMDGPU::VReg_64RegClass;
4168 
4169     const TargetRegisterClass *Src0SubRC =
4170         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4171     const TargetRegisterClass *Src1SubRC =
4172         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4173 
4174     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4175         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4176     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4177         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4178 
4179     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4180         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4181     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4182         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4183 
4184     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4185     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4186                                .addReg(CarryReg, RegState::Define)
4187                                .add(SrcReg0Sub0)
4188                                .add(SrcReg1Sub0)
4189                                .addImm(0); // clamp bit
4190 
4191     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4192     MachineInstr *HiHalf =
4193         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4194             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4195             .add(SrcReg0Sub1)
4196             .add(SrcReg1Sub1)
4197             .addReg(CarryReg, RegState::Kill)
4198             .addImm(0); // clamp bit
4199 
4200     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4201         .addReg(DestSub0)
4202         .addImm(AMDGPU::sub0)
4203         .addReg(DestSub1)
4204         .addImm(AMDGPU::sub1);
4205     TII->legalizeOperands(*LoHalf);
4206     TII->legalizeOperands(*HiHalf);
4207     MI.eraseFromParent();
4208     return BB;
4209   }
4210   case AMDGPU::S_ADD_CO_PSEUDO:
4211   case AMDGPU::S_SUB_CO_PSEUDO: {
4212     // This pseudo has a chance to be selected
4213     // only from uniform add/subcarry node. All the VGPR operands
4214     // therefore assumed to be splat vectors.
4215     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4216     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4217     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4218     MachineBasicBlock::iterator MII = MI;
4219     const DebugLoc &DL = MI.getDebugLoc();
4220     MachineOperand &Dest = MI.getOperand(0);
4221     MachineOperand &CarryDest = MI.getOperand(1);
4222     MachineOperand &Src0 = MI.getOperand(2);
4223     MachineOperand &Src1 = MI.getOperand(3);
4224     MachineOperand &Src2 = MI.getOperand(4);
4225     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4226                        ? AMDGPU::S_ADDC_U32
4227                        : AMDGPU::S_SUBB_U32;
4228     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4229       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4230       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4231           .addReg(Src0.getReg());
4232       Src0.setReg(RegOp0);
4233     }
4234     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4235       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4236       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4237           .addReg(Src1.getReg());
4238       Src1.setReg(RegOp1);
4239     }
4240     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4241     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4242       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4243           .addReg(Src2.getReg());
4244       Src2.setReg(RegOp2);
4245     }
4246 
4247     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4248     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4249     assert(WaveSize == 64 || WaveSize == 32);
4250 
4251     if (WaveSize == 64) {
4252       if (ST.hasScalarCompareEq64()) {
4253         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4254             .addReg(Src2.getReg())
4255             .addImm(0);
4256       } else {
4257         const TargetRegisterClass *SubRC =
4258             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4259         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4260             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4261         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4262             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4263         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4264 
4265         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4266             .add(Src2Sub0)
4267             .add(Src2Sub1);
4268 
4269         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4270             .addReg(Src2_32, RegState::Kill)
4271             .addImm(0);
4272       }
4273     } else {
4274       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4275           .addReg(Src2.getReg())
4276           .addImm(0);
4277     }
4278 
4279     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4280 
4281     unsigned SelOpc =
4282         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4283 
4284     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4285         .addImm(-1)
4286         .addImm(0);
4287 
4288     MI.eraseFromParent();
4289     return BB;
4290   }
4291   case AMDGPU::SI_INIT_M0: {
4292     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4293             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4294         .add(MI.getOperand(0));
4295     MI.eraseFromParent();
4296     return BB;
4297   }
4298   case AMDGPU::GET_GROUPSTATICSIZE: {
4299     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4300            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4301     DebugLoc DL = MI.getDebugLoc();
4302     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4303         .add(MI.getOperand(0))
4304         .addImm(MFI->getLDSSize());
4305     MI.eraseFromParent();
4306     return BB;
4307   }
4308   case AMDGPU::SI_INDIRECT_SRC_V1:
4309   case AMDGPU::SI_INDIRECT_SRC_V2:
4310   case AMDGPU::SI_INDIRECT_SRC_V4:
4311   case AMDGPU::SI_INDIRECT_SRC_V8:
4312   case AMDGPU::SI_INDIRECT_SRC_V16:
4313   case AMDGPU::SI_INDIRECT_SRC_V32:
4314     return emitIndirectSrc(MI, *BB, *getSubtarget());
4315   case AMDGPU::SI_INDIRECT_DST_V1:
4316   case AMDGPU::SI_INDIRECT_DST_V2:
4317   case AMDGPU::SI_INDIRECT_DST_V4:
4318   case AMDGPU::SI_INDIRECT_DST_V8:
4319   case AMDGPU::SI_INDIRECT_DST_V16:
4320   case AMDGPU::SI_INDIRECT_DST_V32:
4321     return emitIndirectDst(MI, *BB, *getSubtarget());
4322   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4323   case AMDGPU::SI_KILL_I1_PSEUDO:
4324     return splitKillBlock(MI, BB);
4325   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4326     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4327     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4328     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4329 
4330     Register Dst = MI.getOperand(0).getReg();
4331     Register Src0 = MI.getOperand(1).getReg();
4332     Register Src1 = MI.getOperand(2).getReg();
4333     const DebugLoc &DL = MI.getDebugLoc();
4334     Register SrcCond = MI.getOperand(3).getReg();
4335 
4336     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4337     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4338     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4339     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4340 
4341     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4342       .addReg(SrcCond);
4343     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4344       .addImm(0)
4345       .addReg(Src0, 0, AMDGPU::sub0)
4346       .addImm(0)
4347       .addReg(Src1, 0, AMDGPU::sub0)
4348       .addReg(SrcCondCopy);
4349     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4350       .addImm(0)
4351       .addReg(Src0, 0, AMDGPU::sub1)
4352       .addImm(0)
4353       .addReg(Src1, 0, AMDGPU::sub1)
4354       .addReg(SrcCondCopy);
4355 
4356     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4357       .addReg(DstLo)
4358       .addImm(AMDGPU::sub0)
4359       .addReg(DstHi)
4360       .addImm(AMDGPU::sub1);
4361     MI.eraseFromParent();
4362     return BB;
4363   }
4364   case AMDGPU::SI_BR_UNDEF: {
4365     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4366     const DebugLoc &DL = MI.getDebugLoc();
4367     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4368                            .add(MI.getOperand(0));
4369     Br->getOperand(1).setIsUndef(true); // read undef SCC
4370     MI.eraseFromParent();
4371     return BB;
4372   }
4373   case AMDGPU::ADJCALLSTACKUP:
4374   case AMDGPU::ADJCALLSTACKDOWN: {
4375     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4376     MachineInstrBuilder MIB(*MF, &MI);
4377     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4378        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4379     return BB;
4380   }
4381   case AMDGPU::SI_CALL_ISEL: {
4382     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4383     const DebugLoc &DL = MI.getDebugLoc();
4384 
4385     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4386 
4387     MachineInstrBuilder MIB;
4388     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4389 
4390     for (const MachineOperand &MO : MI.operands())
4391       MIB.add(MO);
4392 
4393     MIB.cloneMemRefs(MI);
4394     MI.eraseFromParent();
4395     return BB;
4396   }
4397   case AMDGPU::V_ADD_CO_U32_e32:
4398   case AMDGPU::V_SUB_CO_U32_e32:
4399   case AMDGPU::V_SUBREV_CO_U32_e32: {
4400     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4401     const DebugLoc &DL = MI.getDebugLoc();
4402     unsigned Opc = MI.getOpcode();
4403 
4404     bool NeedClampOperand = false;
4405     if (TII->pseudoToMCOpcode(Opc) == -1) {
4406       Opc = AMDGPU::getVOPe64(Opc);
4407       NeedClampOperand = true;
4408     }
4409 
4410     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4411     if (TII->isVOP3(*I)) {
4412       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4413       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4414       I.addReg(TRI->getVCC(), RegState::Define);
4415     }
4416     I.add(MI.getOperand(1))
4417      .add(MI.getOperand(2));
4418     if (NeedClampOperand)
4419       I.addImm(0); // clamp bit for e64 encoding
4420 
4421     TII->legalizeOperands(*I);
4422 
4423     MI.eraseFromParent();
4424     return BB;
4425   }
4426   case AMDGPU::V_ADDC_U32_e32:
4427   case AMDGPU::V_SUBB_U32_e32:
4428   case AMDGPU::V_SUBBREV_U32_e32:
4429     // These instructions have an implicit use of vcc which counts towards the
4430     // constant bus limit.
4431     TII->legalizeOperands(MI);
4432     return BB;
4433   case AMDGPU::DS_GWS_INIT:
4434   case AMDGPU::DS_GWS_SEMA_BR:
4435   case AMDGPU::DS_GWS_BARRIER:
4436     if (Subtarget->needsAlignedVGPRs()) {
4437       // Add implicit aligned super-reg to force alignment on the data operand.
4438       const DebugLoc &DL = MI.getDebugLoc();
4439       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4440       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4441       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4442       Register DataReg = Op->getReg();
4443       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4444       Register Undef = MRI.createVirtualRegister(
4445           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4446       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4447       Register NewVR =
4448           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4449                                            : &AMDGPU::VReg_64_Align2RegClass);
4450       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4451           .addReg(DataReg, 0, Op->getSubReg())
4452           .addImm(AMDGPU::sub0)
4453           .addReg(Undef)
4454           .addImm(AMDGPU::sub1);
4455       Op->setReg(NewVR);
4456       Op->setSubReg(AMDGPU::sub0);
4457       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4458     }
4459     LLVM_FALLTHROUGH;
4460   case AMDGPU::DS_GWS_SEMA_V:
4461   case AMDGPU::DS_GWS_SEMA_P:
4462   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4463     // A s_waitcnt 0 is required to be the instruction immediately following.
4464     if (getSubtarget()->hasGWSAutoReplay()) {
4465       bundleInstWithWaitcnt(MI);
4466       return BB;
4467     }
4468 
4469     return emitGWSMemViolTestLoop(MI, BB);
4470   case AMDGPU::S_SETREG_B32: {
4471     // Try to optimize cases that only set the denormal mode or rounding mode.
4472     //
4473     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4474     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4475     // instead.
4476     //
4477     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4478     // allow you to have a no side effect instruction in the output of a
4479     // sideeffecting pattern.
4480     unsigned ID, Offset, Width;
4481     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4482     if (ID != AMDGPU::Hwreg::ID_MODE)
4483       return BB;
4484 
4485     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4486     const unsigned SetMask = WidthMask << Offset;
4487 
4488     if (getSubtarget()->hasDenormModeInst()) {
4489       unsigned SetDenormOp = 0;
4490       unsigned SetRoundOp = 0;
4491 
4492       // The dedicated instructions can only set the whole denorm or round mode
4493       // at once, not a subset of bits in either.
4494       if (SetMask ==
4495           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4496         // If this fully sets both the round and denorm mode, emit the two
4497         // dedicated instructions for these.
4498         SetRoundOp = AMDGPU::S_ROUND_MODE;
4499         SetDenormOp = AMDGPU::S_DENORM_MODE;
4500       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4501         SetRoundOp = AMDGPU::S_ROUND_MODE;
4502       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4503         SetDenormOp = AMDGPU::S_DENORM_MODE;
4504       }
4505 
4506       if (SetRoundOp || SetDenormOp) {
4507         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4508         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4509         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4510           unsigned ImmVal = Def->getOperand(1).getImm();
4511           if (SetRoundOp) {
4512             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4513                 .addImm(ImmVal & 0xf);
4514 
4515             // If we also have the denorm mode, get just the denorm mode bits.
4516             ImmVal >>= 4;
4517           }
4518 
4519           if (SetDenormOp) {
4520             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4521                 .addImm(ImmVal & 0xf);
4522           }
4523 
4524           MI.eraseFromParent();
4525           return BB;
4526         }
4527       }
4528     }
4529 
4530     // If only FP bits are touched, used the no side effects pseudo.
4531     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4532                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4533       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4534 
4535     return BB;
4536   }
4537   default:
4538     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4539   }
4540 }
4541 
4542 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4543   return isTypeLegal(VT.getScalarType());
4544 }
4545 
4546 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4547   // This currently forces unfolding various combinations of fsub into fma with
4548   // free fneg'd operands. As long as we have fast FMA (controlled by
4549   // isFMAFasterThanFMulAndFAdd), we should perform these.
4550 
4551   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4552   // most of these combines appear to be cycle neutral but save on instruction
4553   // count / code size.
4554   return true;
4555 }
4556 
4557 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4558 
4559 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4560                                          EVT VT) const {
4561   if (!VT.isVector()) {
4562     return MVT::i1;
4563   }
4564   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4565 }
4566 
4567 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4568   // TODO: Should i16 be used always if legal? For now it would force VALU
4569   // shifts.
4570   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4571 }
4572 
4573 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4574   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4575              ? Ty.changeElementSize(16)
4576              : Ty.changeElementSize(32);
4577 }
4578 
4579 // Answering this is somewhat tricky and depends on the specific device which
4580 // have different rates for fma or all f64 operations.
4581 //
4582 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4583 // regardless of which device (although the number of cycles differs between
4584 // devices), so it is always profitable for f64.
4585 //
4586 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4587 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4588 // which we can always do even without fused FP ops since it returns the same
4589 // result as the separate operations and since it is always full
4590 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4591 // however does not support denormals, so we do report fma as faster if we have
4592 // a fast fma device and require denormals.
4593 //
4594 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4595                                                   EVT VT) const {
4596   VT = VT.getScalarType();
4597 
4598   switch (VT.getSimpleVT().SimpleTy) {
4599   case MVT::f32: {
4600     // If mad is not available this depends only on if f32 fma is full rate.
4601     if (!Subtarget->hasMadMacF32Insts())
4602       return Subtarget->hasFastFMAF32();
4603 
4604     // Otherwise f32 mad is always full rate and returns the same result as
4605     // the separate operations so should be preferred over fma.
4606     // However does not support denormals.
4607     if (hasFP32Denormals(MF))
4608       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4609 
4610     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4611     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4612   }
4613   case MVT::f64:
4614     return true;
4615   case MVT::f16:
4616     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4617   default:
4618     break;
4619   }
4620 
4621   return false;
4622 }
4623 
4624 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4625                                                   LLT Ty) const {
4626   switch (Ty.getScalarSizeInBits()) {
4627   case 16:
4628     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4629   case 32:
4630     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4631   case 64:
4632     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4633   default:
4634     break;
4635   }
4636 
4637   return false;
4638 }
4639 
4640 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4641   if (!Ty.isScalar())
4642     return false;
4643 
4644   if (Ty.getScalarSizeInBits() == 16)
4645     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4646   if (Ty.getScalarSizeInBits() == 32)
4647     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4648 
4649   return false;
4650 }
4651 
4652 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4653                                    const SDNode *N) const {
4654   // TODO: Check future ftz flag
4655   // v_mad_f32/v_mac_f32 do not support denormals.
4656   EVT VT = N->getValueType(0);
4657   if (VT == MVT::f32)
4658     return Subtarget->hasMadMacF32Insts() &&
4659            !hasFP32Denormals(DAG.getMachineFunction());
4660   if (VT == MVT::f16) {
4661     return Subtarget->hasMadF16() &&
4662            !hasFP64FP16Denormals(DAG.getMachineFunction());
4663   }
4664 
4665   return false;
4666 }
4667 
4668 //===----------------------------------------------------------------------===//
4669 // Custom DAG Lowering Operations
4670 //===----------------------------------------------------------------------===//
4671 
4672 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4673 // wider vector type is legal.
4674 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4675                                              SelectionDAG &DAG) const {
4676   unsigned Opc = Op.getOpcode();
4677   EVT VT = Op.getValueType();
4678   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4679 
4680   SDValue Lo, Hi;
4681   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4682 
4683   SDLoc SL(Op);
4684   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4685                              Op->getFlags());
4686   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4687                              Op->getFlags());
4688 
4689   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4690 }
4691 
4692 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4693 // wider vector type is legal.
4694 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4695                                               SelectionDAG &DAG) const {
4696   unsigned Opc = Op.getOpcode();
4697   EVT VT = Op.getValueType();
4698   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4699          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4700          VT == MVT::v16f32 || VT == MVT::v32f32);
4701 
4702   SDValue Lo0, Hi0;
4703   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4704   SDValue Lo1, Hi1;
4705   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4706 
4707   SDLoc SL(Op);
4708 
4709   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4710                              Op->getFlags());
4711   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4712                              Op->getFlags());
4713 
4714   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4715 }
4716 
4717 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4718                                               SelectionDAG &DAG) const {
4719   unsigned Opc = Op.getOpcode();
4720   EVT VT = Op.getValueType();
4721   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4722          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4723          VT == MVT::v16f32 || VT == MVT::v32f32);
4724 
4725   SDValue Lo0, Hi0;
4726   SDValue Op0 = Op.getOperand(0);
4727   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4728                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4729                          : std::make_pair(Op0, Op0);
4730   SDValue Lo1, Hi1;
4731   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4732   SDValue Lo2, Hi2;
4733   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4734 
4735   SDLoc SL(Op);
4736   auto ResVT = DAG.GetSplitDestVTs(VT);
4737 
4738   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4739                              Op->getFlags());
4740   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4741                              Op->getFlags());
4742 
4743   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4744 }
4745 
4746 
4747 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4748   switch (Op.getOpcode()) {
4749   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4750   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4751   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4752   case ISD::LOAD: {
4753     SDValue Result = LowerLOAD(Op, DAG);
4754     assert((!Result.getNode() ||
4755             Result.getNode()->getNumValues() == 2) &&
4756            "Load should return a value and a chain");
4757     return Result;
4758   }
4759 
4760   case ISD::FSIN:
4761   case ISD::FCOS:
4762     return LowerTrig(Op, DAG);
4763   case ISD::SELECT: return LowerSELECT(Op, DAG);
4764   case ISD::FDIV: return LowerFDIV(Op, DAG);
4765   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4766   case ISD::STORE: return LowerSTORE(Op, DAG);
4767   case ISD::GlobalAddress: {
4768     MachineFunction &MF = DAG.getMachineFunction();
4769     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4770     return LowerGlobalAddress(MFI, Op, DAG);
4771   }
4772   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4773   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4774   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4775   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4776   case ISD::INSERT_SUBVECTOR:
4777     return lowerINSERT_SUBVECTOR(Op, DAG);
4778   case ISD::INSERT_VECTOR_ELT:
4779     return lowerINSERT_VECTOR_ELT(Op, DAG);
4780   case ISD::EXTRACT_VECTOR_ELT:
4781     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4782   case ISD::VECTOR_SHUFFLE:
4783     return lowerVECTOR_SHUFFLE(Op, DAG);
4784   case ISD::BUILD_VECTOR:
4785     return lowerBUILD_VECTOR(Op, DAG);
4786   case ISD::FP_ROUND:
4787     return lowerFP_ROUND(Op, DAG);
4788   case ISD::FPTRUNC_ROUND: {
4789     unsigned Opc;
4790     SDLoc DL(Op);
4791 
4792     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4793       return SDValue();
4794 
4795     // Get the rounding mode from the last operand
4796     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4797     if (RoundMode == (int)RoundingMode::TowardPositive)
4798       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4799     else if (RoundMode == (int)RoundingMode::TowardNegative)
4800       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4801     else
4802       return SDValue();
4803 
4804     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4805   }
4806   case ISD::TRAP:
4807     return lowerTRAP(Op, DAG);
4808   case ISD::DEBUGTRAP:
4809     return lowerDEBUGTRAP(Op, DAG);
4810   case ISD::FABS:
4811   case ISD::FNEG:
4812   case ISD::FCANONICALIZE:
4813   case ISD::BSWAP:
4814     return splitUnaryVectorOp(Op, DAG);
4815   case ISD::FMINNUM:
4816   case ISD::FMAXNUM:
4817     return lowerFMINNUM_FMAXNUM(Op, DAG);
4818   case ISD::FMA:
4819     return splitTernaryVectorOp(Op, DAG);
4820   case ISD::FP_TO_SINT:
4821   case ISD::FP_TO_UINT:
4822     return LowerFP_TO_INT(Op, DAG);
4823   case ISD::SHL:
4824   case ISD::SRA:
4825   case ISD::SRL:
4826   case ISD::ADD:
4827   case ISD::SUB:
4828   case ISD::MUL:
4829   case ISD::SMIN:
4830   case ISD::SMAX:
4831   case ISD::UMIN:
4832   case ISD::UMAX:
4833   case ISD::FADD:
4834   case ISD::FMUL:
4835   case ISD::FMINNUM_IEEE:
4836   case ISD::FMAXNUM_IEEE:
4837   case ISD::UADDSAT:
4838   case ISD::USUBSAT:
4839   case ISD::SADDSAT:
4840   case ISD::SSUBSAT:
4841     return splitBinaryVectorOp(Op, DAG);
4842   case ISD::SMULO:
4843   case ISD::UMULO:
4844     return lowerXMULO(Op, DAG);
4845   case ISD::SMUL_LOHI:
4846   case ISD::UMUL_LOHI:
4847     return lowerXMUL_LOHI(Op, DAG);
4848   case ISD::DYNAMIC_STACKALLOC:
4849     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4850   }
4851   return SDValue();
4852 }
4853 
4854 // Used for D16: Casts the result of an instruction into the right vector,
4855 // packs values if loads return unpacked values.
4856 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4857                                        const SDLoc &DL,
4858                                        SelectionDAG &DAG, bool Unpacked) {
4859   if (!LoadVT.isVector())
4860     return Result;
4861 
4862   // Cast back to the original packed type or to a larger type that is a
4863   // multiple of 32 bit for D16. Widening the return type is a required for
4864   // legalization.
4865   EVT FittingLoadVT = LoadVT;
4866   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4867     FittingLoadVT =
4868         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4869                          LoadVT.getVectorNumElements() + 1);
4870   }
4871 
4872   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4873     // Truncate to v2i16/v4i16.
4874     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4875 
4876     // Workaround legalizer not scalarizing truncate after vector op
4877     // legalization but not creating intermediate vector trunc.
4878     SmallVector<SDValue, 4> Elts;
4879     DAG.ExtractVectorElements(Result, Elts);
4880     for (SDValue &Elt : Elts)
4881       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4882 
4883     // Pad illegal v1i16/v3fi6 to v4i16
4884     if ((LoadVT.getVectorNumElements() % 2) == 1)
4885       Elts.push_back(DAG.getUNDEF(MVT::i16));
4886 
4887     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4888 
4889     // Bitcast to original type (v2f16/v4f16).
4890     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4891   }
4892 
4893   // Cast back to the original packed type.
4894   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4895 }
4896 
4897 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4898                                               MemSDNode *M,
4899                                               SelectionDAG &DAG,
4900                                               ArrayRef<SDValue> Ops,
4901                                               bool IsIntrinsic) const {
4902   SDLoc DL(M);
4903 
4904   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4905   EVT LoadVT = M->getValueType(0);
4906 
4907   EVT EquivLoadVT = LoadVT;
4908   if (LoadVT.isVector()) {
4909     if (Unpacked) {
4910       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4911                                      LoadVT.getVectorNumElements());
4912     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4913       // Widen v3f16 to legal type
4914       EquivLoadVT =
4915           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4916                            LoadVT.getVectorNumElements() + 1);
4917     }
4918   }
4919 
4920   // Change from v4f16/v2f16 to EquivLoadVT.
4921   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4922 
4923   SDValue Load
4924     = DAG.getMemIntrinsicNode(
4925       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4926       VTList, Ops, M->getMemoryVT(),
4927       M->getMemOperand());
4928 
4929   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4930 
4931   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4932 }
4933 
4934 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4935                                              SelectionDAG &DAG,
4936                                              ArrayRef<SDValue> Ops) const {
4937   SDLoc DL(M);
4938   EVT LoadVT = M->getValueType(0);
4939   EVT EltType = LoadVT.getScalarType();
4940   EVT IntVT = LoadVT.changeTypeToInteger();
4941 
4942   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4943 
4944   unsigned Opc =
4945       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4946 
4947   if (IsD16) {
4948     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4949   }
4950 
4951   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4952   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4953     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4954 
4955   if (isTypeLegal(LoadVT)) {
4956     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4957                                M->getMemOperand(), DAG);
4958   }
4959 
4960   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4961   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4962   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4963                                         M->getMemOperand(), DAG);
4964   return DAG.getMergeValues(
4965       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4966       DL);
4967 }
4968 
4969 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4970                                   SDNode *N, SelectionDAG &DAG) {
4971   EVT VT = N->getValueType(0);
4972   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4973   unsigned CondCode = CD->getZExtValue();
4974   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4975     return DAG.getUNDEF(VT);
4976 
4977   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4978 
4979   SDValue LHS = N->getOperand(1);
4980   SDValue RHS = N->getOperand(2);
4981 
4982   SDLoc DL(N);
4983 
4984   EVT CmpVT = LHS.getValueType();
4985   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4986     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4987       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4988     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4989     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4990   }
4991 
4992   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4993 
4994   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4995   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4996 
4997   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4998                               DAG.getCondCode(CCOpcode));
4999   if (VT.bitsEq(CCVT))
5000     return SetCC;
5001   return DAG.getZExtOrTrunc(SetCC, DL, VT);
5002 }
5003 
5004 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
5005                                   SDNode *N, SelectionDAG &DAG) {
5006   EVT VT = N->getValueType(0);
5007   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
5008 
5009   unsigned CondCode = CD->getZExtValue();
5010   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
5011     return DAG.getUNDEF(VT);
5012 
5013   SDValue Src0 = N->getOperand(1);
5014   SDValue Src1 = N->getOperand(2);
5015   EVT CmpVT = Src0.getValueType();
5016   SDLoc SL(N);
5017 
5018   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5019     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5020     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5021   }
5022 
5023   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5024   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5025   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5026   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5027   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5028                               Src1, DAG.getCondCode(CCOpcode));
5029   if (VT.bitsEq(CCVT))
5030     return SetCC;
5031   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5032 }
5033 
5034 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5035                                     SelectionDAG &DAG) {
5036   EVT VT = N->getValueType(0);
5037   SDValue Src = N->getOperand(1);
5038   SDLoc SL(N);
5039 
5040   if (Src.getOpcode() == ISD::SETCC) {
5041     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5042     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5043                        Src.getOperand(1), Src.getOperand(2));
5044   }
5045   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5046     // (ballot 0) -> 0
5047     if (Arg->isZero())
5048       return DAG.getConstant(0, SL, VT);
5049 
5050     // (ballot 1) -> EXEC/EXEC_LO
5051     if (Arg->isOne()) {
5052       Register Exec;
5053       if (VT.getScalarSizeInBits() == 32)
5054         Exec = AMDGPU::EXEC_LO;
5055       else if (VT.getScalarSizeInBits() == 64)
5056         Exec = AMDGPU::EXEC;
5057       else
5058         return SDValue();
5059 
5060       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5061     }
5062   }
5063 
5064   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5065   // ISD::SETNE)
5066   return DAG.getNode(
5067       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5068       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5069 }
5070 
5071 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5072                                           SmallVectorImpl<SDValue> &Results,
5073                                           SelectionDAG &DAG) const {
5074   switch (N->getOpcode()) {
5075   case ISD::INSERT_VECTOR_ELT: {
5076     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5077       Results.push_back(Res);
5078     return;
5079   }
5080   case ISD::EXTRACT_VECTOR_ELT: {
5081     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5082       Results.push_back(Res);
5083     return;
5084   }
5085   case ISD::INTRINSIC_WO_CHAIN: {
5086     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5087     switch (IID) {
5088     case Intrinsic::amdgcn_cvt_pkrtz: {
5089       SDValue Src0 = N->getOperand(1);
5090       SDValue Src1 = N->getOperand(2);
5091       SDLoc SL(N);
5092       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5093                                 Src0, Src1);
5094       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5095       return;
5096     }
5097     case Intrinsic::amdgcn_cvt_pknorm_i16:
5098     case Intrinsic::amdgcn_cvt_pknorm_u16:
5099     case Intrinsic::amdgcn_cvt_pk_i16:
5100     case Intrinsic::amdgcn_cvt_pk_u16: {
5101       SDValue Src0 = N->getOperand(1);
5102       SDValue Src1 = N->getOperand(2);
5103       SDLoc SL(N);
5104       unsigned Opcode;
5105 
5106       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5107         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5108       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5109         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5110       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5111         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5112       else
5113         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5114 
5115       EVT VT = N->getValueType(0);
5116       if (isTypeLegal(VT))
5117         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5118       else {
5119         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5120         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5121       }
5122       return;
5123     }
5124     }
5125     break;
5126   }
5127   case ISD::INTRINSIC_W_CHAIN: {
5128     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5129       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5130         // FIXME: Hacky
5131         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5132           Results.push_back(Res.getOperand(I));
5133         }
5134       } else {
5135         Results.push_back(Res);
5136         Results.push_back(Res.getValue(1));
5137       }
5138       return;
5139     }
5140 
5141     break;
5142   }
5143   case ISD::SELECT: {
5144     SDLoc SL(N);
5145     EVT VT = N->getValueType(0);
5146     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5147     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5148     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5149 
5150     EVT SelectVT = NewVT;
5151     if (NewVT.bitsLT(MVT::i32)) {
5152       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5153       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5154       SelectVT = MVT::i32;
5155     }
5156 
5157     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5158                                     N->getOperand(0), LHS, RHS);
5159 
5160     if (NewVT != SelectVT)
5161       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5162     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5163     return;
5164   }
5165   case ISD::FNEG: {
5166     if (N->getValueType(0) != MVT::v2f16)
5167       break;
5168 
5169     SDLoc SL(N);
5170     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5171 
5172     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5173                              BC,
5174                              DAG.getConstant(0x80008000, SL, MVT::i32));
5175     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5176     return;
5177   }
5178   case ISD::FABS: {
5179     if (N->getValueType(0) != MVT::v2f16)
5180       break;
5181 
5182     SDLoc SL(N);
5183     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5184 
5185     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5186                              BC,
5187                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5188     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5189     return;
5190   }
5191   default:
5192     break;
5193   }
5194 }
5195 
5196 /// Helper function for LowerBRCOND
5197 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5198 
5199   SDNode *Parent = Value.getNode();
5200   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5201        I != E; ++I) {
5202 
5203     if (I.getUse().get() != Value)
5204       continue;
5205 
5206     if (I->getOpcode() == Opcode)
5207       return *I;
5208   }
5209   return nullptr;
5210 }
5211 
5212 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5213   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5214     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5215     case Intrinsic::amdgcn_if:
5216       return AMDGPUISD::IF;
5217     case Intrinsic::amdgcn_else:
5218       return AMDGPUISD::ELSE;
5219     case Intrinsic::amdgcn_loop:
5220       return AMDGPUISD::LOOP;
5221     case Intrinsic::amdgcn_end_cf:
5222       llvm_unreachable("should not occur");
5223     default:
5224       return 0;
5225     }
5226   }
5227 
5228   // break, if_break, else_break are all only used as inputs to loop, not
5229   // directly as branch conditions.
5230   return 0;
5231 }
5232 
5233 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5234   const Triple &TT = getTargetMachine().getTargetTriple();
5235   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5236           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5237          AMDGPU::shouldEmitConstantsToTextSection(TT);
5238 }
5239 
5240 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5241   // FIXME: Either avoid relying on address space here or change the default
5242   // address space for functions to avoid the explicit check.
5243   return (GV->getValueType()->isFunctionTy() ||
5244           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5245          !shouldEmitFixup(GV) &&
5246          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5247 }
5248 
5249 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5250   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5251 }
5252 
5253 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5254   if (!GV->hasExternalLinkage())
5255     return true;
5256 
5257   const auto OS = getTargetMachine().getTargetTriple().getOS();
5258   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5259 }
5260 
5261 /// This transforms the control flow intrinsics to get the branch destination as
5262 /// last parameter, also switches branch target with BR if the need arise
5263 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5264                                       SelectionDAG &DAG) const {
5265   SDLoc DL(BRCOND);
5266 
5267   SDNode *Intr = BRCOND.getOperand(1).getNode();
5268   SDValue Target = BRCOND.getOperand(2);
5269   SDNode *BR = nullptr;
5270   SDNode *SetCC = nullptr;
5271 
5272   if (Intr->getOpcode() == ISD::SETCC) {
5273     // As long as we negate the condition everything is fine
5274     SetCC = Intr;
5275     Intr = SetCC->getOperand(0).getNode();
5276 
5277   } else {
5278     // Get the target from BR if we don't negate the condition
5279     BR = findUser(BRCOND, ISD::BR);
5280     assert(BR && "brcond missing unconditional branch user");
5281     Target = BR->getOperand(1);
5282   }
5283 
5284   unsigned CFNode = isCFIntrinsic(Intr);
5285   if (CFNode == 0) {
5286     // This is a uniform branch so we don't need to legalize.
5287     return BRCOND;
5288   }
5289 
5290   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5291                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5292 
5293   assert(!SetCC ||
5294         (SetCC->getConstantOperandVal(1) == 1 &&
5295          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5296                                                              ISD::SETNE));
5297 
5298   // operands of the new intrinsic call
5299   SmallVector<SDValue, 4> Ops;
5300   if (HaveChain)
5301     Ops.push_back(BRCOND.getOperand(0));
5302 
5303   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5304   Ops.push_back(Target);
5305 
5306   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5307 
5308   // build the new intrinsic call
5309   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5310 
5311   if (!HaveChain) {
5312     SDValue Ops[] =  {
5313       SDValue(Result, 0),
5314       BRCOND.getOperand(0)
5315     };
5316 
5317     Result = DAG.getMergeValues(Ops, DL).getNode();
5318   }
5319 
5320   if (BR) {
5321     // Give the branch instruction our target
5322     SDValue Ops[] = {
5323       BR->getOperand(0),
5324       BRCOND.getOperand(2)
5325     };
5326     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5327     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5328   }
5329 
5330   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5331 
5332   // Copy the intrinsic results to registers
5333   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5334     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5335     if (!CopyToReg)
5336       continue;
5337 
5338     Chain = DAG.getCopyToReg(
5339       Chain, DL,
5340       CopyToReg->getOperand(1),
5341       SDValue(Result, i - 1),
5342       SDValue());
5343 
5344     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5345   }
5346 
5347   // Remove the old intrinsic from the chain
5348   DAG.ReplaceAllUsesOfValueWith(
5349     SDValue(Intr, Intr->getNumValues() - 1),
5350     Intr->getOperand(0));
5351 
5352   return Chain;
5353 }
5354 
5355 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5356                                           SelectionDAG &DAG) const {
5357   MVT VT = Op.getSimpleValueType();
5358   SDLoc DL(Op);
5359   // Checking the depth
5360   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5361     return DAG.getConstant(0, DL, VT);
5362 
5363   MachineFunction &MF = DAG.getMachineFunction();
5364   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5365   // Check for kernel and shader functions
5366   if (Info->isEntryFunction())
5367     return DAG.getConstant(0, DL, VT);
5368 
5369   MachineFrameInfo &MFI = MF.getFrameInfo();
5370   // There is a call to @llvm.returnaddress in this function
5371   MFI.setReturnAddressIsTaken(true);
5372 
5373   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5374   // Get the return address reg and mark it as an implicit live-in
5375   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5376 
5377   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5378 }
5379 
5380 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5381                                             SDValue Op,
5382                                             const SDLoc &DL,
5383                                             EVT VT) const {
5384   return Op.getValueType().bitsLE(VT) ?
5385       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5386     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5387                 DAG.getTargetConstant(0, DL, MVT::i32));
5388 }
5389 
5390 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5391   assert(Op.getValueType() == MVT::f16 &&
5392          "Do not know how to custom lower FP_ROUND for non-f16 type");
5393 
5394   SDValue Src = Op.getOperand(0);
5395   EVT SrcVT = Src.getValueType();
5396   if (SrcVT != MVT::f64)
5397     return Op;
5398 
5399   SDLoc DL(Op);
5400 
5401   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5402   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5403   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5404 }
5405 
5406 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5407                                                SelectionDAG &DAG) const {
5408   EVT VT = Op.getValueType();
5409   const MachineFunction &MF = DAG.getMachineFunction();
5410   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5411   bool IsIEEEMode = Info->getMode().IEEE;
5412 
5413   // FIXME: Assert during selection that this is only selected for
5414   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5415   // mode functions, but this happens to be OK since it's only done in cases
5416   // where there is known no sNaN.
5417   if (IsIEEEMode)
5418     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5419 
5420   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5421     return splitBinaryVectorOp(Op, DAG);
5422   return Op;
5423 }
5424 
5425 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5426   EVT VT = Op.getValueType();
5427   SDLoc SL(Op);
5428   SDValue LHS = Op.getOperand(0);
5429   SDValue RHS = Op.getOperand(1);
5430   bool isSigned = Op.getOpcode() == ISD::SMULO;
5431 
5432   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5433     const APInt &C = RHSC->getAPIntValue();
5434     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5435     if (C.isPowerOf2()) {
5436       // smulo(x, signed_min) is same as umulo(x, signed_min).
5437       bool UseArithShift = isSigned && !C.isMinSignedValue();
5438       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5439       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5440       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5441           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5442                       SL, VT, Result, ShiftAmt),
5443           LHS, ISD::SETNE);
5444       return DAG.getMergeValues({ Result, Overflow }, SL);
5445     }
5446   }
5447 
5448   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5449   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5450                             SL, VT, LHS, RHS);
5451 
5452   SDValue Sign = isSigned
5453     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5454                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5455     : DAG.getConstant(0, SL, VT);
5456   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5457 
5458   return DAG.getMergeValues({ Result, Overflow }, SL);
5459 }
5460 
5461 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5462   if (Op->isDivergent()) {
5463     // Select to V_MAD_[IU]64_[IU]32.
5464     return Op;
5465   }
5466   if (Subtarget->hasSMulHi()) {
5467     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5468     return SDValue();
5469   }
5470   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5471   // calculate the high part, so we might as well do the whole thing with
5472   // V_MAD_[IU]64_[IU]32.
5473   return Op;
5474 }
5475 
5476 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5477   if (!Subtarget->isTrapHandlerEnabled() ||
5478       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5479     return lowerTrapEndpgm(Op, DAG);
5480 
5481   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5482     switch (*HsaAbiVer) {
5483     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5484     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5485       return lowerTrapHsaQueuePtr(Op, DAG);
5486     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5487     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5488       return Subtarget->supportsGetDoorbellID() ?
5489           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5490     }
5491   }
5492 
5493   llvm_unreachable("Unknown trap handler");
5494 }
5495 
5496 SDValue SITargetLowering::lowerTrapEndpgm(
5497     SDValue Op, SelectionDAG &DAG) const {
5498   SDLoc SL(Op);
5499   SDValue Chain = Op.getOperand(0);
5500   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5501 }
5502 
5503 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5504     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5505   MachineFunction &MF = DAG.getMachineFunction();
5506   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5507   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5508   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5509   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5510                      MachineMemOperand::MODereferenceable |
5511                          MachineMemOperand::MOInvariant);
5512 }
5513 
5514 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5515     SDValue Op, SelectionDAG &DAG) const {
5516   SDLoc SL(Op);
5517   SDValue Chain = Op.getOperand(0);
5518 
5519   SDValue QueuePtr;
5520   // For code object version 5, QueuePtr is passed through implicit kernarg.
5521   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5522     QueuePtr =
5523         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5524   } else {
5525     MachineFunction &MF = DAG.getMachineFunction();
5526     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5527     Register UserSGPR = Info->getQueuePtrUserSGPR();
5528 
5529     if (UserSGPR == AMDGPU::NoRegister) {
5530       // We probably are in a function incorrectly marked with
5531       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5532       // trap, so just use a null pointer.
5533       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5534     } else {
5535       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5536                                       MVT::i64);
5537     }
5538   }
5539 
5540   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5541   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5542                                    QueuePtr, SDValue());
5543 
5544   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5545   SDValue Ops[] = {
5546     ToReg,
5547     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5548     SGPR01,
5549     ToReg.getValue(1)
5550   };
5551   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5552 }
5553 
5554 SDValue SITargetLowering::lowerTrapHsa(
5555     SDValue Op, SelectionDAG &DAG) const {
5556   SDLoc SL(Op);
5557   SDValue Chain = Op.getOperand(0);
5558 
5559   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5560   SDValue Ops[] = {
5561     Chain,
5562     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5563   };
5564   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5565 }
5566 
5567 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5568   SDLoc SL(Op);
5569   SDValue Chain = Op.getOperand(0);
5570   MachineFunction &MF = DAG.getMachineFunction();
5571 
5572   if (!Subtarget->isTrapHandlerEnabled() ||
5573       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5574     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5575                                      "debugtrap handler not supported",
5576                                      Op.getDebugLoc(),
5577                                      DS_Warning);
5578     LLVMContext &Ctx = MF.getFunction().getContext();
5579     Ctx.diagnose(NoTrap);
5580     return Chain;
5581   }
5582 
5583   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5584   SDValue Ops[] = {
5585     Chain,
5586     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5587   };
5588   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5589 }
5590 
5591 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5592                                              SelectionDAG &DAG) const {
5593   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5594   if (Subtarget->hasApertureRegs()) {
5595     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5596         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5597         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5598     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5599         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5600         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5601     unsigned Encoding =
5602         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5603         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5604         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5605 
5606     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5607     SDValue ApertureReg = SDValue(
5608         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5609     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5610     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5611   }
5612 
5613   // For code object version 5, private_base and shared_base are passed through
5614   // implicit kernargs.
5615   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5616     ImplicitParameter Param =
5617         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5618     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5619   }
5620 
5621   MachineFunction &MF = DAG.getMachineFunction();
5622   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5623   Register UserSGPR = Info->getQueuePtrUserSGPR();
5624   if (UserSGPR == AMDGPU::NoRegister) {
5625     // We probably are in a function incorrectly marked with
5626     // amdgpu-no-queue-ptr. This is undefined.
5627     return DAG.getUNDEF(MVT::i32);
5628   }
5629 
5630   SDValue QueuePtr = CreateLiveInRegister(
5631     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5632 
5633   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5634   // private_segment_aperture_base_hi.
5635   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5636 
5637   SDValue Ptr =
5638       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5639 
5640   // TODO: Use custom target PseudoSourceValue.
5641   // TODO: We should use the value from the IR intrinsic call, but it might not
5642   // be available and how do we get it?
5643   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5644   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5645                      commonAlignment(Align(64), StructOffset),
5646                      MachineMemOperand::MODereferenceable |
5647                          MachineMemOperand::MOInvariant);
5648 }
5649 
5650 /// Return true if the value is a known valid address, such that a null check is
5651 /// not necessary.
5652 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5653                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5654   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5655       isa<BasicBlockSDNode>(Val))
5656     return true;
5657 
5658   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5659     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5660 
5661   // TODO: Search through arithmetic, handle arguments and loads
5662   // marked nonnull.
5663   return false;
5664 }
5665 
5666 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5667                                              SelectionDAG &DAG) const {
5668   SDLoc SL(Op);
5669   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5670 
5671   SDValue Src = ASC->getOperand(0);
5672   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5673   unsigned SrcAS = ASC->getSrcAddressSpace();
5674 
5675   const AMDGPUTargetMachine &TM =
5676     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5677 
5678   // flat -> local/private
5679   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5680     unsigned DestAS = ASC->getDestAddressSpace();
5681 
5682     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5683         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5684       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5685 
5686       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5687         return Ptr;
5688 
5689       unsigned NullVal = TM.getNullPointerValue(DestAS);
5690       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5691       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5692 
5693       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5694                          SegmentNullPtr);
5695     }
5696   }
5697 
5698   // local/private -> flat
5699   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5700     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5701         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5702 
5703       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5704       SDValue CvtPtr =
5705           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5706       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5707 
5708       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5709         return CvtPtr;
5710 
5711       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5712       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5713 
5714       SDValue NonNull
5715         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5716 
5717       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5718                          FlatNullPtr);
5719     }
5720   }
5721 
5722   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5723       Op.getValueType() == MVT::i64) {
5724     const SIMachineFunctionInfo *Info =
5725         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5726     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5727     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5728     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5729   }
5730 
5731   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5732       Src.getValueType() == MVT::i64)
5733     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5734 
5735   // global <-> flat are no-ops and never emitted.
5736 
5737   const MachineFunction &MF = DAG.getMachineFunction();
5738   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5739     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5740   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5741 
5742   return DAG.getUNDEF(ASC->getValueType(0));
5743 }
5744 
5745 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5746 // the small vector and inserting them into the big vector. That is better than
5747 // the default expansion of doing it via a stack slot. Even though the use of
5748 // the stack slot would be optimized away afterwards, the stack slot itself
5749 // remains.
5750 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5751                                                 SelectionDAG &DAG) const {
5752   SDValue Vec = Op.getOperand(0);
5753   SDValue Ins = Op.getOperand(1);
5754   SDValue Idx = Op.getOperand(2);
5755   EVT VecVT = Vec.getValueType();
5756   EVT InsVT = Ins.getValueType();
5757   EVT EltVT = VecVT.getVectorElementType();
5758   unsigned InsNumElts = InsVT.getVectorNumElements();
5759   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5760   SDLoc SL(Op);
5761 
5762   for (unsigned I = 0; I != InsNumElts; ++I) {
5763     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5764                               DAG.getConstant(I, SL, MVT::i32));
5765     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5766                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5767   }
5768   return Vec;
5769 }
5770 
5771 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5772                                                  SelectionDAG &DAG) const {
5773   SDValue Vec = Op.getOperand(0);
5774   SDValue InsVal = Op.getOperand(1);
5775   SDValue Idx = Op.getOperand(2);
5776   EVT VecVT = Vec.getValueType();
5777   EVT EltVT = VecVT.getVectorElementType();
5778   unsigned VecSize = VecVT.getSizeInBits();
5779   unsigned EltSize = EltVT.getSizeInBits();
5780 
5781 
5782   assert(VecSize <= 64);
5783 
5784   unsigned NumElts = VecVT.getVectorNumElements();
5785   SDLoc SL(Op);
5786   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5787 
5788   if (NumElts == 4 && EltSize == 16 && KIdx) {
5789     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5790 
5791     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5792                                  DAG.getConstant(0, SL, MVT::i32));
5793     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5794                                  DAG.getConstant(1, SL, MVT::i32));
5795 
5796     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5797     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5798 
5799     unsigned Idx = KIdx->getZExtValue();
5800     bool InsertLo = Idx < 2;
5801     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5802       InsertLo ? LoVec : HiVec,
5803       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5804       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5805 
5806     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5807 
5808     SDValue Concat = InsertLo ?
5809       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5810       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5811 
5812     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5813   }
5814 
5815   if (isa<ConstantSDNode>(Idx))
5816     return SDValue();
5817 
5818   MVT IntVT = MVT::getIntegerVT(VecSize);
5819 
5820   // Avoid stack access for dynamic indexing.
5821   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5822 
5823   // Create a congruent vector with the target value in each element so that
5824   // the required element can be masked and ORed into the target vector.
5825   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5826                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5827 
5828   assert(isPowerOf2_32(EltSize));
5829   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5830 
5831   // Convert vector index to bit-index.
5832   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5833 
5834   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5835   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5836                             DAG.getConstant(0xffff, SL, IntVT),
5837                             ScaledIdx);
5838 
5839   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5840   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5841                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5842 
5843   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5844   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5845 }
5846 
5847 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5848                                                   SelectionDAG &DAG) const {
5849   SDLoc SL(Op);
5850 
5851   EVT ResultVT = Op.getValueType();
5852   SDValue Vec = Op.getOperand(0);
5853   SDValue Idx = Op.getOperand(1);
5854   EVT VecVT = Vec.getValueType();
5855   unsigned VecSize = VecVT.getSizeInBits();
5856   EVT EltVT = VecVT.getVectorElementType();
5857 
5858   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5859 
5860   // Make sure we do any optimizations that will make it easier to fold
5861   // source modifiers before obscuring it with bit operations.
5862 
5863   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5864   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5865     return Combined;
5866 
5867   if (VecSize == 128) {
5868     SDValue Lo, Hi;
5869     EVT LoVT, HiVT;
5870     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5871     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5872     Lo =
5873         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5874                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5875     Hi =
5876         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5877                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5878     EVT IdxVT = Idx.getValueType();
5879     unsigned NElem = VecVT.getVectorNumElements();
5880     assert(isPowerOf2_32(NElem));
5881     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5882     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5883     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5884     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5885   }
5886 
5887   assert(VecSize <= 64);
5888 
5889   unsigned EltSize = EltVT.getSizeInBits();
5890   assert(isPowerOf2_32(EltSize));
5891 
5892   MVT IntVT = MVT::getIntegerVT(VecSize);
5893   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5894 
5895   // Convert vector index to bit-index (* EltSize)
5896   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5897 
5898   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5899   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5900 
5901   if (ResultVT == MVT::f16) {
5902     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5903     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5904   }
5905 
5906   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5907 }
5908 
5909 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5910   assert(Elt % 2 == 0);
5911   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5912 }
5913 
5914 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5915                                               SelectionDAG &DAG) const {
5916   SDLoc SL(Op);
5917   EVT ResultVT = Op.getValueType();
5918   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5919 
5920   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5921   EVT EltVT = PackVT.getVectorElementType();
5922   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5923 
5924   // vector_shuffle <0,1,6,7> lhs, rhs
5925   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5926   //
5927   // vector_shuffle <6,7,2,3> lhs, rhs
5928   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5929   //
5930   // vector_shuffle <6,7,0,1> lhs, rhs
5931   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5932 
5933   // Avoid scalarizing when both halves are reading from consecutive elements.
5934   SmallVector<SDValue, 4> Pieces;
5935   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5936     if (elementPairIsContiguous(SVN->getMask(), I)) {
5937       const int Idx = SVN->getMaskElt(I);
5938       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5939       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5940       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5941                                     PackVT, SVN->getOperand(VecIdx),
5942                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5943       Pieces.push_back(SubVec);
5944     } else {
5945       const int Idx0 = SVN->getMaskElt(I);
5946       const int Idx1 = SVN->getMaskElt(I + 1);
5947       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5948       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5949       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5950       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5951 
5952       SDValue Vec0 = SVN->getOperand(VecIdx0);
5953       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5954                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5955 
5956       SDValue Vec1 = SVN->getOperand(VecIdx1);
5957       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5958                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5959       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5960     }
5961   }
5962 
5963   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5964 }
5965 
5966 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5967                                             SelectionDAG &DAG) const {
5968   SDLoc SL(Op);
5969   EVT VT = Op.getValueType();
5970 
5971   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5972       VT == MVT::v8i16 || VT == MVT::v8f16) {
5973     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5974                                   VT.getVectorNumElements() / 2);
5975     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5976 
5977     // Turn into pair of packed build_vectors.
5978     // TODO: Special case for constants that can be materialized with s_mov_b64.
5979     SmallVector<SDValue, 4> LoOps, HiOps;
5980     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5981       LoOps.push_back(Op.getOperand(I));
5982       HiOps.push_back(Op.getOperand(I + E));
5983     }
5984     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5985     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5986 
5987     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5988     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5989 
5990     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5991                                        { CastLo, CastHi });
5992     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5993   }
5994 
5995   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5996   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5997 
5998   SDValue Lo = Op.getOperand(0);
5999   SDValue Hi = Op.getOperand(1);
6000 
6001   // Avoid adding defined bits with the zero_extend.
6002   if (Hi.isUndef()) {
6003     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6004     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
6005     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
6006   }
6007 
6008   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
6009   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
6010 
6011   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
6012                               DAG.getConstant(16, SL, MVT::i32));
6013   if (Lo.isUndef())
6014     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
6015 
6016   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6017   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
6018 
6019   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
6020   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
6021 }
6022 
6023 bool
6024 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6025   // We can fold offsets for anything that doesn't require a GOT relocation.
6026   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
6027           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6028           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6029          !shouldEmitGOTReloc(GA->getGlobal());
6030 }
6031 
6032 static SDValue
6033 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6034                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6035                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6036   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6037   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6038   // lowered to the following code sequence:
6039   //
6040   // For constant address space:
6041   //   s_getpc_b64 s[0:1]
6042   //   s_add_u32 s0, s0, $symbol
6043   //   s_addc_u32 s1, s1, 0
6044   //
6045   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6046   //   a fixup or relocation is emitted to replace $symbol with a literal
6047   //   constant, which is a pc-relative offset from the encoding of the $symbol
6048   //   operand to the global variable.
6049   //
6050   // For global address space:
6051   //   s_getpc_b64 s[0:1]
6052   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6053   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6054   //
6055   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6056   //   fixups or relocations are emitted to replace $symbol@*@lo and
6057   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6058   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6059   //   operand to the global variable.
6060   //
6061   // What we want here is an offset from the value returned by s_getpc
6062   // (which is the address of the s_add_u32 instruction) to the global
6063   // variable, but since the encoding of $symbol starts 4 bytes after the start
6064   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6065   // small. This requires us to add 4 to the global variable offset in order to
6066   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6067   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6068   // instruction.
6069   SDValue PtrLo =
6070       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6071   SDValue PtrHi;
6072   if (GAFlags == SIInstrInfo::MO_NONE) {
6073     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6074   } else {
6075     PtrHi =
6076         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6077   }
6078   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6079 }
6080 
6081 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6082                                              SDValue Op,
6083                                              SelectionDAG &DAG) const {
6084   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6085   SDLoc DL(GSD);
6086   EVT PtrVT = Op.getValueType();
6087 
6088   const GlobalValue *GV = GSD->getGlobal();
6089   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6090        shouldUseLDSConstAddress(GV)) ||
6091       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6092       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6093     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6094         GV->hasExternalLinkage()) {
6095       Type *Ty = GV->getValueType();
6096       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6097       // zero-sized type in other languages to declare the dynamic shared
6098       // memory which size is not known at the compile time. They will be
6099       // allocated by the runtime and placed directly after the static
6100       // allocated ones. They all share the same offset.
6101       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6102         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6103         // Adjust alignment for that dynamic shared memory array.
6104         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6105         return SDValue(
6106             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6107       }
6108     }
6109     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6110   }
6111 
6112   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6113     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6114                                             SIInstrInfo::MO_ABS32_LO);
6115     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6116   }
6117 
6118   if (shouldEmitFixup(GV))
6119     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6120   else if (shouldEmitPCReloc(GV))
6121     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6122                                    SIInstrInfo::MO_REL32);
6123 
6124   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6125                                             SIInstrInfo::MO_GOTPCREL32);
6126 
6127   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6128   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6129   const DataLayout &DataLayout = DAG.getDataLayout();
6130   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6131   MachinePointerInfo PtrInfo
6132     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6133 
6134   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6135                      MachineMemOperand::MODereferenceable |
6136                          MachineMemOperand::MOInvariant);
6137 }
6138 
6139 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6140                                    const SDLoc &DL, SDValue V) const {
6141   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6142   // the destination register.
6143   //
6144   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6145   // so we will end up with redundant moves to m0.
6146   //
6147   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6148 
6149   // A Null SDValue creates a glue result.
6150   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6151                                   V, Chain);
6152   return SDValue(M0, 0);
6153 }
6154 
6155 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6156                                                  SDValue Op,
6157                                                  MVT VT,
6158                                                  unsigned Offset) const {
6159   SDLoc SL(Op);
6160   SDValue Param = lowerKernargMemParameter(
6161       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6162   // The local size values will have the hi 16-bits as zero.
6163   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6164                      DAG.getValueType(VT));
6165 }
6166 
6167 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6168                                         EVT VT) {
6169   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6170                                       "non-hsa intrinsic with hsa target",
6171                                       DL.getDebugLoc());
6172   DAG.getContext()->diagnose(BadIntrin);
6173   return DAG.getUNDEF(VT);
6174 }
6175 
6176 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6177                                          EVT VT) {
6178   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6179                                       "intrinsic not supported on subtarget",
6180                                       DL.getDebugLoc());
6181   DAG.getContext()->diagnose(BadIntrin);
6182   return DAG.getUNDEF(VT);
6183 }
6184 
6185 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6186                                     ArrayRef<SDValue> Elts) {
6187   assert(!Elts.empty());
6188   MVT Type;
6189   unsigned NumElts = Elts.size();
6190 
6191   if (NumElts <= 8) {
6192     Type = MVT::getVectorVT(MVT::f32, NumElts);
6193   } else {
6194     assert(Elts.size() <= 16);
6195     Type = MVT::v16f32;
6196     NumElts = 16;
6197   }
6198 
6199   SmallVector<SDValue, 16> VecElts(NumElts);
6200   for (unsigned i = 0; i < Elts.size(); ++i) {
6201     SDValue Elt = Elts[i];
6202     if (Elt.getValueType() != MVT::f32)
6203       Elt = DAG.getBitcast(MVT::f32, Elt);
6204     VecElts[i] = Elt;
6205   }
6206   for (unsigned i = Elts.size(); i < NumElts; ++i)
6207     VecElts[i] = DAG.getUNDEF(MVT::f32);
6208 
6209   if (NumElts == 1)
6210     return VecElts[0];
6211   return DAG.getBuildVector(Type, DL, VecElts);
6212 }
6213 
6214 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6215                               SDValue Src, int ExtraElts) {
6216   EVT SrcVT = Src.getValueType();
6217 
6218   SmallVector<SDValue, 8> Elts;
6219 
6220   if (SrcVT.isVector())
6221     DAG.ExtractVectorElements(Src, Elts);
6222   else
6223     Elts.push_back(Src);
6224 
6225   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6226   while (ExtraElts--)
6227     Elts.push_back(Undef);
6228 
6229   return DAG.getBuildVector(CastVT, DL, Elts);
6230 }
6231 
6232 // Re-construct the required return value for a image load intrinsic.
6233 // This is more complicated due to the optional use TexFailCtrl which means the required
6234 // return type is an aggregate
6235 static SDValue constructRetValue(SelectionDAG &DAG,
6236                                  MachineSDNode *Result,
6237                                  ArrayRef<EVT> ResultTypes,
6238                                  bool IsTexFail, bool Unpacked, bool IsD16,
6239                                  int DMaskPop, int NumVDataDwords,
6240                                  const SDLoc &DL) {
6241   // Determine the required return type. This is the same regardless of IsTexFail flag
6242   EVT ReqRetVT = ResultTypes[0];
6243   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6244   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6245     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6246 
6247   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6248     DMaskPop : (DMaskPop + 1) / 2;
6249 
6250   MVT DataDwordVT = NumDataDwords == 1 ?
6251     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6252 
6253   MVT MaskPopVT = MaskPopDwords == 1 ?
6254     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6255 
6256   SDValue Data(Result, 0);
6257   SDValue TexFail;
6258 
6259   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6260     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6261     if (MaskPopVT.isVector()) {
6262       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6263                          SDValue(Result, 0), ZeroIdx);
6264     } else {
6265       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6266                          SDValue(Result, 0), ZeroIdx);
6267     }
6268   }
6269 
6270   if (DataDwordVT.isVector())
6271     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6272                           NumDataDwords - MaskPopDwords);
6273 
6274   if (IsD16)
6275     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6276 
6277   EVT LegalReqRetVT = ReqRetVT;
6278   if (!ReqRetVT.isVector()) {
6279     if (!Data.getValueType().isInteger())
6280       Data = DAG.getNode(ISD::BITCAST, DL,
6281                          Data.getValueType().changeTypeToInteger(), Data);
6282     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6283   } else {
6284     // We need to widen the return vector to a legal type
6285     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6286         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6287       LegalReqRetVT =
6288           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6289                            ReqRetVT.getVectorNumElements() + 1);
6290     }
6291   }
6292   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6293 
6294   if (IsTexFail) {
6295     TexFail =
6296         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6297                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6298 
6299     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6300   }
6301 
6302   if (Result->getNumValues() == 1)
6303     return Data;
6304 
6305   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6306 }
6307 
6308 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6309                          SDValue *LWE, bool &IsTexFail) {
6310   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6311 
6312   uint64_t Value = TexFailCtrlConst->getZExtValue();
6313   if (Value) {
6314     IsTexFail = true;
6315   }
6316 
6317   SDLoc DL(TexFailCtrlConst);
6318   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6319   Value &= ~(uint64_t)0x1;
6320   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6321   Value &= ~(uint64_t)0x2;
6322 
6323   return Value == 0;
6324 }
6325 
6326 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6327                                       MVT PackVectorVT,
6328                                       SmallVectorImpl<SDValue> &PackedAddrs,
6329                                       unsigned DimIdx, unsigned EndIdx,
6330                                       unsigned NumGradients) {
6331   SDLoc DL(Op);
6332   for (unsigned I = DimIdx; I < EndIdx; I++) {
6333     SDValue Addr = Op.getOperand(I);
6334 
6335     // Gradients are packed with undef for each coordinate.
6336     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6337     // 1D: undef,dx/dh; undef,dx/dv
6338     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6339     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6340     if (((I + 1) >= EndIdx) ||
6341         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6342                                          I == DimIdx + NumGradients - 1))) {
6343       if (Addr.getValueType() != MVT::i16)
6344         Addr = DAG.getBitcast(MVT::i16, Addr);
6345       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6346     } else {
6347       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6348       I++;
6349     }
6350     Addr = DAG.getBitcast(MVT::f32, Addr);
6351     PackedAddrs.push_back(Addr);
6352   }
6353 }
6354 
6355 SDValue SITargetLowering::lowerImage(SDValue Op,
6356                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6357                                      SelectionDAG &DAG, bool WithChain) const {
6358   SDLoc DL(Op);
6359   MachineFunction &MF = DAG.getMachineFunction();
6360   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6361   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6362       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6363   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6364   unsigned IntrOpcode = Intr->BaseOpcode;
6365   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6366 
6367   SmallVector<EVT, 3> ResultTypes(Op->values());
6368   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6369   bool IsD16 = false;
6370   bool IsG16 = false;
6371   bool IsA16 = false;
6372   SDValue VData;
6373   int NumVDataDwords;
6374   bool AdjustRetType = false;
6375 
6376   // Offset of intrinsic arguments
6377   const unsigned ArgOffset = WithChain ? 2 : 1;
6378 
6379   unsigned DMask;
6380   unsigned DMaskLanes = 0;
6381 
6382   if (BaseOpcode->Atomic) {
6383     VData = Op.getOperand(2);
6384 
6385     bool Is64Bit = VData.getValueType() == MVT::i64;
6386     if (BaseOpcode->AtomicX2) {
6387       SDValue VData2 = Op.getOperand(3);
6388       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6389                                  {VData, VData2});
6390       if (Is64Bit)
6391         VData = DAG.getBitcast(MVT::v4i32, VData);
6392 
6393       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6394       DMask = Is64Bit ? 0xf : 0x3;
6395       NumVDataDwords = Is64Bit ? 4 : 2;
6396     } else {
6397       DMask = Is64Bit ? 0x3 : 0x1;
6398       NumVDataDwords = Is64Bit ? 2 : 1;
6399     }
6400   } else {
6401     auto *DMaskConst =
6402         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6403     DMask = DMaskConst->getZExtValue();
6404     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6405 
6406     if (BaseOpcode->Store) {
6407       VData = Op.getOperand(2);
6408 
6409       MVT StoreVT = VData.getSimpleValueType();
6410       if (StoreVT.getScalarType() == MVT::f16) {
6411         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6412           return Op; // D16 is unsupported for this instruction
6413 
6414         IsD16 = true;
6415         VData = handleD16VData(VData, DAG, true);
6416       }
6417 
6418       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6419     } else {
6420       // Work out the num dwords based on the dmask popcount and underlying type
6421       // and whether packing is supported.
6422       MVT LoadVT = ResultTypes[0].getSimpleVT();
6423       if (LoadVT.getScalarType() == MVT::f16) {
6424         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6425           return Op; // D16 is unsupported for this instruction
6426 
6427         IsD16 = true;
6428       }
6429 
6430       // Confirm that the return type is large enough for the dmask specified
6431       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6432           (!LoadVT.isVector() && DMaskLanes > 1))
6433           return Op;
6434 
6435       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6436       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6437       // instructions.
6438       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6439           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6440         NumVDataDwords = (DMaskLanes + 1) / 2;
6441       else
6442         NumVDataDwords = DMaskLanes;
6443 
6444       AdjustRetType = true;
6445     }
6446   }
6447 
6448   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6449   SmallVector<SDValue, 4> VAddrs;
6450 
6451   // Check for 16 bit addresses or derivatives and pack if true.
6452   MVT VAddrVT =
6453       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6454   MVT VAddrScalarVT = VAddrVT.getScalarType();
6455   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6456   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6457 
6458   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6459   VAddrScalarVT = VAddrVT.getScalarType();
6460   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6461   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6462 
6463   // Push back extra arguments.
6464   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6465     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6466       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6467       // Special handling of bias when A16 is on. Bias is of type half but
6468       // occupies full 32-bit.
6469       SDValue Bias = DAG.getBuildVector(
6470           MVT::v2f16, DL,
6471           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6472       VAddrs.push_back(Bias);
6473     } else {
6474       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6475              "Bias needs to be converted to 16 bit in A16 mode");
6476       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6477     }
6478   }
6479 
6480   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6481     // 16 bit gradients are supported, but are tied to the A16 control
6482     // so both gradients and addresses must be 16 bit
6483     LLVM_DEBUG(
6484         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6485                   "require 16 bit args for both gradients and addresses");
6486     return Op;
6487   }
6488 
6489   if (IsA16) {
6490     if (!ST->hasA16()) {
6491       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6492                            "support 16 bit addresses\n");
6493       return Op;
6494     }
6495   }
6496 
6497   // We've dealt with incorrect input so we know that if IsA16, IsG16
6498   // are set then we have to compress/pack operands (either address,
6499   // gradient or both)
6500   // In the case where a16 and gradients are tied (no G16 support) then we
6501   // have already verified that both IsA16 and IsG16 are true
6502   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6503     // Activate g16
6504     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6505         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6506     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6507   }
6508 
6509   // Add gradients (packed or unpacked)
6510   if (IsG16) {
6511     // Pack the gradients
6512     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6513     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6514                               ArgOffset + Intr->GradientStart,
6515                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6516   } else {
6517     for (unsigned I = ArgOffset + Intr->GradientStart;
6518          I < ArgOffset + Intr->CoordStart; I++)
6519       VAddrs.push_back(Op.getOperand(I));
6520   }
6521 
6522   // Add addresses (packed or unpacked)
6523   if (IsA16) {
6524     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6525                               ArgOffset + Intr->CoordStart, VAddrEnd,
6526                               0 /* No gradients */);
6527   } else {
6528     // Add uncompressed address
6529     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6530       VAddrs.push_back(Op.getOperand(I));
6531   }
6532 
6533   // If the register allocator cannot place the address registers contiguously
6534   // without introducing moves, then using the non-sequential address encoding
6535   // is always preferable, since it saves VALU instructions and is usually a
6536   // wash in terms of code size or even better.
6537   //
6538   // However, we currently have no way of hinting to the register allocator that
6539   // MIMG addresses should be placed contiguously when it is possible to do so,
6540   // so force non-NSA for the common 2-address case as a heuristic.
6541   //
6542   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6543   // allocation when possible.
6544   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6545                 VAddrs.size() >= 3 &&
6546                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6547   SDValue VAddr;
6548   if (!UseNSA)
6549     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6550 
6551   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6552   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6553   SDValue Unorm;
6554   if (!BaseOpcode->Sampler) {
6555     Unorm = True;
6556   } else {
6557     auto UnormConst =
6558         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6559 
6560     Unorm = UnormConst->getZExtValue() ? True : False;
6561   }
6562 
6563   SDValue TFE;
6564   SDValue LWE;
6565   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6566   bool IsTexFail = false;
6567   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6568     return Op;
6569 
6570   if (IsTexFail) {
6571     if (!DMaskLanes) {
6572       // Expecting to get an error flag since TFC is on - and dmask is 0
6573       // Force dmask to be at least 1 otherwise the instruction will fail
6574       DMask = 0x1;
6575       DMaskLanes = 1;
6576       NumVDataDwords = 1;
6577     }
6578     NumVDataDwords += 1;
6579     AdjustRetType = true;
6580   }
6581 
6582   // Has something earlier tagged that the return type needs adjusting
6583   // This happens if the instruction is a load or has set TexFailCtrl flags
6584   if (AdjustRetType) {
6585     // NumVDataDwords reflects the true number of dwords required in the return type
6586     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6587       // This is a no-op load. This can be eliminated
6588       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6589       if (isa<MemSDNode>(Op))
6590         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6591       return Undef;
6592     }
6593 
6594     EVT NewVT = NumVDataDwords > 1 ?
6595                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6596                 : MVT::i32;
6597 
6598     ResultTypes[0] = NewVT;
6599     if (ResultTypes.size() == 3) {
6600       // Original result was aggregate type used for TexFailCtrl results
6601       // The actual instruction returns as a vector type which has now been
6602       // created. Remove the aggregate result.
6603       ResultTypes.erase(&ResultTypes[1]);
6604     }
6605   }
6606 
6607   unsigned CPol = cast<ConstantSDNode>(
6608       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6609   if (BaseOpcode->Atomic)
6610     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6611   if (CPol & ~AMDGPU::CPol::ALL)
6612     return Op;
6613 
6614   SmallVector<SDValue, 26> Ops;
6615   if (BaseOpcode->Store || BaseOpcode->Atomic)
6616     Ops.push_back(VData); // vdata
6617   if (UseNSA)
6618     append_range(Ops, VAddrs);
6619   else
6620     Ops.push_back(VAddr);
6621   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6622   if (BaseOpcode->Sampler)
6623     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6624   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6625   if (IsGFX10Plus)
6626     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6627   Ops.push_back(Unorm);
6628   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6629   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6630                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6631   if (IsGFX10Plus)
6632     Ops.push_back(IsA16 ? True : False);
6633   if (!Subtarget->hasGFX90AInsts()) {
6634     Ops.push_back(TFE); //tfe
6635   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6636     report_fatal_error("TFE is not supported on this GPU");
6637   }
6638   Ops.push_back(LWE); // lwe
6639   if (!IsGFX10Plus)
6640     Ops.push_back(DimInfo->DA ? True : False);
6641   if (BaseOpcode->HasD16)
6642     Ops.push_back(IsD16 ? True : False);
6643   if (isa<MemSDNode>(Op))
6644     Ops.push_back(Op.getOperand(0)); // chain
6645 
6646   int NumVAddrDwords =
6647       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6648   int Opcode = -1;
6649 
6650   if (IsGFX10Plus) {
6651     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6652                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6653                                           : AMDGPU::MIMGEncGfx10Default,
6654                                    NumVDataDwords, NumVAddrDwords);
6655   } else {
6656     if (Subtarget->hasGFX90AInsts()) {
6657       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6658                                      NumVDataDwords, NumVAddrDwords);
6659       if (Opcode == -1)
6660         report_fatal_error(
6661             "requested image instruction is not supported on this GPU");
6662     }
6663     if (Opcode == -1 &&
6664         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6665       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6666                                      NumVDataDwords, NumVAddrDwords);
6667     if (Opcode == -1)
6668       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6669                                      NumVDataDwords, NumVAddrDwords);
6670   }
6671   assert(Opcode != -1);
6672 
6673   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6674   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6675     MachineMemOperand *MemRef = MemOp->getMemOperand();
6676     DAG.setNodeMemRefs(NewNode, {MemRef});
6677   }
6678 
6679   if (BaseOpcode->AtomicX2) {
6680     SmallVector<SDValue, 1> Elt;
6681     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6682     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6683   }
6684   if (BaseOpcode->Store)
6685     return SDValue(NewNode, 0);
6686   return constructRetValue(DAG, NewNode,
6687                            OrigResultTypes, IsTexFail,
6688                            Subtarget->hasUnpackedD16VMem(), IsD16,
6689                            DMaskLanes, NumVDataDwords, DL);
6690 }
6691 
6692 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6693                                        SDValue Offset, SDValue CachePolicy,
6694                                        SelectionDAG &DAG) const {
6695   MachineFunction &MF = DAG.getMachineFunction();
6696 
6697   const DataLayout &DataLayout = DAG.getDataLayout();
6698   Align Alignment =
6699       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6700 
6701   MachineMemOperand *MMO = MF.getMachineMemOperand(
6702       MachinePointerInfo(),
6703       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6704           MachineMemOperand::MOInvariant,
6705       VT.getStoreSize(), Alignment);
6706 
6707   if (!Offset->isDivergent()) {
6708     SDValue Ops[] = {
6709         Rsrc,
6710         Offset, // Offset
6711         CachePolicy
6712     };
6713 
6714     // Widen vec3 load to vec4.
6715     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6716       EVT WidenedVT =
6717           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6718       auto WidenedOp = DAG.getMemIntrinsicNode(
6719           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6720           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6721       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6722                                    DAG.getVectorIdxConstant(0, DL));
6723       return Subvector;
6724     }
6725 
6726     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6727                                    DAG.getVTList(VT), Ops, VT, MMO);
6728   }
6729 
6730   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6731   // assume that the buffer is unswizzled.
6732   SmallVector<SDValue, 4> Loads;
6733   unsigned NumLoads = 1;
6734   MVT LoadVT = VT.getSimpleVT();
6735   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6736   assert((LoadVT.getScalarType() == MVT::i32 ||
6737           LoadVT.getScalarType() == MVT::f32));
6738 
6739   if (NumElts == 8 || NumElts == 16) {
6740     NumLoads = NumElts / 4;
6741     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6742   }
6743 
6744   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6745   SDValue Ops[] = {
6746       DAG.getEntryNode(),                               // Chain
6747       Rsrc,                                             // rsrc
6748       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6749       {},                                               // voffset
6750       {},                                               // soffset
6751       {},                                               // offset
6752       CachePolicy,                                      // cachepolicy
6753       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6754   };
6755 
6756   // Use the alignment to ensure that the required offsets will fit into the
6757   // immediate offsets.
6758   setBufferOffsets(Offset, DAG, &Ops[3],
6759                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6760 
6761   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6762   for (unsigned i = 0; i < NumLoads; ++i) {
6763     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6764     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6765                                         LoadVT, MMO, DAG));
6766   }
6767 
6768   if (NumElts == 8 || NumElts == 16)
6769     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6770 
6771   return Loads[0];
6772 }
6773 
6774 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6775                                                   SelectionDAG &DAG) const {
6776   MachineFunction &MF = DAG.getMachineFunction();
6777   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6778 
6779   EVT VT = Op.getValueType();
6780   SDLoc DL(Op);
6781   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6782 
6783   // TODO: Should this propagate fast-math-flags?
6784 
6785   switch (IntrinsicID) {
6786   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6787     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6788       return emitNonHSAIntrinsicError(DAG, DL, VT);
6789     return getPreloadedValue(DAG, *MFI, VT,
6790                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6791   }
6792   case Intrinsic::amdgcn_dispatch_ptr:
6793   case Intrinsic::amdgcn_queue_ptr: {
6794     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6795       DiagnosticInfoUnsupported BadIntrin(
6796           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6797           DL.getDebugLoc());
6798       DAG.getContext()->diagnose(BadIntrin);
6799       return DAG.getUNDEF(VT);
6800     }
6801 
6802     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6803       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6804     return getPreloadedValue(DAG, *MFI, VT, RegID);
6805   }
6806   case Intrinsic::amdgcn_implicitarg_ptr: {
6807     if (MFI->isEntryFunction())
6808       return getImplicitArgPtr(DAG, DL);
6809     return getPreloadedValue(DAG, *MFI, VT,
6810                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6811   }
6812   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6813     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6814       // This only makes sense to call in a kernel, so just lower to null.
6815       return DAG.getConstant(0, DL, VT);
6816     }
6817 
6818     return getPreloadedValue(DAG, *MFI, VT,
6819                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6820   }
6821   case Intrinsic::amdgcn_dispatch_id: {
6822     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6823   }
6824   case Intrinsic::amdgcn_rcp:
6825     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6826   case Intrinsic::amdgcn_rsq:
6827     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6828   case Intrinsic::amdgcn_rsq_legacy:
6829     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6830       return emitRemovedIntrinsicError(DAG, DL, VT);
6831     return SDValue();
6832   case Intrinsic::amdgcn_rcp_legacy:
6833     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6834       return emitRemovedIntrinsicError(DAG, DL, VT);
6835     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6836   case Intrinsic::amdgcn_rsq_clamp: {
6837     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6838       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6839 
6840     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6841     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6842     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6843 
6844     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6845     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6846                               DAG.getConstantFP(Max, DL, VT));
6847     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6848                        DAG.getConstantFP(Min, DL, VT));
6849   }
6850   case Intrinsic::r600_read_ngroups_x:
6851     if (Subtarget->isAmdHsaOS())
6852       return emitNonHSAIntrinsicError(DAG, DL, VT);
6853 
6854     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6855                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6856                                     false);
6857   case Intrinsic::r600_read_ngroups_y:
6858     if (Subtarget->isAmdHsaOS())
6859       return emitNonHSAIntrinsicError(DAG, DL, VT);
6860 
6861     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6862                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6863                                     false);
6864   case Intrinsic::r600_read_ngroups_z:
6865     if (Subtarget->isAmdHsaOS())
6866       return emitNonHSAIntrinsicError(DAG, DL, VT);
6867 
6868     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6869                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6870                                     false);
6871   case Intrinsic::r600_read_global_size_x:
6872     if (Subtarget->isAmdHsaOS())
6873       return emitNonHSAIntrinsicError(DAG, DL, VT);
6874 
6875     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6876                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6877                                     Align(4), false);
6878   case Intrinsic::r600_read_global_size_y:
6879     if (Subtarget->isAmdHsaOS())
6880       return emitNonHSAIntrinsicError(DAG, DL, VT);
6881 
6882     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6883                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6884                                     Align(4), false);
6885   case Intrinsic::r600_read_global_size_z:
6886     if (Subtarget->isAmdHsaOS())
6887       return emitNonHSAIntrinsicError(DAG, DL, VT);
6888 
6889     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6890                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6891                                     Align(4), false);
6892   case Intrinsic::r600_read_local_size_x:
6893     if (Subtarget->isAmdHsaOS())
6894       return emitNonHSAIntrinsicError(DAG, DL, VT);
6895 
6896     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6897                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6898   case Intrinsic::r600_read_local_size_y:
6899     if (Subtarget->isAmdHsaOS())
6900       return emitNonHSAIntrinsicError(DAG, DL, VT);
6901 
6902     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6903                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6904   case Intrinsic::r600_read_local_size_z:
6905     if (Subtarget->isAmdHsaOS())
6906       return emitNonHSAIntrinsicError(DAG, DL, VT);
6907 
6908     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6909                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6910   case Intrinsic::amdgcn_workgroup_id_x:
6911     return getPreloadedValue(DAG, *MFI, VT,
6912                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6913   case Intrinsic::amdgcn_workgroup_id_y:
6914     return getPreloadedValue(DAG, *MFI, VT,
6915                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6916   case Intrinsic::amdgcn_workgroup_id_z:
6917     return getPreloadedValue(DAG, *MFI, VT,
6918                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6919   case Intrinsic::amdgcn_workitem_id_x:
6920     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6921       return DAG.getConstant(0, DL, MVT::i32);
6922 
6923     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6924                           SDLoc(DAG.getEntryNode()),
6925                           MFI->getArgInfo().WorkItemIDX);
6926   case Intrinsic::amdgcn_workitem_id_y:
6927     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6928       return DAG.getConstant(0, DL, MVT::i32);
6929 
6930     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6931                           SDLoc(DAG.getEntryNode()),
6932                           MFI->getArgInfo().WorkItemIDY);
6933   case Intrinsic::amdgcn_workitem_id_z:
6934     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6935       return DAG.getConstant(0, DL, MVT::i32);
6936 
6937     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6938                           SDLoc(DAG.getEntryNode()),
6939                           MFI->getArgInfo().WorkItemIDZ);
6940   case Intrinsic::amdgcn_wavefrontsize:
6941     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6942                            SDLoc(Op), MVT::i32);
6943   case Intrinsic::amdgcn_s_buffer_load: {
6944     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6945     if (CPol & ~AMDGPU::CPol::ALL)
6946       return Op;
6947     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6948                         DAG);
6949   }
6950   case Intrinsic::amdgcn_fdiv_fast:
6951     return lowerFDIV_FAST(Op, DAG);
6952   case Intrinsic::amdgcn_sin:
6953     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6954 
6955   case Intrinsic::amdgcn_cos:
6956     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6957 
6958   case Intrinsic::amdgcn_mul_u24:
6959     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6960   case Intrinsic::amdgcn_mul_i24:
6961     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6962 
6963   case Intrinsic::amdgcn_log_clamp: {
6964     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6965       return SDValue();
6966 
6967     return emitRemovedIntrinsicError(DAG, DL, VT);
6968   }
6969   case Intrinsic::amdgcn_ldexp:
6970     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6971                        Op.getOperand(1), Op.getOperand(2));
6972 
6973   case Intrinsic::amdgcn_fract:
6974     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6975 
6976   case Intrinsic::amdgcn_class:
6977     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6978                        Op.getOperand(1), Op.getOperand(2));
6979   case Intrinsic::amdgcn_div_fmas:
6980     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6981                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6982                        Op.getOperand(4));
6983 
6984   case Intrinsic::amdgcn_div_fixup:
6985     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6986                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6987 
6988   case Intrinsic::amdgcn_div_scale: {
6989     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6990 
6991     // Translate to the operands expected by the machine instruction. The
6992     // first parameter must be the same as the first instruction.
6993     SDValue Numerator = Op.getOperand(1);
6994     SDValue Denominator = Op.getOperand(2);
6995 
6996     // Note this order is opposite of the machine instruction's operations,
6997     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6998     // intrinsic has the numerator as the first operand to match a normal
6999     // division operation.
7000 
7001     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
7002 
7003     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
7004                        Denominator, Numerator);
7005   }
7006   case Intrinsic::amdgcn_icmp: {
7007     // There is a Pat that handles this variant, so return it as-is.
7008     if (Op.getOperand(1).getValueType() == MVT::i1 &&
7009         Op.getConstantOperandVal(2) == 0 &&
7010         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7011       return Op;
7012     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7013   }
7014   case Intrinsic::amdgcn_fcmp: {
7015     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7016   }
7017   case Intrinsic::amdgcn_ballot:
7018     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7019   case Intrinsic::amdgcn_fmed3:
7020     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7021                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7022   case Intrinsic::amdgcn_fdot2:
7023     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7024                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7025                        Op.getOperand(4));
7026   case Intrinsic::amdgcn_fmul_legacy:
7027     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7028                        Op.getOperand(1), Op.getOperand(2));
7029   case Intrinsic::amdgcn_sffbh:
7030     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7031   case Intrinsic::amdgcn_sbfe:
7032     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7033                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7034   case Intrinsic::amdgcn_ubfe:
7035     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7036                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7037   case Intrinsic::amdgcn_cvt_pkrtz:
7038   case Intrinsic::amdgcn_cvt_pknorm_i16:
7039   case Intrinsic::amdgcn_cvt_pknorm_u16:
7040   case Intrinsic::amdgcn_cvt_pk_i16:
7041   case Intrinsic::amdgcn_cvt_pk_u16: {
7042     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7043     EVT VT = Op.getValueType();
7044     unsigned Opcode;
7045 
7046     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7047       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7048     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7049       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7050     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7051       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7052     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7053       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7054     else
7055       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7056 
7057     if (isTypeLegal(VT))
7058       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7059 
7060     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7061                                Op.getOperand(1), Op.getOperand(2));
7062     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7063   }
7064   case Intrinsic::amdgcn_fmad_ftz:
7065     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7066                        Op.getOperand(2), Op.getOperand(3));
7067 
7068   case Intrinsic::amdgcn_if_break:
7069     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7070                                       Op->getOperand(1), Op->getOperand(2)), 0);
7071 
7072   case Intrinsic::amdgcn_groupstaticsize: {
7073     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7074     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7075       return Op;
7076 
7077     const Module *M = MF.getFunction().getParent();
7078     const GlobalValue *GV =
7079         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7080     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7081                                             SIInstrInfo::MO_ABS32_LO);
7082     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7083   }
7084   case Intrinsic::amdgcn_is_shared:
7085   case Intrinsic::amdgcn_is_private: {
7086     SDLoc SL(Op);
7087     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7088       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7089     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7090     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7091                                  Op.getOperand(1));
7092 
7093     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7094                                 DAG.getConstant(1, SL, MVT::i32));
7095     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7096   }
7097   case Intrinsic::amdgcn_perm:
7098     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7099                        Op.getOperand(2), Op.getOperand(3));
7100   case Intrinsic::amdgcn_reloc_constant: {
7101     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7102     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7103     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7104     auto RelocSymbol = cast<GlobalVariable>(
7105         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7106     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7107                                             SIInstrInfo::MO_ABS32_LO);
7108     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7109   }
7110   default:
7111     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7112             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7113       return lowerImage(Op, ImageDimIntr, DAG, false);
7114 
7115     return Op;
7116   }
7117 }
7118 
7119 /// Update \p MMO based on the offset inputs to an intrinsic.
7120 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7121                             SDValue SOffset, SDValue Offset,
7122                             SDValue VIndex = SDValue()) {
7123   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7124       !isa<ConstantSDNode>(Offset)) {
7125     // The combined offset is not known to be constant, so we cannot represent
7126     // it in the MMO. Give up.
7127     MMO->setValue((Value *)nullptr);
7128     return;
7129   }
7130 
7131   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7132                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7133     // The strided index component of the address is not known to be zero, so we
7134     // cannot represent it in the MMO. Give up.
7135     MMO->setValue((Value *)nullptr);
7136     return;
7137   }
7138 
7139   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7140                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7141                  cast<ConstantSDNode>(Offset)->getSExtValue());
7142 }
7143 
7144 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7145                                                      SelectionDAG &DAG,
7146                                                      unsigned NewOpcode) const {
7147   SDLoc DL(Op);
7148 
7149   SDValue VData = Op.getOperand(2);
7150   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7151   SDValue Ops[] = {
7152     Op.getOperand(0), // Chain
7153     VData,            // vdata
7154     Op.getOperand(3), // rsrc
7155     DAG.getConstant(0, DL, MVT::i32), // vindex
7156     Offsets.first,    // voffset
7157     Op.getOperand(5), // soffset
7158     Offsets.second,   // offset
7159     Op.getOperand(6), // cachepolicy
7160     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7161   };
7162 
7163   auto *M = cast<MemSDNode>(Op);
7164   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7165 
7166   EVT MemVT = VData.getValueType();
7167   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7168                                  M->getMemOperand());
7169 }
7170 
7171 // Return a value to use for the idxen operand by examining the vindex operand.
7172 static unsigned getIdxEn(SDValue VIndex) {
7173   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7174     // No need to set idxen if vindex is known to be zero.
7175     return VIndexC->getZExtValue() != 0;
7176   return 1;
7177 }
7178 
7179 SDValue
7180 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7181                                                 unsigned NewOpcode) const {
7182   SDLoc DL(Op);
7183 
7184   SDValue VData = Op.getOperand(2);
7185   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7186   SDValue Ops[] = {
7187     Op.getOperand(0), // Chain
7188     VData,            // vdata
7189     Op.getOperand(3), // rsrc
7190     Op.getOperand(4), // vindex
7191     Offsets.first,    // voffset
7192     Op.getOperand(6), // soffset
7193     Offsets.second,   // offset
7194     Op.getOperand(7), // cachepolicy
7195     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7196   };
7197 
7198   auto *M = cast<MemSDNode>(Op);
7199   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7200 
7201   EVT MemVT = VData.getValueType();
7202   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7203                                  M->getMemOperand());
7204 }
7205 
7206 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7207                                                  SelectionDAG &DAG) const {
7208   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7209   SDLoc DL(Op);
7210 
7211   switch (IntrID) {
7212   case Intrinsic::amdgcn_ds_ordered_add:
7213   case Intrinsic::amdgcn_ds_ordered_swap: {
7214     MemSDNode *M = cast<MemSDNode>(Op);
7215     SDValue Chain = M->getOperand(0);
7216     SDValue M0 = M->getOperand(2);
7217     SDValue Value = M->getOperand(3);
7218     unsigned IndexOperand = M->getConstantOperandVal(7);
7219     unsigned WaveRelease = M->getConstantOperandVal(8);
7220     unsigned WaveDone = M->getConstantOperandVal(9);
7221 
7222     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7223     IndexOperand &= ~0x3f;
7224     unsigned CountDw = 0;
7225 
7226     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7227       CountDw = (IndexOperand >> 24) & 0xf;
7228       IndexOperand &= ~(0xf << 24);
7229 
7230       if (CountDw < 1 || CountDw > 4) {
7231         report_fatal_error(
7232             "ds_ordered_count: dword count must be between 1 and 4");
7233       }
7234     }
7235 
7236     if (IndexOperand)
7237       report_fatal_error("ds_ordered_count: bad index operand");
7238 
7239     if (WaveDone && !WaveRelease)
7240       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7241 
7242     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7243     unsigned ShaderType =
7244         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7245     unsigned Offset0 = OrderedCountIndex << 2;
7246     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7247                        (Instruction << 4);
7248 
7249     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7250       Offset1 |= (CountDw - 1) << 6;
7251 
7252     unsigned Offset = Offset0 | (Offset1 << 8);
7253 
7254     SDValue Ops[] = {
7255       Chain,
7256       Value,
7257       DAG.getTargetConstant(Offset, DL, MVT::i16),
7258       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7259     };
7260     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7261                                    M->getVTList(), Ops, M->getMemoryVT(),
7262                                    M->getMemOperand());
7263   }
7264   case Intrinsic::amdgcn_ds_fadd: {
7265     MemSDNode *M = cast<MemSDNode>(Op);
7266     unsigned Opc;
7267     switch (IntrID) {
7268     case Intrinsic::amdgcn_ds_fadd:
7269       Opc = ISD::ATOMIC_LOAD_FADD;
7270       break;
7271     }
7272 
7273     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7274                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7275                          M->getMemOperand());
7276   }
7277   case Intrinsic::amdgcn_atomic_inc:
7278   case Intrinsic::amdgcn_atomic_dec:
7279   case Intrinsic::amdgcn_ds_fmin:
7280   case Intrinsic::amdgcn_ds_fmax: {
7281     MemSDNode *M = cast<MemSDNode>(Op);
7282     unsigned Opc;
7283     switch (IntrID) {
7284     case Intrinsic::amdgcn_atomic_inc:
7285       Opc = AMDGPUISD::ATOMIC_INC;
7286       break;
7287     case Intrinsic::amdgcn_atomic_dec:
7288       Opc = AMDGPUISD::ATOMIC_DEC;
7289       break;
7290     case Intrinsic::amdgcn_ds_fmin:
7291       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7292       break;
7293     case Intrinsic::amdgcn_ds_fmax:
7294       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7295       break;
7296     default:
7297       llvm_unreachable("Unknown intrinsic!");
7298     }
7299     SDValue Ops[] = {
7300       M->getOperand(0), // Chain
7301       M->getOperand(2), // Ptr
7302       M->getOperand(3)  // Value
7303     };
7304 
7305     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7306                                    M->getMemoryVT(), M->getMemOperand());
7307   }
7308   case Intrinsic::amdgcn_buffer_load:
7309   case Intrinsic::amdgcn_buffer_load_format: {
7310     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7311     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7312     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7313     SDValue Ops[] = {
7314       Op.getOperand(0), // Chain
7315       Op.getOperand(2), // rsrc
7316       Op.getOperand(3), // vindex
7317       SDValue(),        // voffset -- will be set by setBufferOffsets
7318       SDValue(),        // soffset -- will be set by setBufferOffsets
7319       SDValue(),        // offset -- will be set by setBufferOffsets
7320       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7321       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7322     };
7323     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7324 
7325     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7326         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7327 
7328     EVT VT = Op.getValueType();
7329     EVT IntVT = VT.changeTypeToInteger();
7330     auto *M = cast<MemSDNode>(Op);
7331     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7332     EVT LoadVT = Op.getValueType();
7333 
7334     if (LoadVT.getScalarType() == MVT::f16)
7335       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7336                                  M, DAG, Ops);
7337 
7338     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7339     if (LoadVT.getScalarType() == MVT::i8 ||
7340         LoadVT.getScalarType() == MVT::i16)
7341       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7342 
7343     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7344                                M->getMemOperand(), DAG);
7345   }
7346   case Intrinsic::amdgcn_raw_buffer_load:
7347   case Intrinsic::amdgcn_raw_buffer_load_format: {
7348     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7349 
7350     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7351     SDValue Ops[] = {
7352       Op.getOperand(0), // Chain
7353       Op.getOperand(2), // rsrc
7354       DAG.getConstant(0, DL, MVT::i32), // vindex
7355       Offsets.first,    // voffset
7356       Op.getOperand(4), // soffset
7357       Offsets.second,   // offset
7358       Op.getOperand(5), // cachepolicy, swizzled buffer
7359       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7360     };
7361 
7362     auto *M = cast<MemSDNode>(Op);
7363     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7364     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7365   }
7366   case Intrinsic::amdgcn_struct_buffer_load:
7367   case Intrinsic::amdgcn_struct_buffer_load_format: {
7368     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7369 
7370     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7371     SDValue Ops[] = {
7372       Op.getOperand(0), // Chain
7373       Op.getOperand(2), // rsrc
7374       Op.getOperand(3), // vindex
7375       Offsets.first,    // voffset
7376       Op.getOperand(5), // soffset
7377       Offsets.second,   // offset
7378       Op.getOperand(6), // cachepolicy, swizzled buffer
7379       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7380     };
7381 
7382     auto *M = cast<MemSDNode>(Op);
7383     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7384     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7385   }
7386   case Intrinsic::amdgcn_tbuffer_load: {
7387     MemSDNode *M = cast<MemSDNode>(Op);
7388     EVT LoadVT = Op.getValueType();
7389 
7390     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7391     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7392     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7393     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7394     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7395     SDValue Ops[] = {
7396       Op.getOperand(0),  // Chain
7397       Op.getOperand(2),  // rsrc
7398       Op.getOperand(3),  // vindex
7399       Op.getOperand(4),  // voffset
7400       Op.getOperand(5),  // soffset
7401       Op.getOperand(6),  // offset
7402       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7403       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7404       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7405     };
7406 
7407     if (LoadVT.getScalarType() == MVT::f16)
7408       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7409                                  M, DAG, Ops);
7410     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7411                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7412                                DAG);
7413   }
7414   case Intrinsic::amdgcn_raw_tbuffer_load: {
7415     MemSDNode *M = cast<MemSDNode>(Op);
7416     EVT LoadVT = Op.getValueType();
7417     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7418 
7419     SDValue Ops[] = {
7420       Op.getOperand(0),  // Chain
7421       Op.getOperand(2),  // rsrc
7422       DAG.getConstant(0, DL, MVT::i32), // vindex
7423       Offsets.first,     // voffset
7424       Op.getOperand(4),  // soffset
7425       Offsets.second,    // offset
7426       Op.getOperand(5),  // format
7427       Op.getOperand(6),  // cachepolicy, swizzled buffer
7428       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7429     };
7430 
7431     if (LoadVT.getScalarType() == MVT::f16)
7432       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7433                                  M, DAG, Ops);
7434     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7435                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7436                                DAG);
7437   }
7438   case Intrinsic::amdgcn_struct_tbuffer_load: {
7439     MemSDNode *M = cast<MemSDNode>(Op);
7440     EVT LoadVT = Op.getValueType();
7441     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7442 
7443     SDValue Ops[] = {
7444       Op.getOperand(0),  // Chain
7445       Op.getOperand(2),  // rsrc
7446       Op.getOperand(3),  // vindex
7447       Offsets.first,     // voffset
7448       Op.getOperand(5),  // soffset
7449       Offsets.second,    // offset
7450       Op.getOperand(6),  // format
7451       Op.getOperand(7),  // cachepolicy, swizzled buffer
7452       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7453     };
7454 
7455     if (LoadVT.getScalarType() == MVT::f16)
7456       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7457                                  M, DAG, Ops);
7458     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7459                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7460                                DAG);
7461   }
7462   case Intrinsic::amdgcn_buffer_atomic_swap:
7463   case Intrinsic::amdgcn_buffer_atomic_add:
7464   case Intrinsic::amdgcn_buffer_atomic_sub:
7465   case Intrinsic::amdgcn_buffer_atomic_csub:
7466   case Intrinsic::amdgcn_buffer_atomic_smin:
7467   case Intrinsic::amdgcn_buffer_atomic_umin:
7468   case Intrinsic::amdgcn_buffer_atomic_smax:
7469   case Intrinsic::amdgcn_buffer_atomic_umax:
7470   case Intrinsic::amdgcn_buffer_atomic_and:
7471   case Intrinsic::amdgcn_buffer_atomic_or:
7472   case Intrinsic::amdgcn_buffer_atomic_xor:
7473   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7474     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7475     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7476     SDValue Ops[] = {
7477       Op.getOperand(0), // Chain
7478       Op.getOperand(2), // vdata
7479       Op.getOperand(3), // rsrc
7480       Op.getOperand(4), // vindex
7481       SDValue(),        // voffset -- will be set by setBufferOffsets
7482       SDValue(),        // soffset -- will be set by setBufferOffsets
7483       SDValue(),        // offset -- will be set by setBufferOffsets
7484       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7485       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7486     };
7487     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7488 
7489     EVT VT = Op.getValueType();
7490 
7491     auto *M = cast<MemSDNode>(Op);
7492     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7493     unsigned Opcode = 0;
7494 
7495     switch (IntrID) {
7496     case Intrinsic::amdgcn_buffer_atomic_swap:
7497       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7498       break;
7499     case Intrinsic::amdgcn_buffer_atomic_add:
7500       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7501       break;
7502     case Intrinsic::amdgcn_buffer_atomic_sub:
7503       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7504       break;
7505     case Intrinsic::amdgcn_buffer_atomic_csub:
7506       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7507       break;
7508     case Intrinsic::amdgcn_buffer_atomic_smin:
7509       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7510       break;
7511     case Intrinsic::amdgcn_buffer_atomic_umin:
7512       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7513       break;
7514     case Intrinsic::amdgcn_buffer_atomic_smax:
7515       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7516       break;
7517     case Intrinsic::amdgcn_buffer_atomic_umax:
7518       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7519       break;
7520     case Intrinsic::amdgcn_buffer_atomic_and:
7521       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7522       break;
7523     case Intrinsic::amdgcn_buffer_atomic_or:
7524       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7525       break;
7526     case Intrinsic::amdgcn_buffer_atomic_xor:
7527       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7528       break;
7529     case Intrinsic::amdgcn_buffer_atomic_fadd:
7530       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7531         DiagnosticInfoUnsupported
7532           NoFpRet(DAG.getMachineFunction().getFunction(),
7533                   "return versions of fp atomics not supported",
7534                   DL.getDebugLoc(), DS_Error);
7535         DAG.getContext()->diagnose(NoFpRet);
7536         return SDValue();
7537       }
7538       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7539       break;
7540     default:
7541       llvm_unreachable("unhandled atomic opcode");
7542     }
7543 
7544     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7545                                    M->getMemOperand());
7546   }
7547   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7548     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7549   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7550     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7551   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7552     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7553   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7554     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7555   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7556     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7557   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7558     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7559   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7560     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7561   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7562     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7563   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7564     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7565   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7566     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7567   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7568     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7569   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7570     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7571   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7572     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7573   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7574     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7575   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7576     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7577   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7578     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7579   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7580     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7581   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7582     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7583   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7584     return lowerStructBufferAtomicIntrin(Op, DAG,
7585                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7586   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7587     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7588   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7589     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7590   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7591     return lowerStructBufferAtomicIntrin(Op, DAG,
7592                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7593   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7594     return lowerStructBufferAtomicIntrin(Op, DAG,
7595                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7596   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7597     return lowerStructBufferAtomicIntrin(Op, DAG,
7598                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7599   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7600     return lowerStructBufferAtomicIntrin(Op, DAG,
7601                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7602   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7603     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7604   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7605     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7606   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7607     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7608   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7609     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7610   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7611     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7612 
7613   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7614     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7615     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7616     SDValue Ops[] = {
7617       Op.getOperand(0), // Chain
7618       Op.getOperand(2), // src
7619       Op.getOperand(3), // cmp
7620       Op.getOperand(4), // rsrc
7621       Op.getOperand(5), // vindex
7622       SDValue(),        // voffset -- will be set by setBufferOffsets
7623       SDValue(),        // soffset -- will be set by setBufferOffsets
7624       SDValue(),        // offset -- will be set by setBufferOffsets
7625       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7626       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7627     };
7628     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7629 
7630     EVT VT = Op.getValueType();
7631     auto *M = cast<MemSDNode>(Op);
7632     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7633 
7634     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7635                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7636   }
7637   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7638     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7639     SDValue Ops[] = {
7640       Op.getOperand(0), // Chain
7641       Op.getOperand(2), // src
7642       Op.getOperand(3), // cmp
7643       Op.getOperand(4), // rsrc
7644       DAG.getConstant(0, DL, MVT::i32), // vindex
7645       Offsets.first,    // voffset
7646       Op.getOperand(6), // soffset
7647       Offsets.second,   // offset
7648       Op.getOperand(7), // cachepolicy
7649       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7650     };
7651     EVT VT = Op.getValueType();
7652     auto *M = cast<MemSDNode>(Op);
7653     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7654 
7655     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7656                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7657   }
7658   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7659     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7660     SDValue Ops[] = {
7661       Op.getOperand(0), // Chain
7662       Op.getOperand(2), // src
7663       Op.getOperand(3), // cmp
7664       Op.getOperand(4), // rsrc
7665       Op.getOperand(5), // vindex
7666       Offsets.first,    // voffset
7667       Op.getOperand(7), // soffset
7668       Offsets.second,   // offset
7669       Op.getOperand(8), // cachepolicy
7670       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7671     };
7672     EVT VT = Op.getValueType();
7673     auto *M = cast<MemSDNode>(Op);
7674     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7675 
7676     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7677                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7678   }
7679   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7680     MemSDNode *M = cast<MemSDNode>(Op);
7681     SDValue NodePtr = M->getOperand(2);
7682     SDValue RayExtent = M->getOperand(3);
7683     SDValue RayOrigin = M->getOperand(4);
7684     SDValue RayDir = M->getOperand(5);
7685     SDValue RayInvDir = M->getOperand(6);
7686     SDValue TDescr = M->getOperand(7);
7687 
7688     assert(NodePtr.getValueType() == MVT::i32 ||
7689            NodePtr.getValueType() == MVT::i64);
7690     assert(RayDir.getValueType() == MVT::v3f16 ||
7691            RayDir.getValueType() == MVT::v3f32);
7692 
7693     if (!Subtarget->hasGFX10_AEncoding()) {
7694       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7695       return SDValue();
7696     }
7697 
7698     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7699     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7700     const unsigned NumVDataDwords = 4;
7701     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7702     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7703                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7704     const unsigned BaseOpcodes[2][2] = {
7705         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7706         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7707          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7708     int Opcode;
7709     if (UseNSA) {
7710       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7711                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7712                                      NumVAddrDwords);
7713     } else {
7714       Opcode = AMDGPU::getMIMGOpcode(
7715           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7716           PowerOf2Ceil(NumVAddrDwords));
7717     }
7718     assert(Opcode != -1);
7719 
7720     SmallVector<SDValue, 16> Ops;
7721 
7722     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7723       SmallVector<SDValue, 3> Lanes;
7724       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7725       if (Lanes[0].getValueSizeInBits() == 32) {
7726         for (unsigned I = 0; I < 3; ++I)
7727           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7728       } else {
7729         if (IsAligned) {
7730           Ops.push_back(
7731             DAG.getBitcast(MVT::i32,
7732                            DAG.getBuildVector(MVT::v2f16, DL,
7733                                               { Lanes[0], Lanes[1] })));
7734           Ops.push_back(Lanes[2]);
7735         } else {
7736           SDValue Elt0 = Ops.pop_back_val();
7737           Ops.push_back(
7738             DAG.getBitcast(MVT::i32,
7739                            DAG.getBuildVector(MVT::v2f16, DL,
7740                                               { Elt0, Lanes[0] })));
7741           Ops.push_back(
7742             DAG.getBitcast(MVT::i32,
7743                            DAG.getBuildVector(MVT::v2f16, DL,
7744                                               { Lanes[1], Lanes[2] })));
7745         }
7746       }
7747     };
7748 
7749     if (Is64)
7750       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7751     else
7752       Ops.push_back(NodePtr);
7753 
7754     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7755     packLanes(RayOrigin, true);
7756     packLanes(RayDir, true);
7757     packLanes(RayInvDir, false);
7758 
7759     if (!UseNSA) {
7760       // Build a single vector containing all the operands so far prepared.
7761       if (NumVAddrDwords > 8) {
7762         SDValue Undef = DAG.getUNDEF(MVT::i32);
7763         Ops.append(16 - Ops.size(), Undef);
7764       }
7765       assert(Ops.size() == 8 || Ops.size() == 16);
7766       SDValue MergedOps = DAG.getBuildVector(
7767           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7768       Ops.clear();
7769       Ops.push_back(MergedOps);
7770     }
7771 
7772     Ops.push_back(TDescr);
7773     if (IsA16)
7774       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7775     Ops.push_back(M->getChain());
7776 
7777     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7778     MachineMemOperand *MemRef = M->getMemOperand();
7779     DAG.setNodeMemRefs(NewNode, {MemRef});
7780     return SDValue(NewNode, 0);
7781   }
7782   case Intrinsic::amdgcn_global_atomic_fadd:
7783     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7784       DiagnosticInfoUnsupported
7785         NoFpRet(DAG.getMachineFunction().getFunction(),
7786                 "return versions of fp atomics not supported",
7787                 DL.getDebugLoc(), DS_Error);
7788       DAG.getContext()->diagnose(NoFpRet);
7789       return SDValue();
7790     }
7791     LLVM_FALLTHROUGH;
7792   case Intrinsic::amdgcn_global_atomic_fmin:
7793   case Intrinsic::amdgcn_global_atomic_fmax:
7794   case Intrinsic::amdgcn_flat_atomic_fadd:
7795   case Intrinsic::amdgcn_flat_atomic_fmin:
7796   case Intrinsic::amdgcn_flat_atomic_fmax: {
7797     MemSDNode *M = cast<MemSDNode>(Op);
7798     SDValue Ops[] = {
7799       M->getOperand(0), // Chain
7800       M->getOperand(2), // Ptr
7801       M->getOperand(3)  // Value
7802     };
7803     unsigned Opcode = 0;
7804     switch (IntrID) {
7805     case Intrinsic::amdgcn_global_atomic_fadd:
7806     case Intrinsic::amdgcn_flat_atomic_fadd: {
7807       EVT VT = Op.getOperand(3).getValueType();
7808       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7809                            DAG.getVTList(VT, MVT::Other), Ops,
7810                            M->getMemOperand());
7811     }
7812     case Intrinsic::amdgcn_global_atomic_fmin:
7813     case Intrinsic::amdgcn_flat_atomic_fmin: {
7814       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7815       break;
7816     }
7817     case Intrinsic::amdgcn_global_atomic_fmax:
7818     case Intrinsic::amdgcn_flat_atomic_fmax: {
7819       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7820       break;
7821     }
7822     default:
7823       llvm_unreachable("unhandled atomic opcode");
7824     }
7825     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7826                                    M->getVTList(), Ops, M->getMemoryVT(),
7827                                    M->getMemOperand());
7828   }
7829   default:
7830 
7831     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7832             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7833       return lowerImage(Op, ImageDimIntr, DAG, true);
7834 
7835     return SDValue();
7836   }
7837 }
7838 
7839 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7840 // dwordx4 if on SI.
7841 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7842                                               SDVTList VTList,
7843                                               ArrayRef<SDValue> Ops, EVT MemVT,
7844                                               MachineMemOperand *MMO,
7845                                               SelectionDAG &DAG) const {
7846   EVT VT = VTList.VTs[0];
7847   EVT WidenedVT = VT;
7848   EVT WidenedMemVT = MemVT;
7849   if (!Subtarget->hasDwordx3LoadStores() &&
7850       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7851     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7852                                  WidenedVT.getVectorElementType(), 4);
7853     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7854                                     WidenedMemVT.getVectorElementType(), 4);
7855     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7856   }
7857 
7858   assert(VTList.NumVTs == 2);
7859   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7860 
7861   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7862                                        WidenedMemVT, MMO);
7863   if (WidenedVT != VT) {
7864     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7865                                DAG.getVectorIdxConstant(0, DL));
7866     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7867   }
7868   return NewOp;
7869 }
7870 
7871 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7872                                          bool ImageStore) const {
7873   EVT StoreVT = VData.getValueType();
7874 
7875   // No change for f16 and legal vector D16 types.
7876   if (!StoreVT.isVector())
7877     return VData;
7878 
7879   SDLoc DL(VData);
7880   unsigned NumElements = StoreVT.getVectorNumElements();
7881 
7882   if (Subtarget->hasUnpackedD16VMem()) {
7883     // We need to unpack the packed data to store.
7884     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7885     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7886 
7887     EVT EquivStoreVT =
7888         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7889     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7890     return DAG.UnrollVectorOp(ZExt.getNode());
7891   }
7892 
7893   // The sq block of gfx8.1 does not estimate register use correctly for d16
7894   // image store instructions. The data operand is computed as if it were not a
7895   // d16 image instruction.
7896   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7897     // Bitcast to i16
7898     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7899     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7900 
7901     // Decompose into scalars
7902     SmallVector<SDValue, 4> Elts;
7903     DAG.ExtractVectorElements(IntVData, Elts);
7904 
7905     // Group pairs of i16 into v2i16 and bitcast to i32
7906     SmallVector<SDValue, 4> PackedElts;
7907     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7908       SDValue Pair =
7909           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7910       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7911       PackedElts.push_back(IntPair);
7912     }
7913     if ((NumElements % 2) == 1) {
7914       // Handle v3i16
7915       unsigned I = Elts.size() / 2;
7916       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7917                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7918       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7919       PackedElts.push_back(IntPair);
7920     }
7921 
7922     // Pad using UNDEF
7923     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7924 
7925     // Build final vector
7926     EVT VecVT =
7927         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7928     return DAG.getBuildVector(VecVT, DL, PackedElts);
7929   }
7930 
7931   if (NumElements == 3) {
7932     EVT IntStoreVT =
7933         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7934     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7935 
7936     EVT WidenedStoreVT = EVT::getVectorVT(
7937         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7938     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7939                                          WidenedStoreVT.getStoreSizeInBits());
7940     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7941     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7942   }
7943 
7944   assert(isTypeLegal(StoreVT));
7945   return VData;
7946 }
7947 
7948 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7949                                               SelectionDAG &DAG) const {
7950   SDLoc DL(Op);
7951   SDValue Chain = Op.getOperand(0);
7952   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7953   MachineFunction &MF = DAG.getMachineFunction();
7954 
7955   switch (IntrinsicID) {
7956   case Intrinsic::amdgcn_exp_compr: {
7957     SDValue Src0 = Op.getOperand(4);
7958     SDValue Src1 = Op.getOperand(5);
7959     // Hack around illegal type on SI by directly selecting it.
7960     if (isTypeLegal(Src0.getValueType()))
7961       return SDValue();
7962 
7963     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7964     SDValue Undef = DAG.getUNDEF(MVT::f32);
7965     const SDValue Ops[] = {
7966       Op.getOperand(2), // tgt
7967       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7968       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7969       Undef, // src2
7970       Undef, // src3
7971       Op.getOperand(7), // vm
7972       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7973       Op.getOperand(3), // en
7974       Op.getOperand(0) // Chain
7975     };
7976 
7977     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7978     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7979   }
7980   case Intrinsic::amdgcn_s_barrier: {
7981     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7982       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7983       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7984       if (WGSize <= ST.getWavefrontSize())
7985         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7986                                           Op.getOperand(0)), 0);
7987     }
7988     return SDValue();
7989   };
7990   case Intrinsic::amdgcn_tbuffer_store: {
7991     SDValue VData = Op.getOperand(2);
7992     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7993     if (IsD16)
7994       VData = handleD16VData(VData, DAG);
7995     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7996     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7997     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7998     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7999     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8000     SDValue Ops[] = {
8001       Chain,
8002       VData,             // vdata
8003       Op.getOperand(3),  // rsrc
8004       Op.getOperand(4),  // vindex
8005       Op.getOperand(5),  // voffset
8006       Op.getOperand(6),  // soffset
8007       Op.getOperand(7),  // offset
8008       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8009       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8010       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8011     };
8012     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8013                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8014     MemSDNode *M = cast<MemSDNode>(Op);
8015     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8016                                    M->getMemoryVT(), M->getMemOperand());
8017   }
8018 
8019   case Intrinsic::amdgcn_struct_tbuffer_store: {
8020     SDValue VData = Op.getOperand(2);
8021     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8022     if (IsD16)
8023       VData = handleD16VData(VData, DAG);
8024     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8025     SDValue Ops[] = {
8026       Chain,
8027       VData,             // vdata
8028       Op.getOperand(3),  // rsrc
8029       Op.getOperand(4),  // vindex
8030       Offsets.first,     // voffset
8031       Op.getOperand(6),  // soffset
8032       Offsets.second,    // offset
8033       Op.getOperand(7),  // format
8034       Op.getOperand(8),  // cachepolicy, swizzled buffer
8035       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8036     };
8037     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8038                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8039     MemSDNode *M = cast<MemSDNode>(Op);
8040     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8041                                    M->getMemoryVT(), M->getMemOperand());
8042   }
8043 
8044   case Intrinsic::amdgcn_raw_tbuffer_store: {
8045     SDValue VData = Op.getOperand(2);
8046     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8047     if (IsD16)
8048       VData = handleD16VData(VData, DAG);
8049     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8050     SDValue Ops[] = {
8051       Chain,
8052       VData,             // vdata
8053       Op.getOperand(3),  // rsrc
8054       DAG.getConstant(0, DL, MVT::i32), // vindex
8055       Offsets.first,     // voffset
8056       Op.getOperand(5),  // soffset
8057       Offsets.second,    // offset
8058       Op.getOperand(6),  // format
8059       Op.getOperand(7),  // cachepolicy, swizzled buffer
8060       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8061     };
8062     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8063                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8064     MemSDNode *M = cast<MemSDNode>(Op);
8065     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8066                                    M->getMemoryVT(), M->getMemOperand());
8067   }
8068 
8069   case Intrinsic::amdgcn_buffer_store:
8070   case Intrinsic::amdgcn_buffer_store_format: {
8071     SDValue VData = Op.getOperand(2);
8072     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8073     if (IsD16)
8074       VData = handleD16VData(VData, DAG);
8075     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8076     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8077     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8078     SDValue Ops[] = {
8079       Chain,
8080       VData,
8081       Op.getOperand(3), // rsrc
8082       Op.getOperand(4), // vindex
8083       SDValue(), // voffset -- will be set by setBufferOffsets
8084       SDValue(), // soffset -- will be set by setBufferOffsets
8085       SDValue(), // offset -- will be set by setBufferOffsets
8086       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8087       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8088     };
8089     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8090 
8091     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8092                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8093     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8094     MemSDNode *M = cast<MemSDNode>(Op);
8095     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8096 
8097     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8098     EVT VDataType = VData.getValueType().getScalarType();
8099     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8100       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8101 
8102     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8103                                    M->getMemoryVT(), M->getMemOperand());
8104   }
8105 
8106   case Intrinsic::amdgcn_raw_buffer_store:
8107   case Intrinsic::amdgcn_raw_buffer_store_format: {
8108     const bool IsFormat =
8109         IntrinsicID == Intrinsic::amdgcn_raw_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     if (IsD16) {
8116       VData = handleD16VData(VData, DAG);
8117       VDataVT = VData.getValueType();
8118     }
8119 
8120     if (!isTypeLegal(VDataVT)) {
8121       VData =
8122           DAG.getNode(ISD::BITCAST, DL,
8123                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8124     }
8125 
8126     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8127     SDValue Ops[] = {
8128       Chain,
8129       VData,
8130       Op.getOperand(3), // rsrc
8131       DAG.getConstant(0, DL, MVT::i32), // vindex
8132       Offsets.first,    // voffset
8133       Op.getOperand(5), // soffset
8134       Offsets.second,   // offset
8135       Op.getOperand(6), // cachepolicy, swizzled buffer
8136       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8137     };
8138     unsigned Opc =
8139         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8140     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8141     MemSDNode *M = cast<MemSDNode>(Op);
8142     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8143 
8144     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8145     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8146       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8147 
8148     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8149                                    M->getMemoryVT(), M->getMemOperand());
8150   }
8151 
8152   case Intrinsic::amdgcn_struct_buffer_store:
8153   case Intrinsic::amdgcn_struct_buffer_store_format: {
8154     const bool IsFormat =
8155         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8156 
8157     SDValue VData = Op.getOperand(2);
8158     EVT VDataVT = VData.getValueType();
8159     EVT EltType = VDataVT.getScalarType();
8160     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8161 
8162     if (IsD16) {
8163       VData = handleD16VData(VData, DAG);
8164       VDataVT = VData.getValueType();
8165     }
8166 
8167     if (!isTypeLegal(VDataVT)) {
8168       VData =
8169           DAG.getNode(ISD::BITCAST, DL,
8170                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8171     }
8172 
8173     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8174     SDValue Ops[] = {
8175       Chain,
8176       VData,
8177       Op.getOperand(3), // rsrc
8178       Op.getOperand(4), // vindex
8179       Offsets.first,    // voffset
8180       Op.getOperand(6), // soffset
8181       Offsets.second,   // offset
8182       Op.getOperand(7), // cachepolicy, swizzled buffer
8183       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8184     };
8185     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8186                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8187     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8188     MemSDNode *M = cast<MemSDNode>(Op);
8189     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8190 
8191     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8192     EVT VDataType = VData.getValueType().getScalarType();
8193     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8194       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8195 
8196     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8197                                    M->getMemoryVT(), M->getMemOperand());
8198   }
8199   case Intrinsic::amdgcn_end_cf:
8200     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8201                                       Op->getOperand(2), Chain), 0);
8202 
8203   default: {
8204     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8205             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8206       return lowerImage(Op, ImageDimIntr, DAG, true);
8207 
8208     return Op;
8209   }
8210   }
8211 }
8212 
8213 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8214 // offset (the offset that is included in bounds checking and swizzling, to be
8215 // split between the instruction's voffset and immoffset fields) and soffset
8216 // (the offset that is excluded from bounds checking and swizzling, to go in
8217 // the instruction's soffset field).  This function takes the first kind of
8218 // offset and figures out how to split it between voffset and immoffset.
8219 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8220     SDValue Offset, SelectionDAG &DAG) const {
8221   SDLoc DL(Offset);
8222   const unsigned MaxImm = 4095;
8223   SDValue N0 = Offset;
8224   ConstantSDNode *C1 = nullptr;
8225 
8226   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8227     N0 = SDValue();
8228   else if (DAG.isBaseWithConstantOffset(N0)) {
8229     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8230     N0 = N0.getOperand(0);
8231   }
8232 
8233   if (C1) {
8234     unsigned ImmOffset = C1->getZExtValue();
8235     // If the immediate value is too big for the immoffset field, put the value
8236     // and -4096 into the immoffset field so that the value that is copied/added
8237     // for the voffset field is a multiple of 4096, and it stands more chance
8238     // of being CSEd with the copy/add for another similar load/store.
8239     // However, do not do that rounding down to a multiple of 4096 if that is a
8240     // negative number, as it appears to be illegal to have a negative offset
8241     // in the vgpr, even if adding the immediate offset makes it positive.
8242     unsigned Overflow = ImmOffset & ~MaxImm;
8243     ImmOffset -= Overflow;
8244     if ((int32_t)Overflow < 0) {
8245       Overflow += ImmOffset;
8246       ImmOffset = 0;
8247     }
8248     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8249     if (Overflow) {
8250       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8251       if (!N0)
8252         N0 = OverflowVal;
8253       else {
8254         SDValue Ops[] = { N0, OverflowVal };
8255         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8256       }
8257     }
8258   }
8259   if (!N0)
8260     N0 = DAG.getConstant(0, DL, MVT::i32);
8261   if (!C1)
8262     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8263   return {N0, SDValue(C1, 0)};
8264 }
8265 
8266 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8267 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8268 // pointed to by Offsets.
8269 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8270                                         SelectionDAG &DAG, SDValue *Offsets,
8271                                         Align Alignment) const {
8272   SDLoc DL(CombinedOffset);
8273   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8274     uint32_t Imm = C->getZExtValue();
8275     uint32_t SOffset, ImmOffset;
8276     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8277                                  Alignment)) {
8278       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8279       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8280       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8281       return;
8282     }
8283   }
8284   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8285     SDValue N0 = CombinedOffset.getOperand(0);
8286     SDValue N1 = CombinedOffset.getOperand(1);
8287     uint32_t SOffset, ImmOffset;
8288     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8289     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8290                                                 Subtarget, Alignment)) {
8291       Offsets[0] = N0;
8292       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8293       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8294       return;
8295     }
8296   }
8297   Offsets[0] = CombinedOffset;
8298   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8299   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8300 }
8301 
8302 // Handle 8 bit and 16 bit buffer loads
8303 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8304                                                      EVT LoadVT, SDLoc DL,
8305                                                      ArrayRef<SDValue> Ops,
8306                                                      MemSDNode *M) const {
8307   EVT IntVT = LoadVT.changeTypeToInteger();
8308   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8309          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8310 
8311   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8312   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8313                                                Ops, IntVT,
8314                                                M->getMemOperand());
8315   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8316   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8317 
8318   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8319 }
8320 
8321 // Handle 8 bit and 16 bit buffer stores
8322 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8323                                                       EVT VDataType, SDLoc DL,
8324                                                       SDValue Ops[],
8325                                                       MemSDNode *M) const {
8326   if (VDataType == MVT::f16)
8327     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8328 
8329   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8330   Ops[1] = BufferStoreExt;
8331   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8332                                  AMDGPUISD::BUFFER_STORE_SHORT;
8333   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8334   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8335                                      M->getMemOperand());
8336 }
8337 
8338 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8339                                  ISD::LoadExtType ExtType, SDValue Op,
8340                                  const SDLoc &SL, EVT VT) {
8341   if (VT.bitsLT(Op.getValueType()))
8342     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8343 
8344   switch (ExtType) {
8345   case ISD::SEXTLOAD:
8346     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8347   case ISD::ZEXTLOAD:
8348     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8349   case ISD::EXTLOAD:
8350     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8351   case ISD::NON_EXTLOAD:
8352     return Op;
8353   }
8354 
8355   llvm_unreachable("invalid ext type");
8356 }
8357 
8358 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8359   SelectionDAG &DAG = DCI.DAG;
8360   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8361     return SDValue();
8362 
8363   // FIXME: Constant loads should all be marked invariant.
8364   unsigned AS = Ld->getAddressSpace();
8365   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8366       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8367       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8368     return SDValue();
8369 
8370   // Don't do this early, since it may interfere with adjacent load merging for
8371   // illegal types. We can avoid losing alignment information for exotic types
8372   // pre-legalize.
8373   EVT MemVT = Ld->getMemoryVT();
8374   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8375       MemVT.getSizeInBits() >= 32)
8376     return SDValue();
8377 
8378   SDLoc SL(Ld);
8379 
8380   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8381          "unexpected vector extload");
8382 
8383   // TODO: Drop only high part of range.
8384   SDValue Ptr = Ld->getBasePtr();
8385   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8386                                 MVT::i32, SL, Ld->getChain(), Ptr,
8387                                 Ld->getOffset(),
8388                                 Ld->getPointerInfo(), MVT::i32,
8389                                 Ld->getAlignment(),
8390                                 Ld->getMemOperand()->getFlags(),
8391                                 Ld->getAAInfo(),
8392                                 nullptr); // Drop ranges
8393 
8394   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8395   if (MemVT.isFloatingPoint()) {
8396     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8397            "unexpected fp extload");
8398     TruncVT = MemVT.changeTypeToInteger();
8399   }
8400 
8401   SDValue Cvt = NewLoad;
8402   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8403     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8404                       DAG.getValueType(TruncVT));
8405   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8406              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8407     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8408   } else {
8409     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8410   }
8411 
8412   EVT VT = Ld->getValueType(0);
8413   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8414 
8415   DCI.AddToWorklist(Cvt.getNode());
8416 
8417   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8418   // the appropriate extension from the 32-bit load.
8419   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8420   DCI.AddToWorklist(Cvt.getNode());
8421 
8422   // Handle conversion back to floating point if necessary.
8423   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8424 
8425   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8426 }
8427 
8428 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8429   SDLoc DL(Op);
8430   LoadSDNode *Load = cast<LoadSDNode>(Op);
8431   ISD::LoadExtType ExtType = Load->getExtensionType();
8432   EVT MemVT = Load->getMemoryVT();
8433 
8434   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8435     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8436       return SDValue();
8437 
8438     // FIXME: Copied from PPC
8439     // First, load into 32 bits, then truncate to 1 bit.
8440 
8441     SDValue Chain = Load->getChain();
8442     SDValue BasePtr = Load->getBasePtr();
8443     MachineMemOperand *MMO = Load->getMemOperand();
8444 
8445     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8446 
8447     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8448                                    BasePtr, RealMemVT, MMO);
8449 
8450     if (!MemVT.isVector()) {
8451       SDValue Ops[] = {
8452         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8453         NewLD.getValue(1)
8454       };
8455 
8456       return DAG.getMergeValues(Ops, DL);
8457     }
8458 
8459     SmallVector<SDValue, 3> Elts;
8460     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8461       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8462                                 DAG.getConstant(I, DL, MVT::i32));
8463 
8464       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8465     }
8466 
8467     SDValue Ops[] = {
8468       DAG.getBuildVector(MemVT, DL, Elts),
8469       NewLD.getValue(1)
8470     };
8471 
8472     return DAG.getMergeValues(Ops, DL);
8473   }
8474 
8475   if (!MemVT.isVector())
8476     return SDValue();
8477 
8478   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8479          "Custom lowering for non-i32 vectors hasn't been implemented.");
8480 
8481   unsigned Alignment = Load->getAlignment();
8482   unsigned AS = Load->getAddressSpace();
8483   if (Subtarget->hasLDSMisalignedBug() &&
8484       AS == AMDGPUAS::FLAT_ADDRESS &&
8485       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8486     return SplitVectorLoad(Op, DAG);
8487   }
8488 
8489   MachineFunction &MF = DAG.getMachineFunction();
8490   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8491   // If there is a possibility that flat instruction access scratch memory
8492   // then we need to use the same legalization rules we use for private.
8493   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8494       !Subtarget->hasMultiDwordFlatScratchAddressing())
8495     AS = MFI->hasFlatScratchInit() ?
8496          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8497 
8498   unsigned NumElements = MemVT.getVectorNumElements();
8499 
8500   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8501       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8502     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8503       if (MemVT.isPow2VectorType())
8504         return SDValue();
8505       return WidenOrSplitVectorLoad(Op, DAG);
8506     }
8507     // Non-uniform loads will be selected to MUBUF instructions, so they
8508     // have the same legalization requirements as global and private
8509     // loads.
8510     //
8511   }
8512 
8513   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8514       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8515       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8516     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8517         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8518         Alignment >= 4 && NumElements < 32) {
8519       if (MemVT.isPow2VectorType())
8520         return SDValue();
8521       return WidenOrSplitVectorLoad(Op, DAG);
8522     }
8523     // Non-uniform loads will be selected to MUBUF instructions, so they
8524     // have the same legalization requirements as global and private
8525     // loads.
8526     //
8527   }
8528   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8529       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8530       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8531       AS == AMDGPUAS::FLAT_ADDRESS) {
8532     if (NumElements > 4)
8533       return SplitVectorLoad(Op, DAG);
8534     // v3 loads not supported on SI.
8535     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8536       return WidenOrSplitVectorLoad(Op, DAG);
8537 
8538     // v3 and v4 loads are supported for private and global memory.
8539     return SDValue();
8540   }
8541   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8542     // Depending on the setting of the private_element_size field in the
8543     // resource descriptor, we can only make private accesses up to a certain
8544     // size.
8545     switch (Subtarget->getMaxPrivateElementSize()) {
8546     case 4: {
8547       SDValue Ops[2];
8548       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8549       return DAG.getMergeValues(Ops, DL);
8550     }
8551     case 8:
8552       if (NumElements > 2)
8553         return SplitVectorLoad(Op, DAG);
8554       return SDValue();
8555     case 16:
8556       // Same as global/flat
8557       if (NumElements > 4)
8558         return SplitVectorLoad(Op, DAG);
8559       // v3 loads not supported on SI.
8560       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8561         return WidenOrSplitVectorLoad(Op, DAG);
8562 
8563       return SDValue();
8564     default:
8565       llvm_unreachable("unsupported private_element_size");
8566     }
8567   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8568     bool Fast = false;
8569     auto Flags = Load->getMemOperand()->getFlags();
8570     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8571                                            Load->getAlign(), Flags, &Fast) &&
8572         Fast)
8573       return SDValue();
8574 
8575     if (MemVT.isVector())
8576       return SplitVectorLoad(Op, DAG);
8577   }
8578 
8579   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8580                                       MemVT, *Load->getMemOperand())) {
8581     SDValue Ops[2];
8582     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8583     return DAG.getMergeValues(Ops, DL);
8584   }
8585 
8586   return SDValue();
8587 }
8588 
8589 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8590   EVT VT = Op.getValueType();
8591   if (VT.getSizeInBits() == 128)
8592     return splitTernaryVectorOp(Op, DAG);
8593 
8594   assert(VT.getSizeInBits() == 64);
8595 
8596   SDLoc DL(Op);
8597   SDValue Cond = Op.getOperand(0);
8598 
8599   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8600   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8601 
8602   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8603   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8604 
8605   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8606   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8607 
8608   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8609 
8610   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8611   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8612 
8613   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8614 
8615   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8616   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8617 }
8618 
8619 // Catch division cases where we can use shortcuts with rcp and rsq
8620 // instructions.
8621 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8622                                               SelectionDAG &DAG) const {
8623   SDLoc SL(Op);
8624   SDValue LHS = Op.getOperand(0);
8625   SDValue RHS = Op.getOperand(1);
8626   EVT VT = Op.getValueType();
8627   const SDNodeFlags Flags = Op->getFlags();
8628 
8629   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8630 
8631   // Without !fpmath accuracy information, we can't do more because we don't
8632   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8633   if (!AllowInaccurateRcp)
8634     return SDValue();
8635 
8636   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8637     if (CLHS->isExactlyValue(1.0)) {
8638       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8639       // the CI documentation has a worst case error of 1 ulp.
8640       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8641       // use it as long as we aren't trying to use denormals.
8642       //
8643       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8644 
8645       // 1.0 / sqrt(x) -> rsq(x)
8646 
8647       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8648       // error seems really high at 2^29 ULP.
8649       if (RHS.getOpcode() == ISD::FSQRT)
8650         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8651 
8652       // 1.0 / x -> rcp(x)
8653       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8654     }
8655 
8656     // Same as for 1.0, but expand the sign out of the constant.
8657     if (CLHS->isExactlyValue(-1.0)) {
8658       // -1.0 / x -> rcp (fneg x)
8659       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8660       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8661     }
8662   }
8663 
8664   // Turn into multiply by the reciprocal.
8665   // x / y -> x * (1.0 / y)
8666   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8667   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8668 }
8669 
8670 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8671                                                 SelectionDAG &DAG) const {
8672   SDLoc SL(Op);
8673   SDValue X = Op.getOperand(0);
8674   SDValue Y = Op.getOperand(1);
8675   EVT VT = Op.getValueType();
8676   const SDNodeFlags Flags = Op->getFlags();
8677 
8678   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8679                             DAG.getTarget().Options.UnsafeFPMath;
8680   if (!AllowInaccurateDiv)
8681     return SDValue();
8682 
8683   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8684   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8685 
8686   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8687   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8688 
8689   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8690   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8691   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8692   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8693   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8694   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8695 }
8696 
8697 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8698                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8699                           SDNodeFlags Flags) {
8700   if (GlueChain->getNumValues() <= 1) {
8701     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8702   }
8703 
8704   assert(GlueChain->getNumValues() == 3);
8705 
8706   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8707   switch (Opcode) {
8708   default: llvm_unreachable("no chain equivalent for opcode");
8709   case ISD::FMUL:
8710     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8711     break;
8712   }
8713 
8714   return DAG.getNode(Opcode, SL, VTList,
8715                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8716                      Flags);
8717 }
8718 
8719 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8720                            EVT VT, SDValue A, SDValue B, SDValue C,
8721                            SDValue GlueChain, SDNodeFlags Flags) {
8722   if (GlueChain->getNumValues() <= 1) {
8723     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8724   }
8725 
8726   assert(GlueChain->getNumValues() == 3);
8727 
8728   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8729   switch (Opcode) {
8730   default: llvm_unreachable("no chain equivalent for opcode");
8731   case ISD::FMA:
8732     Opcode = AMDGPUISD::FMA_W_CHAIN;
8733     break;
8734   }
8735 
8736   return DAG.getNode(Opcode, SL, VTList,
8737                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8738                      Flags);
8739 }
8740 
8741 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8742   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8743     return FastLowered;
8744 
8745   SDLoc SL(Op);
8746   SDValue Src0 = Op.getOperand(0);
8747   SDValue Src1 = Op.getOperand(1);
8748 
8749   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8750   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8751 
8752   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8753   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8754 
8755   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8756   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8757 
8758   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8759 }
8760 
8761 // Faster 2.5 ULP division that does not support denormals.
8762 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8763   SDLoc SL(Op);
8764   SDValue LHS = Op.getOperand(1);
8765   SDValue RHS = Op.getOperand(2);
8766 
8767   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8768 
8769   const APFloat K0Val(BitsToFloat(0x6f800000));
8770   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8771 
8772   const APFloat K1Val(BitsToFloat(0x2f800000));
8773   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8774 
8775   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8776 
8777   EVT SetCCVT =
8778     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8779 
8780   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8781 
8782   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8783 
8784   // TODO: Should this propagate fast-math-flags?
8785   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8786 
8787   // rcp does not support denormals.
8788   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8789 
8790   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8791 
8792   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8793 }
8794 
8795 // Returns immediate value for setting the F32 denorm mode when using the
8796 // S_DENORM_MODE instruction.
8797 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8798                                     const SDLoc &SL, const GCNSubtarget *ST) {
8799   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8800   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8801                                 ? FP_DENORM_FLUSH_NONE
8802                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8803 
8804   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8805   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8806 }
8807 
8808 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8809   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8810     return FastLowered;
8811 
8812   // The selection matcher assumes anything with a chain selecting to a
8813   // mayRaiseFPException machine instruction. Since we're introducing a chain
8814   // here, we need to explicitly report nofpexcept for the regular fdiv
8815   // lowering.
8816   SDNodeFlags Flags = Op->getFlags();
8817   Flags.setNoFPExcept(true);
8818 
8819   SDLoc SL(Op);
8820   SDValue LHS = Op.getOperand(0);
8821   SDValue RHS = Op.getOperand(1);
8822 
8823   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8824 
8825   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8826 
8827   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8828                                           {RHS, RHS, LHS}, Flags);
8829   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8830                                         {LHS, RHS, LHS}, Flags);
8831 
8832   // Denominator is scaled to not be denormal, so using rcp is ok.
8833   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8834                                   DenominatorScaled, Flags);
8835   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8836                                      DenominatorScaled, Flags);
8837 
8838   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8839                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8840                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8841   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8842 
8843   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8844 
8845   if (!HasFP32Denormals) {
8846     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8847     // lowering. The chain dependence is insufficient, and we need glue. We do
8848     // not need the glue variants in a strictfp function.
8849 
8850     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8851 
8852     SDNode *EnableDenorm;
8853     if (Subtarget->hasDenormModeInst()) {
8854       const SDValue EnableDenormValue =
8855           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8856 
8857       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8858                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8859     } else {
8860       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8861                                                         SL, MVT::i32);
8862       EnableDenorm =
8863           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8864                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8865     }
8866 
8867     SDValue Ops[3] = {
8868       NegDivScale0,
8869       SDValue(EnableDenorm, 0),
8870       SDValue(EnableDenorm, 1)
8871     };
8872 
8873     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8874   }
8875 
8876   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8877                              ApproxRcp, One, NegDivScale0, Flags);
8878 
8879   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8880                              ApproxRcp, Fma0, Flags);
8881 
8882   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8883                            Fma1, Fma1, Flags);
8884 
8885   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8886                              NumeratorScaled, Mul, Flags);
8887 
8888   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8889                              Fma2, Fma1, Mul, Fma2, Flags);
8890 
8891   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8892                              NumeratorScaled, Fma3, Flags);
8893 
8894   if (!HasFP32Denormals) {
8895     SDNode *DisableDenorm;
8896     if (Subtarget->hasDenormModeInst()) {
8897       const SDValue DisableDenormValue =
8898           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8899 
8900       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8901                                   Fma4.getValue(1), DisableDenormValue,
8902                                   Fma4.getValue(2)).getNode();
8903     } else {
8904       const SDValue DisableDenormValue =
8905           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8906 
8907       DisableDenorm = DAG.getMachineNode(
8908           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8909           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8910     }
8911 
8912     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8913                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8914     DAG.setRoot(OutputChain);
8915   }
8916 
8917   SDValue Scale = NumeratorScaled.getValue(1);
8918   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8919                              {Fma4, Fma1, Fma3, Scale}, Flags);
8920 
8921   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8922 }
8923 
8924 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8925   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8926     return FastLowered;
8927 
8928   SDLoc SL(Op);
8929   SDValue X = Op.getOperand(0);
8930   SDValue Y = Op.getOperand(1);
8931 
8932   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8933 
8934   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8935 
8936   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8937 
8938   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8939 
8940   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8941 
8942   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8943 
8944   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8945 
8946   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8947 
8948   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8949 
8950   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8951   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8952 
8953   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8954                              NegDivScale0, Mul, DivScale1);
8955 
8956   SDValue Scale;
8957 
8958   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8959     // Workaround a hardware bug on SI where the condition output from div_scale
8960     // is not usable.
8961 
8962     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8963 
8964     // Figure out if the scale to use for div_fmas.
8965     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8966     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8967     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8968     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8969 
8970     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8971     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8972 
8973     SDValue Scale0Hi
8974       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8975     SDValue Scale1Hi
8976       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8977 
8978     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8979     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8980     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8981   } else {
8982     Scale = DivScale1.getValue(1);
8983   }
8984 
8985   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8986                              Fma4, Fma3, Mul, Scale);
8987 
8988   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8989 }
8990 
8991 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8992   EVT VT = Op.getValueType();
8993 
8994   if (VT == MVT::f32)
8995     return LowerFDIV32(Op, DAG);
8996 
8997   if (VT == MVT::f64)
8998     return LowerFDIV64(Op, DAG);
8999 
9000   if (VT == MVT::f16)
9001     return LowerFDIV16(Op, DAG);
9002 
9003   llvm_unreachable("Unexpected type for fdiv");
9004 }
9005 
9006 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9007   SDLoc DL(Op);
9008   StoreSDNode *Store = cast<StoreSDNode>(Op);
9009   EVT VT = Store->getMemoryVT();
9010 
9011   if (VT == MVT::i1) {
9012     return DAG.getTruncStore(Store->getChain(), DL,
9013        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9014        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9015   }
9016 
9017   assert(VT.isVector() &&
9018          Store->getValue().getValueType().getScalarType() == MVT::i32);
9019 
9020   unsigned AS = Store->getAddressSpace();
9021   if (Subtarget->hasLDSMisalignedBug() &&
9022       AS == AMDGPUAS::FLAT_ADDRESS &&
9023       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9024     return SplitVectorStore(Op, DAG);
9025   }
9026 
9027   MachineFunction &MF = DAG.getMachineFunction();
9028   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9029   // If there is a possibility that flat instruction access scratch memory
9030   // then we need to use the same legalization rules we use for private.
9031   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9032       !Subtarget->hasMultiDwordFlatScratchAddressing())
9033     AS = MFI->hasFlatScratchInit() ?
9034          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9035 
9036   unsigned NumElements = VT.getVectorNumElements();
9037   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9038       AS == AMDGPUAS::FLAT_ADDRESS) {
9039     if (NumElements > 4)
9040       return SplitVectorStore(Op, DAG);
9041     // v3 stores not supported on SI.
9042     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9043       return SplitVectorStore(Op, DAG);
9044 
9045     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9046                                         VT, *Store->getMemOperand()))
9047       return expandUnalignedStore(Store, DAG);
9048 
9049     return SDValue();
9050   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9051     switch (Subtarget->getMaxPrivateElementSize()) {
9052     case 4:
9053       return scalarizeVectorStore(Store, DAG);
9054     case 8:
9055       if (NumElements > 2)
9056         return SplitVectorStore(Op, DAG);
9057       return SDValue();
9058     case 16:
9059       if (NumElements > 4 ||
9060           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9061         return SplitVectorStore(Op, DAG);
9062       return SDValue();
9063     default:
9064       llvm_unreachable("unsupported private_element_size");
9065     }
9066   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9067     bool Fast = false;
9068     auto Flags = Store->getMemOperand()->getFlags();
9069     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9070                                            Store->getAlign(), Flags, &Fast) &&
9071         Fast)
9072       return SDValue();
9073 
9074     if (VT.isVector())
9075       return SplitVectorStore(Op, DAG);
9076 
9077     return expandUnalignedStore(Store, DAG);
9078   }
9079 
9080   // Probably an invalid store. If so we'll end up emitting a selection error.
9081   return SDValue();
9082 }
9083 
9084 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9085   SDLoc DL(Op);
9086   EVT VT = Op.getValueType();
9087   SDValue Arg = Op.getOperand(0);
9088   SDValue TrigVal;
9089 
9090   // Propagate fast-math flags so that the multiply we introduce can be folded
9091   // if Arg is already the result of a multiply by constant.
9092   auto Flags = Op->getFlags();
9093 
9094   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9095 
9096   if (Subtarget->hasTrigReducedRange()) {
9097     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9098     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9099   } else {
9100     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9101   }
9102 
9103   switch (Op.getOpcode()) {
9104   case ISD::FCOS:
9105     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9106   case ISD::FSIN:
9107     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9108   default:
9109     llvm_unreachable("Wrong trig opcode");
9110   }
9111 }
9112 
9113 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9114   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9115   assert(AtomicNode->isCompareAndSwap());
9116   unsigned AS = AtomicNode->getAddressSpace();
9117 
9118   // No custom lowering required for local address space
9119   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9120     return Op;
9121 
9122   // Non-local address space requires custom lowering for atomic compare
9123   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9124   SDLoc DL(Op);
9125   SDValue ChainIn = Op.getOperand(0);
9126   SDValue Addr = Op.getOperand(1);
9127   SDValue Old = Op.getOperand(2);
9128   SDValue New = Op.getOperand(3);
9129   EVT VT = Op.getValueType();
9130   MVT SimpleVT = VT.getSimpleVT();
9131   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9132 
9133   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9134   SDValue Ops[] = { ChainIn, Addr, NewOld };
9135 
9136   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9137                                  Ops, VT, AtomicNode->getMemOperand());
9138 }
9139 
9140 //===----------------------------------------------------------------------===//
9141 // Custom DAG optimizations
9142 //===----------------------------------------------------------------------===//
9143 
9144 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9145                                                      DAGCombinerInfo &DCI) const {
9146   EVT VT = N->getValueType(0);
9147   EVT ScalarVT = VT.getScalarType();
9148   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9149     return SDValue();
9150 
9151   SelectionDAG &DAG = DCI.DAG;
9152   SDLoc DL(N);
9153 
9154   SDValue Src = N->getOperand(0);
9155   EVT SrcVT = Src.getValueType();
9156 
9157   // TODO: We could try to match extracting the higher bytes, which would be
9158   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9159   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9160   // about in practice.
9161   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9162     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9163       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9164       DCI.AddToWorklist(Cvt.getNode());
9165 
9166       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9167       if (ScalarVT != MVT::f32) {
9168         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9169                           DAG.getTargetConstant(0, DL, MVT::i32));
9170       }
9171       return Cvt;
9172     }
9173   }
9174 
9175   return SDValue();
9176 }
9177 
9178 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9179 
9180 // This is a variant of
9181 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9182 //
9183 // The normal DAG combiner will do this, but only if the add has one use since
9184 // that would increase the number of instructions.
9185 //
9186 // This prevents us from seeing a constant offset that can be folded into a
9187 // memory instruction's addressing mode. If we know the resulting add offset of
9188 // a pointer can be folded into an addressing offset, we can replace the pointer
9189 // operand with the add of new constant offset. This eliminates one of the uses,
9190 // and may allow the remaining use to also be simplified.
9191 //
9192 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9193                                                unsigned AddrSpace,
9194                                                EVT MemVT,
9195                                                DAGCombinerInfo &DCI) const {
9196   SDValue N0 = N->getOperand(0);
9197   SDValue N1 = N->getOperand(1);
9198 
9199   // We only do this to handle cases where it's profitable when there are
9200   // multiple uses of the add, so defer to the standard combine.
9201   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9202       N0->hasOneUse())
9203     return SDValue();
9204 
9205   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9206   if (!CN1)
9207     return SDValue();
9208 
9209   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9210   if (!CAdd)
9211     return SDValue();
9212 
9213   // If the resulting offset is too large, we can't fold it into the addressing
9214   // mode offset.
9215   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9216   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9217 
9218   AddrMode AM;
9219   AM.HasBaseReg = true;
9220   AM.BaseOffs = Offset.getSExtValue();
9221   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9222     return SDValue();
9223 
9224   SelectionDAG &DAG = DCI.DAG;
9225   SDLoc SL(N);
9226   EVT VT = N->getValueType(0);
9227 
9228   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9229   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9230 
9231   SDNodeFlags Flags;
9232   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9233                           (N0.getOpcode() == ISD::OR ||
9234                            N0->getFlags().hasNoUnsignedWrap()));
9235 
9236   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9237 }
9238 
9239 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9240 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9241 /// specific intrinsic, but they all place the pointer operand first.
9242 static unsigned getBasePtrIndex(const MemSDNode *N) {
9243   switch (N->getOpcode()) {
9244   case ISD::STORE:
9245   case ISD::INTRINSIC_W_CHAIN:
9246   case ISD::INTRINSIC_VOID:
9247     return 2;
9248   default:
9249     return 1;
9250   }
9251 }
9252 
9253 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9254                                                   DAGCombinerInfo &DCI) const {
9255   SelectionDAG &DAG = DCI.DAG;
9256   SDLoc SL(N);
9257 
9258   unsigned PtrIdx = getBasePtrIndex(N);
9259   SDValue Ptr = N->getOperand(PtrIdx);
9260 
9261   // TODO: We could also do this for multiplies.
9262   if (Ptr.getOpcode() == ISD::SHL) {
9263     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9264                                           N->getMemoryVT(), DCI);
9265     if (NewPtr) {
9266       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9267 
9268       NewOps[PtrIdx] = NewPtr;
9269       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9270     }
9271   }
9272 
9273   return SDValue();
9274 }
9275 
9276 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9277   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9278          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9279          (Opc == ISD::XOR && Val == 0);
9280 }
9281 
9282 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9283 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9284 // integer combine opportunities since most 64-bit operations are decomposed
9285 // this way.  TODO: We won't want this for SALU especially if it is an inline
9286 // immediate.
9287 SDValue SITargetLowering::splitBinaryBitConstantOp(
9288   DAGCombinerInfo &DCI,
9289   const SDLoc &SL,
9290   unsigned Opc, SDValue LHS,
9291   const ConstantSDNode *CRHS) const {
9292   uint64_t Val = CRHS->getZExtValue();
9293   uint32_t ValLo = Lo_32(Val);
9294   uint32_t ValHi = Hi_32(Val);
9295   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9296 
9297     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9298          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9299         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9300     // If we need to materialize a 64-bit immediate, it will be split up later
9301     // anyway. Avoid creating the harder to understand 64-bit immediate
9302     // materialization.
9303     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9304   }
9305 
9306   return SDValue();
9307 }
9308 
9309 // Returns true if argument is a boolean value which is not serialized into
9310 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9311 static bool isBoolSGPR(SDValue V) {
9312   if (V.getValueType() != MVT::i1)
9313     return false;
9314   switch (V.getOpcode()) {
9315   default:
9316     break;
9317   case ISD::SETCC:
9318   case AMDGPUISD::FP_CLASS:
9319     return true;
9320   case ISD::AND:
9321   case ISD::OR:
9322   case ISD::XOR:
9323     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9324   }
9325   return false;
9326 }
9327 
9328 // If a constant has all zeroes or all ones within each byte return it.
9329 // Otherwise return 0.
9330 static uint32_t getConstantPermuteMask(uint32_t C) {
9331   // 0xff for any zero byte in the mask
9332   uint32_t ZeroByteMask = 0;
9333   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9334   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9335   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9336   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9337   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9338   if ((NonZeroByteMask & C) != NonZeroByteMask)
9339     return 0; // Partial bytes selected.
9340   return C;
9341 }
9342 
9343 // Check if a node selects whole bytes from its operand 0 starting at a byte
9344 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9345 // or -1 if not succeeded.
9346 // Note byte select encoding:
9347 // value 0-3 selects corresponding source byte;
9348 // value 0xc selects zero;
9349 // value 0xff selects 0xff.
9350 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9351   assert(V.getValueSizeInBits() == 32);
9352 
9353   if (V.getNumOperands() != 2)
9354     return ~0;
9355 
9356   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9357   if (!N1)
9358     return ~0;
9359 
9360   uint32_t C = N1->getZExtValue();
9361 
9362   switch (V.getOpcode()) {
9363   default:
9364     break;
9365   case ISD::AND:
9366     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9367       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9368     }
9369     break;
9370 
9371   case ISD::OR:
9372     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9373       return (0x03020100 & ~ConstMask) | ConstMask;
9374     }
9375     break;
9376 
9377   case ISD::SHL:
9378     if (C % 8)
9379       return ~0;
9380 
9381     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9382 
9383   case ISD::SRL:
9384     if (C % 8)
9385       return ~0;
9386 
9387     return uint32_t(0x0c0c0c0c03020100ull >> C);
9388   }
9389 
9390   return ~0;
9391 }
9392 
9393 SDValue SITargetLowering::performAndCombine(SDNode *N,
9394                                             DAGCombinerInfo &DCI) const {
9395   if (DCI.isBeforeLegalize())
9396     return SDValue();
9397 
9398   SelectionDAG &DAG = DCI.DAG;
9399   EVT VT = N->getValueType(0);
9400   SDValue LHS = N->getOperand(0);
9401   SDValue RHS = N->getOperand(1);
9402 
9403 
9404   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9405   if (VT == MVT::i64 && CRHS) {
9406     if (SDValue Split
9407         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9408       return Split;
9409   }
9410 
9411   if (CRHS && VT == MVT::i32) {
9412     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9413     // nb = number of trailing zeroes in mask
9414     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9415     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9416     uint64_t Mask = CRHS->getZExtValue();
9417     unsigned Bits = countPopulation(Mask);
9418     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9419         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9420       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9421         unsigned Shift = CShift->getZExtValue();
9422         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9423         unsigned Offset = NB + Shift;
9424         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9425           SDLoc SL(N);
9426           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9427                                     LHS->getOperand(0),
9428                                     DAG.getConstant(Offset, SL, MVT::i32),
9429                                     DAG.getConstant(Bits, SL, MVT::i32));
9430           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9431           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9432                                     DAG.getValueType(NarrowVT));
9433           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9434                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9435           return Shl;
9436         }
9437       }
9438     }
9439 
9440     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9441     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9442         isa<ConstantSDNode>(LHS.getOperand(2))) {
9443       uint32_t Sel = getConstantPermuteMask(Mask);
9444       if (!Sel)
9445         return SDValue();
9446 
9447       // Select 0xc for all zero bytes
9448       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9449       SDLoc DL(N);
9450       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9451                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9452     }
9453   }
9454 
9455   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9456   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9457   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9458     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9459     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9460 
9461     SDValue X = LHS.getOperand(0);
9462     SDValue Y = RHS.getOperand(0);
9463     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9464       return SDValue();
9465 
9466     if (LCC == ISD::SETO) {
9467       if (X != LHS.getOperand(1))
9468         return SDValue();
9469 
9470       if (RCC == ISD::SETUNE) {
9471         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9472         if (!C1 || !C1->isInfinity() || C1->isNegative())
9473           return SDValue();
9474 
9475         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9476                               SIInstrFlags::N_SUBNORMAL |
9477                               SIInstrFlags::N_ZERO |
9478                               SIInstrFlags::P_ZERO |
9479                               SIInstrFlags::P_SUBNORMAL |
9480                               SIInstrFlags::P_NORMAL;
9481 
9482         static_assert(((~(SIInstrFlags::S_NAN |
9483                           SIInstrFlags::Q_NAN |
9484                           SIInstrFlags::N_INFINITY |
9485                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9486                       "mask not equal");
9487 
9488         SDLoc DL(N);
9489         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9490                            X, DAG.getConstant(Mask, DL, MVT::i32));
9491       }
9492     }
9493   }
9494 
9495   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9496     std::swap(LHS, RHS);
9497 
9498   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9499       RHS.hasOneUse()) {
9500     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9501     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9502     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9503     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9504     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9505         (RHS.getOperand(0) == LHS.getOperand(0) &&
9506          LHS.getOperand(0) == LHS.getOperand(1))) {
9507       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9508       unsigned NewMask = LCC == ISD::SETO ?
9509         Mask->getZExtValue() & ~OrdMask :
9510         Mask->getZExtValue() & OrdMask;
9511 
9512       SDLoc DL(N);
9513       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9514                          DAG.getConstant(NewMask, DL, MVT::i32));
9515     }
9516   }
9517 
9518   if (VT == MVT::i32 &&
9519       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9520     // and x, (sext cc from i1) => select cc, x, 0
9521     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9522       std::swap(LHS, RHS);
9523     if (isBoolSGPR(RHS.getOperand(0)))
9524       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9525                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9526   }
9527 
9528   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9529   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9530   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9531       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9532     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9533     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9534     if (LHSMask != ~0u && RHSMask != ~0u) {
9535       // Canonicalize the expression in an attempt to have fewer unique masks
9536       // and therefore fewer registers used to hold the masks.
9537       if (LHSMask > RHSMask) {
9538         std::swap(LHSMask, RHSMask);
9539         std::swap(LHS, RHS);
9540       }
9541 
9542       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9543       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9544       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9545       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9546 
9547       // Check of we need to combine values from two sources within a byte.
9548       if (!(LHSUsedLanes & RHSUsedLanes) &&
9549           // If we select high and lower word keep it for SDWA.
9550           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9551           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9552         // Each byte in each mask is either selector mask 0-3, or has higher
9553         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9554         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9555         // mask which is not 0xff wins. By anding both masks we have a correct
9556         // result except that 0x0c shall be corrected to give 0x0c only.
9557         uint32_t Mask = LHSMask & RHSMask;
9558         for (unsigned I = 0; I < 32; I += 8) {
9559           uint32_t ByteSel = 0xff << I;
9560           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9561             Mask &= (0x0c << I) & 0xffffffff;
9562         }
9563 
9564         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9565         // or 0x0c.
9566         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9567         SDLoc DL(N);
9568 
9569         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9570                            LHS.getOperand(0), RHS.getOperand(0),
9571                            DAG.getConstant(Sel, DL, MVT::i32));
9572       }
9573     }
9574   }
9575 
9576   return SDValue();
9577 }
9578 
9579 SDValue SITargetLowering::performOrCombine(SDNode *N,
9580                                            DAGCombinerInfo &DCI) const {
9581   SelectionDAG &DAG = DCI.DAG;
9582   SDValue LHS = N->getOperand(0);
9583   SDValue RHS = N->getOperand(1);
9584 
9585   EVT VT = N->getValueType(0);
9586   if (VT == MVT::i1) {
9587     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9588     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9589         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9590       SDValue Src = LHS.getOperand(0);
9591       if (Src != RHS.getOperand(0))
9592         return SDValue();
9593 
9594       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9595       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9596       if (!CLHS || !CRHS)
9597         return SDValue();
9598 
9599       // Only 10 bits are used.
9600       static const uint32_t MaxMask = 0x3ff;
9601 
9602       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9603       SDLoc DL(N);
9604       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9605                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9606     }
9607 
9608     return SDValue();
9609   }
9610 
9611   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9612   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9613       LHS.getOpcode() == AMDGPUISD::PERM &&
9614       isa<ConstantSDNode>(LHS.getOperand(2))) {
9615     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9616     if (!Sel)
9617       return SDValue();
9618 
9619     Sel |= LHS.getConstantOperandVal(2);
9620     SDLoc DL(N);
9621     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9622                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9623   }
9624 
9625   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9626   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9627   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9628       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9629     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9630     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9631     if (LHSMask != ~0u && RHSMask != ~0u) {
9632       // Canonicalize the expression in an attempt to have fewer unique masks
9633       // and therefore fewer registers used to hold the masks.
9634       if (LHSMask > RHSMask) {
9635         std::swap(LHSMask, RHSMask);
9636         std::swap(LHS, RHS);
9637       }
9638 
9639       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9640       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9641       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9642       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9643 
9644       // Check of we need to combine values from two sources within a byte.
9645       if (!(LHSUsedLanes & RHSUsedLanes) &&
9646           // If we select high and lower word keep it for SDWA.
9647           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9648           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9649         // Kill zero bytes selected by other mask. Zero value is 0xc.
9650         LHSMask &= ~RHSUsedLanes;
9651         RHSMask &= ~LHSUsedLanes;
9652         // Add 4 to each active LHS lane
9653         LHSMask |= LHSUsedLanes & 0x04040404;
9654         // Combine masks
9655         uint32_t Sel = LHSMask | RHSMask;
9656         SDLoc DL(N);
9657 
9658         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9659                            LHS.getOperand(0), RHS.getOperand(0),
9660                            DAG.getConstant(Sel, DL, MVT::i32));
9661       }
9662     }
9663   }
9664 
9665   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9666     return SDValue();
9667 
9668   // TODO: This could be a generic combine with a predicate for extracting the
9669   // high half of an integer being free.
9670 
9671   // (or i64:x, (zero_extend i32:y)) ->
9672   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9673   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9674       RHS.getOpcode() != ISD::ZERO_EXTEND)
9675     std::swap(LHS, RHS);
9676 
9677   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9678     SDValue ExtSrc = RHS.getOperand(0);
9679     EVT SrcVT = ExtSrc.getValueType();
9680     if (SrcVT == MVT::i32) {
9681       SDLoc SL(N);
9682       SDValue LowLHS, HiBits;
9683       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9684       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9685 
9686       DCI.AddToWorklist(LowOr.getNode());
9687       DCI.AddToWorklist(HiBits.getNode());
9688 
9689       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9690                                 LowOr, HiBits);
9691       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9692     }
9693   }
9694 
9695   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9696   if (CRHS) {
9697     if (SDValue Split
9698           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9699                                      N->getOperand(0), CRHS))
9700       return Split;
9701   }
9702 
9703   return SDValue();
9704 }
9705 
9706 SDValue SITargetLowering::performXorCombine(SDNode *N,
9707                                             DAGCombinerInfo &DCI) const {
9708   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9709     return RV;
9710 
9711   EVT VT = N->getValueType(0);
9712   if (VT != MVT::i64)
9713     return SDValue();
9714 
9715   SDValue LHS = N->getOperand(0);
9716   SDValue RHS = N->getOperand(1);
9717 
9718   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9719   if (CRHS) {
9720     if (SDValue Split
9721           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9722       return Split;
9723   }
9724 
9725   return SDValue();
9726 }
9727 
9728 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9729                                                    DAGCombinerInfo &DCI) const {
9730   if (!Subtarget->has16BitInsts() ||
9731       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9732     return SDValue();
9733 
9734   EVT VT = N->getValueType(0);
9735   if (VT != MVT::i32)
9736     return SDValue();
9737 
9738   SDValue Src = N->getOperand(0);
9739   if (Src.getValueType() != MVT::i16)
9740     return SDValue();
9741 
9742   return SDValue();
9743 }
9744 
9745 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9746                                                         DAGCombinerInfo &DCI)
9747                                                         const {
9748   SDValue Src = N->getOperand(0);
9749   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9750 
9751   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9752       VTSign->getVT() == MVT::i8) ||
9753       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9754       VTSign->getVT() == MVT::i16)) &&
9755       Src.hasOneUse()) {
9756     auto *M = cast<MemSDNode>(Src);
9757     SDValue Ops[] = {
9758       Src.getOperand(0), // Chain
9759       Src.getOperand(1), // rsrc
9760       Src.getOperand(2), // vindex
9761       Src.getOperand(3), // voffset
9762       Src.getOperand(4), // soffset
9763       Src.getOperand(5), // offset
9764       Src.getOperand(6),
9765       Src.getOperand(7)
9766     };
9767     // replace with BUFFER_LOAD_BYTE/SHORT
9768     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9769                                          Src.getOperand(0).getValueType());
9770     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9771                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9772     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9773                                                           ResList,
9774                                                           Ops, M->getMemoryVT(),
9775                                                           M->getMemOperand());
9776     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9777                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9778   }
9779   return SDValue();
9780 }
9781 
9782 SDValue SITargetLowering::performClassCombine(SDNode *N,
9783                                               DAGCombinerInfo &DCI) const {
9784   SelectionDAG &DAG = DCI.DAG;
9785   SDValue Mask = N->getOperand(1);
9786 
9787   // fp_class x, 0 -> false
9788   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9789     if (CMask->isZero())
9790       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9791   }
9792 
9793   if (N->getOperand(0).isUndef())
9794     return DAG.getUNDEF(MVT::i1);
9795 
9796   return SDValue();
9797 }
9798 
9799 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9800                                             DAGCombinerInfo &DCI) const {
9801   EVT VT = N->getValueType(0);
9802   SDValue N0 = N->getOperand(0);
9803 
9804   if (N0.isUndef())
9805     return N0;
9806 
9807   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9808                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9809     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9810                            N->getFlags());
9811   }
9812 
9813   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9814     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9815                            N0.getOperand(0), N->getFlags());
9816   }
9817 
9818   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9819 }
9820 
9821 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9822                                        unsigned MaxDepth) const {
9823   unsigned Opcode = Op.getOpcode();
9824   if (Opcode == ISD::FCANONICALIZE)
9825     return true;
9826 
9827   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9828     auto F = CFP->getValueAPF();
9829     if (F.isNaN() && F.isSignaling())
9830       return false;
9831     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9832   }
9833 
9834   // If source is a result of another standard FP operation it is already in
9835   // canonical form.
9836   if (MaxDepth == 0)
9837     return false;
9838 
9839   switch (Opcode) {
9840   // These will flush denorms if required.
9841   case ISD::FADD:
9842   case ISD::FSUB:
9843   case ISD::FMUL:
9844   case ISD::FCEIL:
9845   case ISD::FFLOOR:
9846   case ISD::FMA:
9847   case ISD::FMAD:
9848   case ISD::FSQRT:
9849   case ISD::FDIV:
9850   case ISD::FREM:
9851   case ISD::FP_ROUND:
9852   case ISD::FP_EXTEND:
9853   case AMDGPUISD::FMUL_LEGACY:
9854   case AMDGPUISD::FMAD_FTZ:
9855   case AMDGPUISD::RCP:
9856   case AMDGPUISD::RSQ:
9857   case AMDGPUISD::RSQ_CLAMP:
9858   case AMDGPUISD::RCP_LEGACY:
9859   case AMDGPUISD::RCP_IFLAG:
9860   case AMDGPUISD::DIV_SCALE:
9861   case AMDGPUISD::DIV_FMAS:
9862   case AMDGPUISD::DIV_FIXUP:
9863   case AMDGPUISD::FRACT:
9864   case AMDGPUISD::LDEXP:
9865   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9866   case AMDGPUISD::CVT_F32_UBYTE0:
9867   case AMDGPUISD::CVT_F32_UBYTE1:
9868   case AMDGPUISD::CVT_F32_UBYTE2:
9869   case AMDGPUISD::CVT_F32_UBYTE3:
9870     return true;
9871 
9872   // It can/will be lowered or combined as a bit operation.
9873   // Need to check their input recursively to handle.
9874   case ISD::FNEG:
9875   case ISD::FABS:
9876   case ISD::FCOPYSIGN:
9877     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9878 
9879   case ISD::FSIN:
9880   case ISD::FCOS:
9881   case ISD::FSINCOS:
9882     return Op.getValueType().getScalarType() != MVT::f16;
9883 
9884   case ISD::FMINNUM:
9885   case ISD::FMAXNUM:
9886   case ISD::FMINNUM_IEEE:
9887   case ISD::FMAXNUM_IEEE:
9888   case AMDGPUISD::CLAMP:
9889   case AMDGPUISD::FMED3:
9890   case AMDGPUISD::FMAX3:
9891   case AMDGPUISD::FMIN3: {
9892     // FIXME: Shouldn't treat the generic operations different based these.
9893     // However, we aren't really required to flush the result from
9894     // minnum/maxnum..
9895 
9896     // snans will be quieted, so we only need to worry about denormals.
9897     if (Subtarget->supportsMinMaxDenormModes() ||
9898         denormalsEnabledForType(DAG, Op.getValueType()))
9899       return true;
9900 
9901     // Flushing may be required.
9902     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9903     // targets need to check their input recursively.
9904 
9905     // FIXME: Does this apply with clamp? It's implemented with max.
9906     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9907       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9908         return false;
9909     }
9910 
9911     return true;
9912   }
9913   case ISD::SELECT: {
9914     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9915            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9916   }
9917   case ISD::BUILD_VECTOR: {
9918     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9919       SDValue SrcOp = Op.getOperand(i);
9920       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9921         return false;
9922     }
9923 
9924     return true;
9925   }
9926   case ISD::EXTRACT_VECTOR_ELT:
9927   case ISD::EXTRACT_SUBVECTOR: {
9928     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9929   }
9930   case ISD::INSERT_VECTOR_ELT: {
9931     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9932            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9933   }
9934   case ISD::UNDEF:
9935     // Could be anything.
9936     return false;
9937 
9938   case ISD::BITCAST:
9939     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9940   case ISD::TRUNCATE: {
9941     // Hack round the mess we make when legalizing extract_vector_elt
9942     if (Op.getValueType() == MVT::i16) {
9943       SDValue TruncSrc = Op.getOperand(0);
9944       if (TruncSrc.getValueType() == MVT::i32 &&
9945           TruncSrc.getOpcode() == ISD::BITCAST &&
9946           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9947         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9948       }
9949     }
9950     return false;
9951   }
9952   case ISD::INTRINSIC_WO_CHAIN: {
9953     unsigned IntrinsicID
9954       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9955     // TODO: Handle more intrinsics
9956     switch (IntrinsicID) {
9957     case Intrinsic::amdgcn_cvt_pkrtz:
9958     case Intrinsic::amdgcn_cubeid:
9959     case Intrinsic::amdgcn_frexp_mant:
9960     case Intrinsic::amdgcn_fdot2:
9961     case Intrinsic::amdgcn_rcp:
9962     case Intrinsic::amdgcn_rsq:
9963     case Intrinsic::amdgcn_rsq_clamp:
9964     case Intrinsic::amdgcn_rcp_legacy:
9965     case Intrinsic::amdgcn_rsq_legacy:
9966     case Intrinsic::amdgcn_trig_preop:
9967       return true;
9968     default:
9969       break;
9970     }
9971 
9972     LLVM_FALLTHROUGH;
9973   }
9974   default:
9975     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9976            DAG.isKnownNeverSNaN(Op);
9977   }
9978 
9979   llvm_unreachable("invalid operation");
9980 }
9981 
9982 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9983                                        unsigned MaxDepth) const {
9984   MachineRegisterInfo &MRI = MF.getRegInfo();
9985   MachineInstr *MI = MRI.getVRegDef(Reg);
9986   unsigned Opcode = MI->getOpcode();
9987 
9988   if (Opcode == AMDGPU::G_FCANONICALIZE)
9989     return true;
9990 
9991   Optional<FPValueAndVReg> FCR;
9992   // Constant splat (can be padded with undef) or scalar constant.
9993   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9994     if (FCR->Value.isSignaling())
9995       return false;
9996     return !FCR->Value.isDenormal() ||
9997            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9998   }
9999 
10000   if (MaxDepth == 0)
10001     return false;
10002 
10003   switch (Opcode) {
10004   case AMDGPU::G_FMINNUM_IEEE:
10005   case AMDGPU::G_FMAXNUM_IEEE: {
10006     if (Subtarget->supportsMinMaxDenormModes() ||
10007         denormalsEnabledForType(MRI.getType(Reg), MF))
10008       return true;
10009     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10010       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10011         return false;
10012     return true;
10013   }
10014   default:
10015     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10016            isKnownNeverSNaN(Reg, MRI);
10017   }
10018 
10019   llvm_unreachable("invalid operation");
10020 }
10021 
10022 // Constant fold canonicalize.
10023 SDValue SITargetLowering::getCanonicalConstantFP(
10024   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10025   // Flush denormals to 0 if not enabled.
10026   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10027     return DAG.getConstantFP(0.0, SL, VT);
10028 
10029   if (C.isNaN()) {
10030     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10031     if (C.isSignaling()) {
10032       // Quiet a signaling NaN.
10033       // FIXME: Is this supposed to preserve payload bits?
10034       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10035     }
10036 
10037     // Make sure it is the canonical NaN bitpattern.
10038     //
10039     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10040     // immediate?
10041     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10042       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10043   }
10044 
10045   // Already canonical.
10046   return DAG.getConstantFP(C, SL, VT);
10047 }
10048 
10049 static bool vectorEltWillFoldAway(SDValue Op) {
10050   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10051 }
10052 
10053 SDValue SITargetLowering::performFCanonicalizeCombine(
10054   SDNode *N,
10055   DAGCombinerInfo &DCI) const {
10056   SelectionDAG &DAG = DCI.DAG;
10057   SDValue N0 = N->getOperand(0);
10058   EVT VT = N->getValueType(0);
10059 
10060   // fcanonicalize undef -> qnan
10061   if (N0.isUndef()) {
10062     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10063     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10064   }
10065 
10066   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10067     EVT VT = N->getValueType(0);
10068     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10069   }
10070 
10071   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10072   //                                                   (fcanonicalize k)
10073   //
10074   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10075 
10076   // TODO: This could be better with wider vectors that will be split to v2f16,
10077   // and to consider uses since there aren't that many packed operations.
10078   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10079       isTypeLegal(MVT::v2f16)) {
10080     SDLoc SL(N);
10081     SDValue NewElts[2];
10082     SDValue Lo = N0.getOperand(0);
10083     SDValue Hi = N0.getOperand(1);
10084     EVT EltVT = Lo.getValueType();
10085 
10086     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10087       for (unsigned I = 0; I != 2; ++I) {
10088         SDValue Op = N0.getOperand(I);
10089         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10090           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10091                                               CFP->getValueAPF());
10092         } else if (Op.isUndef()) {
10093           // Handled below based on what the other operand is.
10094           NewElts[I] = Op;
10095         } else {
10096           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10097         }
10098       }
10099 
10100       // If one half is undef, and one is constant, prefer a splat vector rather
10101       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10102       // cheaper to use and may be free with a packed operation.
10103       if (NewElts[0].isUndef()) {
10104         if (isa<ConstantFPSDNode>(NewElts[1]))
10105           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10106             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10107       }
10108 
10109       if (NewElts[1].isUndef()) {
10110         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10111           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10112       }
10113 
10114       return DAG.getBuildVector(VT, SL, NewElts);
10115     }
10116   }
10117 
10118   unsigned SrcOpc = N0.getOpcode();
10119 
10120   // If it's free to do so, push canonicalizes further up the source, which may
10121   // find a canonical source.
10122   //
10123   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10124   // sNaNs.
10125   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10126     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10127     if (CRHS && N0.hasOneUse()) {
10128       SDLoc SL(N);
10129       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10130                                    N0.getOperand(0));
10131       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10132       DCI.AddToWorklist(Canon0.getNode());
10133 
10134       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10135     }
10136   }
10137 
10138   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10139 }
10140 
10141 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10142   switch (Opc) {
10143   case ISD::FMAXNUM:
10144   case ISD::FMAXNUM_IEEE:
10145     return AMDGPUISD::FMAX3;
10146   case ISD::SMAX:
10147     return AMDGPUISD::SMAX3;
10148   case ISD::UMAX:
10149     return AMDGPUISD::UMAX3;
10150   case ISD::FMINNUM:
10151   case ISD::FMINNUM_IEEE:
10152     return AMDGPUISD::FMIN3;
10153   case ISD::SMIN:
10154     return AMDGPUISD::SMIN3;
10155   case ISD::UMIN:
10156     return AMDGPUISD::UMIN3;
10157   default:
10158     llvm_unreachable("Not a min/max opcode");
10159   }
10160 }
10161 
10162 SDValue SITargetLowering::performIntMed3ImmCombine(
10163   SelectionDAG &DAG, const SDLoc &SL,
10164   SDValue Op0, SDValue Op1, bool Signed) const {
10165   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10166   if (!K1)
10167     return SDValue();
10168 
10169   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10170   if (!K0)
10171     return SDValue();
10172 
10173   if (Signed) {
10174     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10175       return SDValue();
10176   } else {
10177     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10178       return SDValue();
10179   }
10180 
10181   EVT VT = K0->getValueType(0);
10182   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10183   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10184     return DAG.getNode(Med3Opc, SL, VT,
10185                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10186   }
10187 
10188   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10189   if (VT == MVT::i16) {
10190     MVT NVT = MVT::i32;
10191     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10192 
10193     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10194     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10195     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10196 
10197     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10198     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10199   }
10200 
10201   return SDValue();
10202 }
10203 
10204 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10205   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10206     return C;
10207 
10208   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10209     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10210       return C;
10211   }
10212 
10213   return nullptr;
10214 }
10215 
10216 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10217                                                   const SDLoc &SL,
10218                                                   SDValue Op0,
10219                                                   SDValue Op1) const {
10220   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10221   if (!K1)
10222     return SDValue();
10223 
10224   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10225   if (!K0)
10226     return SDValue();
10227 
10228   // Ordered >= (although NaN inputs should have folded away by now).
10229   if (K0->getValueAPF() > K1->getValueAPF())
10230     return SDValue();
10231 
10232   const MachineFunction &MF = DAG.getMachineFunction();
10233   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10234 
10235   // TODO: Check IEEE bit enabled?
10236   EVT VT = Op0.getValueType();
10237   if (Info->getMode().DX10Clamp) {
10238     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10239     // hardware fmed3 behavior converting to a min.
10240     // FIXME: Should this be allowing -0.0?
10241     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10242       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10243   }
10244 
10245   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10246   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10247     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10248     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10249     // then give the other result, which is different from med3 with a NaN
10250     // input.
10251     SDValue Var = Op0.getOperand(0);
10252     if (!DAG.isKnownNeverSNaN(Var))
10253       return SDValue();
10254 
10255     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10256 
10257     if ((!K0->hasOneUse() ||
10258          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10259         (!K1->hasOneUse() ||
10260          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10261       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10262                          Var, SDValue(K0, 0), SDValue(K1, 0));
10263     }
10264   }
10265 
10266   return SDValue();
10267 }
10268 
10269 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10270                                                DAGCombinerInfo &DCI) const {
10271   SelectionDAG &DAG = DCI.DAG;
10272 
10273   EVT VT = N->getValueType(0);
10274   unsigned Opc = N->getOpcode();
10275   SDValue Op0 = N->getOperand(0);
10276   SDValue Op1 = N->getOperand(1);
10277 
10278   // Only do this if the inner op has one use since this will just increases
10279   // register pressure for no benefit.
10280 
10281   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10282       !VT.isVector() &&
10283       (VT == MVT::i32 || VT == MVT::f32 ||
10284        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10285     // max(max(a, b), c) -> max3(a, b, c)
10286     // min(min(a, b), c) -> min3(a, b, c)
10287     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10288       SDLoc DL(N);
10289       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10290                          DL,
10291                          N->getValueType(0),
10292                          Op0.getOperand(0),
10293                          Op0.getOperand(1),
10294                          Op1);
10295     }
10296 
10297     // Try commuted.
10298     // max(a, max(b, c)) -> max3(a, b, c)
10299     // min(a, min(b, c)) -> min3(a, b, c)
10300     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10301       SDLoc DL(N);
10302       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10303                          DL,
10304                          N->getValueType(0),
10305                          Op0,
10306                          Op1.getOperand(0),
10307                          Op1.getOperand(1));
10308     }
10309   }
10310 
10311   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10312   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10313     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10314       return Med3;
10315   }
10316 
10317   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10318     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10319       return Med3;
10320   }
10321 
10322   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10323   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10324        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10325        (Opc == AMDGPUISD::FMIN_LEGACY &&
10326         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10327       (VT == MVT::f32 || VT == MVT::f64 ||
10328        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10329        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10330       Op0.hasOneUse()) {
10331     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10332       return Res;
10333   }
10334 
10335   return SDValue();
10336 }
10337 
10338 static bool isClampZeroToOne(SDValue A, SDValue B) {
10339   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10340     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10341       // FIXME: Should this be allowing -0.0?
10342       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10343              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10344     }
10345   }
10346 
10347   return false;
10348 }
10349 
10350 // FIXME: Should only worry about snans for version with chain.
10351 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10352                                               DAGCombinerInfo &DCI) const {
10353   EVT VT = N->getValueType(0);
10354   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10355   // NaNs. With a NaN input, the order of the operands may change the result.
10356 
10357   SelectionDAG &DAG = DCI.DAG;
10358   SDLoc SL(N);
10359 
10360   SDValue Src0 = N->getOperand(0);
10361   SDValue Src1 = N->getOperand(1);
10362   SDValue Src2 = N->getOperand(2);
10363 
10364   if (isClampZeroToOne(Src0, Src1)) {
10365     // const_a, const_b, x -> clamp is safe in all cases including signaling
10366     // nans.
10367     // FIXME: Should this be allowing -0.0?
10368     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10369   }
10370 
10371   const MachineFunction &MF = DAG.getMachineFunction();
10372   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10373 
10374   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10375   // handling no dx10-clamp?
10376   if (Info->getMode().DX10Clamp) {
10377     // If NaNs is clamped to 0, we are free to reorder the inputs.
10378 
10379     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10380       std::swap(Src0, Src1);
10381 
10382     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10383       std::swap(Src1, Src2);
10384 
10385     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10386       std::swap(Src0, Src1);
10387 
10388     if (isClampZeroToOne(Src1, Src2))
10389       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10390   }
10391 
10392   return SDValue();
10393 }
10394 
10395 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10396                                                  DAGCombinerInfo &DCI) const {
10397   SDValue Src0 = N->getOperand(0);
10398   SDValue Src1 = N->getOperand(1);
10399   if (Src0.isUndef() && Src1.isUndef())
10400     return DCI.DAG.getUNDEF(N->getValueType(0));
10401   return SDValue();
10402 }
10403 
10404 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10405 // expanded into a set of cmp/select instructions.
10406 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10407                                                 unsigned NumElem,
10408                                                 bool IsDivergentIdx) {
10409   if (UseDivergentRegisterIndexing)
10410     return false;
10411 
10412   unsigned VecSize = EltSize * NumElem;
10413 
10414   // Sub-dword vectors of size 2 dword or less have better implementation.
10415   if (VecSize <= 64 && EltSize < 32)
10416     return false;
10417 
10418   // Always expand the rest of sub-dword instructions, otherwise it will be
10419   // lowered via memory.
10420   if (EltSize < 32)
10421     return true;
10422 
10423   // Always do this if var-idx is divergent, otherwise it will become a loop.
10424   if (IsDivergentIdx)
10425     return true;
10426 
10427   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10428   unsigned NumInsts = NumElem /* Number of compares */ +
10429                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10430   return NumInsts <= 16;
10431 }
10432 
10433 static bool shouldExpandVectorDynExt(SDNode *N) {
10434   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10435   if (isa<ConstantSDNode>(Idx))
10436     return false;
10437 
10438   SDValue Vec = N->getOperand(0);
10439   EVT VecVT = Vec.getValueType();
10440   EVT EltVT = VecVT.getVectorElementType();
10441   unsigned EltSize = EltVT.getSizeInBits();
10442   unsigned NumElem = VecVT.getVectorNumElements();
10443 
10444   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10445                                                     Idx->isDivergent());
10446 }
10447 
10448 SDValue SITargetLowering::performExtractVectorEltCombine(
10449   SDNode *N, DAGCombinerInfo &DCI) const {
10450   SDValue Vec = N->getOperand(0);
10451   SelectionDAG &DAG = DCI.DAG;
10452 
10453   EVT VecVT = Vec.getValueType();
10454   EVT EltVT = VecVT.getVectorElementType();
10455 
10456   if ((Vec.getOpcode() == ISD::FNEG ||
10457        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10458     SDLoc SL(N);
10459     EVT EltVT = N->getValueType(0);
10460     SDValue Idx = N->getOperand(1);
10461     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10462                               Vec.getOperand(0), Idx);
10463     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10464   }
10465 
10466   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10467   //    =>
10468   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10469   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10470   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10471   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10472     SDLoc SL(N);
10473     EVT EltVT = N->getValueType(0);
10474     SDValue Idx = N->getOperand(1);
10475     unsigned Opc = Vec.getOpcode();
10476 
10477     switch(Opc) {
10478     default:
10479       break;
10480       // TODO: Support other binary operations.
10481     case ISD::FADD:
10482     case ISD::FSUB:
10483     case ISD::FMUL:
10484     case ISD::ADD:
10485     case ISD::UMIN:
10486     case ISD::UMAX:
10487     case ISD::SMIN:
10488     case ISD::SMAX:
10489     case ISD::FMAXNUM:
10490     case ISD::FMINNUM:
10491     case ISD::FMAXNUM_IEEE:
10492     case ISD::FMINNUM_IEEE: {
10493       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10494                                  Vec.getOperand(0), Idx);
10495       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10496                                  Vec.getOperand(1), Idx);
10497 
10498       DCI.AddToWorklist(Elt0.getNode());
10499       DCI.AddToWorklist(Elt1.getNode());
10500       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10501     }
10502     }
10503   }
10504 
10505   unsigned VecSize = VecVT.getSizeInBits();
10506   unsigned EltSize = EltVT.getSizeInBits();
10507 
10508   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10509   if (::shouldExpandVectorDynExt(N)) {
10510     SDLoc SL(N);
10511     SDValue Idx = N->getOperand(1);
10512     SDValue V;
10513     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10514       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10515       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10516       if (I == 0)
10517         V = Elt;
10518       else
10519         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10520     }
10521     return V;
10522   }
10523 
10524   if (!DCI.isBeforeLegalize())
10525     return SDValue();
10526 
10527   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10528   // elements. This exposes more load reduction opportunities by replacing
10529   // multiple small extract_vector_elements with a single 32-bit extract.
10530   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10531   if (isa<MemSDNode>(Vec) &&
10532       EltSize <= 16 &&
10533       EltVT.isByteSized() &&
10534       VecSize > 32 &&
10535       VecSize % 32 == 0 &&
10536       Idx) {
10537     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10538 
10539     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10540     unsigned EltIdx = BitIndex / 32;
10541     unsigned LeftoverBitIdx = BitIndex % 32;
10542     SDLoc SL(N);
10543 
10544     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10545     DCI.AddToWorklist(Cast.getNode());
10546 
10547     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10548                               DAG.getConstant(EltIdx, SL, MVT::i32));
10549     DCI.AddToWorklist(Elt.getNode());
10550     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10551                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10552     DCI.AddToWorklist(Srl.getNode());
10553 
10554     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10555     DCI.AddToWorklist(Trunc.getNode());
10556     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10557   }
10558 
10559   return SDValue();
10560 }
10561 
10562 SDValue
10563 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10564                                                 DAGCombinerInfo &DCI) const {
10565   SDValue Vec = N->getOperand(0);
10566   SDValue Idx = N->getOperand(2);
10567   EVT VecVT = Vec.getValueType();
10568   EVT EltVT = VecVT.getVectorElementType();
10569 
10570   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10571   // => BUILD_VECTOR n x select (e, const-idx)
10572   if (!::shouldExpandVectorDynExt(N))
10573     return SDValue();
10574 
10575   SelectionDAG &DAG = DCI.DAG;
10576   SDLoc SL(N);
10577   SDValue Ins = N->getOperand(1);
10578   EVT IdxVT = Idx.getValueType();
10579 
10580   SmallVector<SDValue, 16> Ops;
10581   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10582     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10583     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10584     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10585     Ops.push_back(V);
10586   }
10587 
10588   return DAG.getBuildVector(VecVT, SL, Ops);
10589 }
10590 
10591 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10592                                           const SDNode *N0,
10593                                           const SDNode *N1) const {
10594   EVT VT = N0->getValueType(0);
10595 
10596   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10597   // support denormals ever.
10598   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10599        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10600         getSubtarget()->hasMadF16())) &&
10601        isOperationLegal(ISD::FMAD, VT))
10602     return ISD::FMAD;
10603 
10604   const TargetOptions &Options = DAG.getTarget().Options;
10605   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10606        (N0->getFlags().hasAllowContract() &&
10607         N1->getFlags().hasAllowContract())) &&
10608       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10609     return ISD::FMA;
10610   }
10611 
10612   return 0;
10613 }
10614 
10615 // For a reassociatable opcode perform:
10616 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10617 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10618                                                SelectionDAG &DAG) const {
10619   EVT VT = N->getValueType(0);
10620   if (VT != MVT::i32 && VT != MVT::i64)
10621     return SDValue();
10622 
10623   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10624     return SDValue();
10625 
10626   unsigned Opc = N->getOpcode();
10627   SDValue Op0 = N->getOperand(0);
10628   SDValue Op1 = N->getOperand(1);
10629 
10630   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10631     return SDValue();
10632 
10633   if (Op0->isDivergent())
10634     std::swap(Op0, Op1);
10635 
10636   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10637     return SDValue();
10638 
10639   SDValue Op2 = Op1.getOperand(1);
10640   Op1 = Op1.getOperand(0);
10641   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10642     return SDValue();
10643 
10644   if (Op1->isDivergent())
10645     std::swap(Op1, Op2);
10646 
10647   SDLoc SL(N);
10648   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10649   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10650 }
10651 
10652 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10653                            EVT VT,
10654                            SDValue N0, SDValue N1, SDValue N2,
10655                            bool Signed) {
10656   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10657   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10658   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10659   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10660 }
10661 
10662 SDValue SITargetLowering::performAddCombine(SDNode *N,
10663                                             DAGCombinerInfo &DCI) const {
10664   SelectionDAG &DAG = DCI.DAG;
10665   EVT VT = N->getValueType(0);
10666   SDLoc SL(N);
10667   SDValue LHS = N->getOperand(0);
10668   SDValue RHS = N->getOperand(1);
10669 
10670   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10671       && Subtarget->hasMad64_32() &&
10672       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10673       VT.getScalarSizeInBits() <= 64) {
10674     if (LHS.getOpcode() != ISD::MUL)
10675       std::swap(LHS, RHS);
10676 
10677     SDValue MulLHS = LHS.getOperand(0);
10678     SDValue MulRHS = LHS.getOperand(1);
10679     SDValue AddRHS = RHS;
10680 
10681     // TODO: Maybe restrict if SGPR inputs.
10682     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10683         numBitsUnsigned(MulRHS, DAG) <= 32) {
10684       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10685       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10686       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10687       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10688     }
10689 
10690     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10691       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10692       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10693       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10694       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10695     }
10696 
10697     return SDValue();
10698   }
10699 
10700   if (SDValue V = reassociateScalarOps(N, DAG)) {
10701     return V;
10702   }
10703 
10704   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10705     return SDValue();
10706 
10707   // add x, zext (setcc) => addcarry x, 0, setcc
10708   // add x, sext (setcc) => subcarry x, 0, setcc
10709   unsigned Opc = LHS.getOpcode();
10710   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10711       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10712     std::swap(RHS, LHS);
10713 
10714   Opc = RHS.getOpcode();
10715   switch (Opc) {
10716   default: break;
10717   case ISD::ZERO_EXTEND:
10718   case ISD::SIGN_EXTEND:
10719   case ISD::ANY_EXTEND: {
10720     auto Cond = RHS.getOperand(0);
10721     // If this won't be a real VOPC output, we would still need to insert an
10722     // extra instruction anyway.
10723     if (!isBoolSGPR(Cond))
10724       break;
10725     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10726     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10727     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10728     return DAG.getNode(Opc, SL, VTList, Args);
10729   }
10730   case ISD::ADDCARRY: {
10731     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10732     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10733     if (!C || C->getZExtValue() != 0) break;
10734     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10735     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10736   }
10737   }
10738   return SDValue();
10739 }
10740 
10741 SDValue SITargetLowering::performSubCombine(SDNode *N,
10742                                             DAGCombinerInfo &DCI) const {
10743   SelectionDAG &DAG = DCI.DAG;
10744   EVT VT = N->getValueType(0);
10745 
10746   if (VT != MVT::i32)
10747     return SDValue();
10748 
10749   SDLoc SL(N);
10750   SDValue LHS = N->getOperand(0);
10751   SDValue RHS = N->getOperand(1);
10752 
10753   // sub x, zext (setcc) => subcarry x, 0, setcc
10754   // sub x, sext (setcc) => addcarry x, 0, setcc
10755   unsigned Opc = RHS.getOpcode();
10756   switch (Opc) {
10757   default: break;
10758   case ISD::ZERO_EXTEND:
10759   case ISD::SIGN_EXTEND:
10760   case ISD::ANY_EXTEND: {
10761     auto Cond = RHS.getOperand(0);
10762     // If this won't be a real VOPC output, we would still need to insert an
10763     // extra instruction anyway.
10764     if (!isBoolSGPR(Cond))
10765       break;
10766     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10767     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10768     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10769     return DAG.getNode(Opc, SL, VTList, Args);
10770   }
10771   }
10772 
10773   if (LHS.getOpcode() == ISD::SUBCARRY) {
10774     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10775     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10776     if (!C || !C->isZero())
10777       return SDValue();
10778     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10779     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10780   }
10781   return SDValue();
10782 }
10783 
10784 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10785   DAGCombinerInfo &DCI) const {
10786 
10787   if (N->getValueType(0) != MVT::i32)
10788     return SDValue();
10789 
10790   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10791   if (!C || C->getZExtValue() != 0)
10792     return SDValue();
10793 
10794   SelectionDAG &DAG = DCI.DAG;
10795   SDValue LHS = N->getOperand(0);
10796 
10797   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10798   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10799   unsigned LHSOpc = LHS.getOpcode();
10800   unsigned Opc = N->getOpcode();
10801   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10802       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10803     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10804     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10805   }
10806   return SDValue();
10807 }
10808 
10809 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10810                                              DAGCombinerInfo &DCI) const {
10811   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10812     return SDValue();
10813 
10814   SelectionDAG &DAG = DCI.DAG;
10815   EVT VT = N->getValueType(0);
10816 
10817   SDLoc SL(N);
10818   SDValue LHS = N->getOperand(0);
10819   SDValue RHS = N->getOperand(1);
10820 
10821   // These should really be instruction patterns, but writing patterns with
10822   // source modifiers is a pain.
10823 
10824   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10825   if (LHS.getOpcode() == ISD::FADD) {
10826     SDValue A = LHS.getOperand(0);
10827     if (A == LHS.getOperand(1)) {
10828       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10829       if (FusedOp != 0) {
10830         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10831         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10832       }
10833     }
10834   }
10835 
10836   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10837   if (RHS.getOpcode() == ISD::FADD) {
10838     SDValue A = RHS.getOperand(0);
10839     if (A == RHS.getOperand(1)) {
10840       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10841       if (FusedOp != 0) {
10842         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10843         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10844       }
10845     }
10846   }
10847 
10848   return SDValue();
10849 }
10850 
10851 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10852                                              DAGCombinerInfo &DCI) const {
10853   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10854     return SDValue();
10855 
10856   SelectionDAG &DAG = DCI.DAG;
10857   SDLoc SL(N);
10858   EVT VT = N->getValueType(0);
10859   assert(!VT.isVector());
10860 
10861   // Try to get the fneg to fold into the source modifier. This undoes generic
10862   // DAG combines and folds them into the mad.
10863   //
10864   // Only do this if we are not trying to support denormals. v_mad_f32 does
10865   // not support denormals ever.
10866   SDValue LHS = N->getOperand(0);
10867   SDValue RHS = N->getOperand(1);
10868   if (LHS.getOpcode() == ISD::FADD) {
10869     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10870     SDValue A = LHS.getOperand(0);
10871     if (A == LHS.getOperand(1)) {
10872       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10873       if (FusedOp != 0){
10874         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10875         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10876 
10877         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10878       }
10879     }
10880   }
10881 
10882   if (RHS.getOpcode() == ISD::FADD) {
10883     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10884 
10885     SDValue A = RHS.getOperand(0);
10886     if (A == RHS.getOperand(1)) {
10887       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10888       if (FusedOp != 0){
10889         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10890         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10891       }
10892     }
10893   }
10894 
10895   return SDValue();
10896 }
10897 
10898 SDValue SITargetLowering::performFMACombine(SDNode *N,
10899                                             DAGCombinerInfo &DCI) const {
10900   SelectionDAG &DAG = DCI.DAG;
10901   EVT VT = N->getValueType(0);
10902   SDLoc SL(N);
10903 
10904   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10905     return SDValue();
10906 
10907   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10908   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10909   SDValue Op1 = N->getOperand(0);
10910   SDValue Op2 = N->getOperand(1);
10911   SDValue FMA = N->getOperand(2);
10912 
10913   if (FMA.getOpcode() != ISD::FMA ||
10914       Op1.getOpcode() != ISD::FP_EXTEND ||
10915       Op2.getOpcode() != ISD::FP_EXTEND)
10916     return SDValue();
10917 
10918   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10919   // regardless of the denorm mode setting. Therefore,
10920   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10921   const TargetOptions &Options = DAG.getTarget().Options;
10922   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10923       (N->getFlags().hasAllowContract() &&
10924        FMA->getFlags().hasAllowContract())) {
10925     Op1 = Op1.getOperand(0);
10926     Op2 = Op2.getOperand(0);
10927     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10928         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10929       return SDValue();
10930 
10931     SDValue Vec1 = Op1.getOperand(0);
10932     SDValue Idx1 = Op1.getOperand(1);
10933     SDValue Vec2 = Op2.getOperand(0);
10934 
10935     SDValue FMAOp1 = FMA.getOperand(0);
10936     SDValue FMAOp2 = FMA.getOperand(1);
10937     SDValue FMAAcc = FMA.getOperand(2);
10938 
10939     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10940         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10941       return SDValue();
10942 
10943     FMAOp1 = FMAOp1.getOperand(0);
10944     FMAOp2 = FMAOp2.getOperand(0);
10945     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10946         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10947       return SDValue();
10948 
10949     SDValue Vec3 = FMAOp1.getOperand(0);
10950     SDValue Vec4 = FMAOp2.getOperand(0);
10951     SDValue Idx2 = FMAOp1.getOperand(1);
10952 
10953     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10954         // Idx1 and Idx2 cannot be the same.
10955         Idx1 == Idx2)
10956       return SDValue();
10957 
10958     if (Vec1 == Vec2 || Vec3 == Vec4)
10959       return SDValue();
10960 
10961     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10962       return SDValue();
10963 
10964     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10965         (Vec1 == Vec4 && Vec2 == Vec3)) {
10966       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10967                          DAG.getTargetConstant(0, SL, MVT::i1));
10968     }
10969   }
10970   return SDValue();
10971 }
10972 
10973 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10974                                               DAGCombinerInfo &DCI) const {
10975   SelectionDAG &DAG = DCI.DAG;
10976   SDLoc SL(N);
10977 
10978   SDValue LHS = N->getOperand(0);
10979   SDValue RHS = N->getOperand(1);
10980   EVT VT = LHS.getValueType();
10981   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10982 
10983   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10984   if (!CRHS) {
10985     CRHS = dyn_cast<ConstantSDNode>(LHS);
10986     if (CRHS) {
10987       std::swap(LHS, RHS);
10988       CC = getSetCCSwappedOperands(CC);
10989     }
10990   }
10991 
10992   if (CRHS) {
10993     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10994         isBoolSGPR(LHS.getOperand(0))) {
10995       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10996       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10997       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10998       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10999       if ((CRHS->isAllOnes() &&
11000            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11001           (CRHS->isZero() &&
11002            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11003         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11004                            DAG.getConstant(-1, SL, MVT::i1));
11005       if ((CRHS->isAllOnes() &&
11006            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11007           (CRHS->isZero() &&
11008            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11009         return LHS.getOperand(0);
11010     }
11011 
11012     const APInt &CRHSVal = CRHS->getAPIntValue();
11013     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11014         LHS.getOpcode() == ISD::SELECT &&
11015         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11016         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11017         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11018         isBoolSGPR(LHS.getOperand(0))) {
11019       // Given CT != FT:
11020       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11021       // setcc (select cc, CT, CF), CF, ne => cc
11022       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11023       // setcc (select cc, CT, CF), CT, eq => cc
11024       const APInt &CT = LHS.getConstantOperandAPInt(1);
11025       const APInt &CF = LHS.getConstantOperandAPInt(2);
11026 
11027       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11028           (CT == CRHSVal && CC == ISD::SETNE))
11029         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11030                            DAG.getConstant(-1, SL, MVT::i1));
11031       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11032           (CT == CRHSVal && CC == ISD::SETEQ))
11033         return LHS.getOperand(0);
11034     }
11035   }
11036 
11037   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11038                                            VT != MVT::f16))
11039     return SDValue();
11040 
11041   // Match isinf/isfinite pattern
11042   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11043   // (fcmp one (fabs x), inf) -> (fp_class x,
11044   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11045   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11046     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11047     if (!CRHS)
11048       return SDValue();
11049 
11050     const APFloat &APF = CRHS->getValueAPF();
11051     if (APF.isInfinity() && !APF.isNegative()) {
11052       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11053                                  SIInstrFlags::N_INFINITY;
11054       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11055                                     SIInstrFlags::P_ZERO |
11056                                     SIInstrFlags::N_NORMAL |
11057                                     SIInstrFlags::P_NORMAL |
11058                                     SIInstrFlags::N_SUBNORMAL |
11059                                     SIInstrFlags::P_SUBNORMAL;
11060       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11061       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11062                          DAG.getConstant(Mask, SL, MVT::i32));
11063     }
11064   }
11065 
11066   return SDValue();
11067 }
11068 
11069 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11070                                                      DAGCombinerInfo &DCI) const {
11071   SelectionDAG &DAG = DCI.DAG;
11072   SDLoc SL(N);
11073   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11074 
11075   SDValue Src = N->getOperand(0);
11076   SDValue Shift = N->getOperand(0);
11077 
11078   // TODO: Extend type shouldn't matter (assuming legal types).
11079   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11080     Shift = Shift.getOperand(0);
11081 
11082   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11083     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11084     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11085     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11086     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11087     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11088     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11089       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11090                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11091 
11092       unsigned ShiftOffset = 8 * Offset;
11093       if (Shift.getOpcode() == ISD::SHL)
11094         ShiftOffset -= C->getZExtValue();
11095       else
11096         ShiftOffset += C->getZExtValue();
11097 
11098       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11099         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11100                            MVT::f32, Shifted);
11101       }
11102     }
11103   }
11104 
11105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11106   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11107   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11108     // We simplified Src. If this node is not dead, visit it again so it is
11109     // folded properly.
11110     if (N->getOpcode() != ISD::DELETED_NODE)
11111       DCI.AddToWorklist(N);
11112     return SDValue(N, 0);
11113   }
11114 
11115   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11116   if (SDValue DemandedSrc =
11117           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11118     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11119 
11120   return SDValue();
11121 }
11122 
11123 SDValue SITargetLowering::performClampCombine(SDNode *N,
11124                                               DAGCombinerInfo &DCI) const {
11125   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11126   if (!CSrc)
11127     return SDValue();
11128 
11129   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11130   const APFloat &F = CSrc->getValueAPF();
11131   APFloat Zero = APFloat::getZero(F.getSemantics());
11132   if (F < Zero ||
11133       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11134     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11135   }
11136 
11137   APFloat One(F.getSemantics(), "1.0");
11138   if (F > One)
11139     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11140 
11141   return SDValue(CSrc, 0);
11142 }
11143 
11144 
11145 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11146                                             DAGCombinerInfo &DCI) const {
11147   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11148     return SDValue();
11149   switch (N->getOpcode()) {
11150   case ISD::ADD:
11151     return performAddCombine(N, DCI);
11152   case ISD::SUB:
11153     return performSubCombine(N, DCI);
11154   case ISD::ADDCARRY:
11155   case ISD::SUBCARRY:
11156     return performAddCarrySubCarryCombine(N, DCI);
11157   case ISD::FADD:
11158     return performFAddCombine(N, DCI);
11159   case ISD::FSUB:
11160     return performFSubCombine(N, DCI);
11161   case ISD::SETCC:
11162     return performSetCCCombine(N, DCI);
11163   case ISD::FMAXNUM:
11164   case ISD::FMINNUM:
11165   case ISD::FMAXNUM_IEEE:
11166   case ISD::FMINNUM_IEEE:
11167   case ISD::SMAX:
11168   case ISD::SMIN:
11169   case ISD::UMAX:
11170   case ISD::UMIN:
11171   case AMDGPUISD::FMIN_LEGACY:
11172   case AMDGPUISD::FMAX_LEGACY:
11173     return performMinMaxCombine(N, DCI);
11174   case ISD::FMA:
11175     return performFMACombine(N, DCI);
11176   case ISD::AND:
11177     return performAndCombine(N, DCI);
11178   case ISD::OR:
11179     return performOrCombine(N, DCI);
11180   case ISD::XOR:
11181     return performXorCombine(N, DCI);
11182   case ISD::ZERO_EXTEND:
11183     return performZeroExtendCombine(N, DCI);
11184   case ISD::SIGN_EXTEND_INREG:
11185     return performSignExtendInRegCombine(N , DCI);
11186   case AMDGPUISD::FP_CLASS:
11187     return performClassCombine(N, DCI);
11188   case ISD::FCANONICALIZE:
11189     return performFCanonicalizeCombine(N, DCI);
11190   case AMDGPUISD::RCP:
11191     return performRcpCombine(N, DCI);
11192   case AMDGPUISD::FRACT:
11193   case AMDGPUISD::RSQ:
11194   case AMDGPUISD::RCP_LEGACY:
11195   case AMDGPUISD::RCP_IFLAG:
11196   case AMDGPUISD::RSQ_CLAMP:
11197   case AMDGPUISD::LDEXP: {
11198     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11199     SDValue Src = N->getOperand(0);
11200     if (Src.isUndef())
11201       return Src;
11202     break;
11203   }
11204   case ISD::SINT_TO_FP:
11205   case ISD::UINT_TO_FP:
11206     return performUCharToFloatCombine(N, DCI);
11207   case AMDGPUISD::CVT_F32_UBYTE0:
11208   case AMDGPUISD::CVT_F32_UBYTE1:
11209   case AMDGPUISD::CVT_F32_UBYTE2:
11210   case AMDGPUISD::CVT_F32_UBYTE3:
11211     return performCvtF32UByteNCombine(N, DCI);
11212   case AMDGPUISD::FMED3:
11213     return performFMed3Combine(N, DCI);
11214   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11215     return performCvtPkRTZCombine(N, DCI);
11216   case AMDGPUISD::CLAMP:
11217     return performClampCombine(N, DCI);
11218   case ISD::SCALAR_TO_VECTOR: {
11219     SelectionDAG &DAG = DCI.DAG;
11220     EVT VT = N->getValueType(0);
11221 
11222     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11223     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11224       SDLoc SL(N);
11225       SDValue Src = N->getOperand(0);
11226       EVT EltVT = Src.getValueType();
11227       if (EltVT == MVT::f16)
11228         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11229 
11230       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11231       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11232     }
11233 
11234     break;
11235   }
11236   case ISD::EXTRACT_VECTOR_ELT:
11237     return performExtractVectorEltCombine(N, DCI);
11238   case ISD::INSERT_VECTOR_ELT:
11239     return performInsertVectorEltCombine(N, DCI);
11240   case ISD::LOAD: {
11241     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11242       return Widended;
11243     LLVM_FALLTHROUGH;
11244   }
11245   default: {
11246     if (!DCI.isBeforeLegalize()) {
11247       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11248         return performMemSDNodeCombine(MemNode, DCI);
11249     }
11250 
11251     break;
11252   }
11253   }
11254 
11255   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11256 }
11257 
11258 /// Helper function for adjustWritemask
11259 static unsigned SubIdx2Lane(unsigned Idx) {
11260   switch (Idx) {
11261   default: return ~0u;
11262   case AMDGPU::sub0: return 0;
11263   case AMDGPU::sub1: return 1;
11264   case AMDGPU::sub2: return 2;
11265   case AMDGPU::sub3: return 3;
11266   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11267   }
11268 }
11269 
11270 /// Adjust the writemask of MIMG instructions
11271 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11272                                           SelectionDAG &DAG) const {
11273   unsigned Opcode = Node->getMachineOpcode();
11274 
11275   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11276   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11277   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11278     return Node; // not implemented for D16
11279 
11280   SDNode *Users[5] = { nullptr };
11281   unsigned Lane = 0;
11282   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11283   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11284   unsigned NewDmask = 0;
11285   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11286   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11287   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11288                   Node->getConstantOperandVal(LWEIdx))
11289                      ? true
11290                      : false;
11291   unsigned TFCLane = 0;
11292   bool HasChain = Node->getNumValues() > 1;
11293 
11294   if (OldDmask == 0) {
11295     // These are folded out, but on the chance it happens don't assert.
11296     return Node;
11297   }
11298 
11299   unsigned OldBitsSet = countPopulation(OldDmask);
11300   // Work out which is the TFE/LWE lane if that is enabled.
11301   if (UsesTFC) {
11302     TFCLane = OldBitsSet;
11303   }
11304 
11305   // Try to figure out the used register components
11306   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11307        I != E; ++I) {
11308 
11309     // Don't look at users of the chain.
11310     if (I.getUse().getResNo() != 0)
11311       continue;
11312 
11313     // Abort if we can't understand the usage
11314     if (!I->isMachineOpcode() ||
11315         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11316       return Node;
11317 
11318     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11319     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11320     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11321     // set, etc.
11322     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11323     if (Lane == ~0u)
11324       return Node;
11325 
11326     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11327     if (UsesTFC && Lane == TFCLane) {
11328       Users[Lane] = *I;
11329     } else {
11330       // Set which texture component corresponds to the lane.
11331       unsigned Comp;
11332       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11333         Comp = countTrailingZeros(Dmask);
11334         Dmask &= ~(1 << Comp);
11335       }
11336 
11337       // Abort if we have more than one user per component.
11338       if (Users[Lane])
11339         return Node;
11340 
11341       Users[Lane] = *I;
11342       NewDmask |= 1 << Comp;
11343     }
11344   }
11345 
11346   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11347   bool NoChannels = !NewDmask;
11348   if (NoChannels) {
11349     if (!UsesTFC) {
11350       // No uses of the result and not using TFC. Then do nothing.
11351       return Node;
11352     }
11353     // If the original dmask has one channel - then nothing to do
11354     if (OldBitsSet == 1)
11355       return Node;
11356     // Use an arbitrary dmask - required for the instruction to work
11357     NewDmask = 1;
11358   }
11359   // Abort if there's no change
11360   if (NewDmask == OldDmask)
11361     return Node;
11362 
11363   unsigned BitsSet = countPopulation(NewDmask);
11364 
11365   // Check for TFE or LWE - increase the number of channels by one to account
11366   // for the extra return value
11367   // This will need adjustment for D16 if this is also included in
11368   // adjustWriteMask (this function) but at present D16 are excluded.
11369   unsigned NewChannels = BitsSet + UsesTFC;
11370 
11371   int NewOpcode =
11372       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11373   assert(NewOpcode != -1 &&
11374          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11375          "failed to find equivalent MIMG op");
11376 
11377   // Adjust the writemask in the node
11378   SmallVector<SDValue, 12> Ops;
11379   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11380   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11381   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11382 
11383   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11384 
11385   MVT ResultVT = NewChannels == 1 ?
11386     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11387                            NewChannels == 5 ? 8 : NewChannels);
11388   SDVTList NewVTList = HasChain ?
11389     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11390 
11391 
11392   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11393                                               NewVTList, Ops);
11394 
11395   if (HasChain) {
11396     // Update chain.
11397     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11398     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11399   }
11400 
11401   if (NewChannels == 1) {
11402     assert(Node->hasNUsesOfValue(1, 0));
11403     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11404                                       SDLoc(Node), Users[Lane]->getValueType(0),
11405                                       SDValue(NewNode, 0));
11406     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11407     return nullptr;
11408   }
11409 
11410   // Update the users of the node with the new indices
11411   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11412     SDNode *User = Users[i];
11413     if (!User) {
11414       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11415       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11416       if (i || !NoChannels)
11417         continue;
11418     } else {
11419       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11420       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11421     }
11422 
11423     switch (Idx) {
11424     default: break;
11425     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11426     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11427     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11428     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11429     }
11430   }
11431 
11432   DAG.RemoveDeadNode(Node);
11433   return nullptr;
11434 }
11435 
11436 static bool isFrameIndexOp(SDValue Op) {
11437   if (Op.getOpcode() == ISD::AssertZext)
11438     Op = Op.getOperand(0);
11439 
11440   return isa<FrameIndexSDNode>(Op);
11441 }
11442 
11443 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11444 /// with frame index operands.
11445 /// LLVM assumes that inputs are to these instructions are registers.
11446 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11447                                                         SelectionDAG &DAG) const {
11448   if (Node->getOpcode() == ISD::CopyToReg) {
11449     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11450     SDValue SrcVal = Node->getOperand(2);
11451 
11452     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11453     // to try understanding copies to physical registers.
11454     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11455       SDLoc SL(Node);
11456       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11457       SDValue VReg = DAG.getRegister(
11458         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11459 
11460       SDNode *Glued = Node->getGluedNode();
11461       SDValue ToVReg
11462         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11463                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11464       SDValue ToResultReg
11465         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11466                            VReg, ToVReg.getValue(1));
11467       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11468       DAG.RemoveDeadNode(Node);
11469       return ToResultReg.getNode();
11470     }
11471   }
11472 
11473   SmallVector<SDValue, 8> Ops;
11474   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11475     if (!isFrameIndexOp(Node->getOperand(i))) {
11476       Ops.push_back(Node->getOperand(i));
11477       continue;
11478     }
11479 
11480     SDLoc DL(Node);
11481     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11482                                      Node->getOperand(i).getValueType(),
11483                                      Node->getOperand(i)), 0));
11484   }
11485 
11486   return DAG.UpdateNodeOperands(Node, Ops);
11487 }
11488 
11489 /// Fold the instructions after selecting them.
11490 /// Returns null if users were already updated.
11491 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11492                                           SelectionDAG &DAG) const {
11493   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11494   unsigned Opcode = Node->getMachineOpcode();
11495 
11496   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11497       !TII->isGather4(Opcode) &&
11498       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11499     return adjustWritemask(Node, DAG);
11500   }
11501 
11502   if (Opcode == AMDGPU::INSERT_SUBREG ||
11503       Opcode == AMDGPU::REG_SEQUENCE) {
11504     legalizeTargetIndependentNode(Node, DAG);
11505     return Node;
11506   }
11507 
11508   switch (Opcode) {
11509   case AMDGPU::V_DIV_SCALE_F32_e64:
11510   case AMDGPU::V_DIV_SCALE_F64_e64: {
11511     // Satisfy the operand register constraint when one of the inputs is
11512     // undefined. Ordinarily each undef value will have its own implicit_def of
11513     // a vreg, so force these to use a single register.
11514     SDValue Src0 = Node->getOperand(1);
11515     SDValue Src1 = Node->getOperand(3);
11516     SDValue Src2 = Node->getOperand(5);
11517 
11518     if ((Src0.isMachineOpcode() &&
11519          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11520         (Src0 == Src1 || Src0 == Src2))
11521       break;
11522 
11523     MVT VT = Src0.getValueType().getSimpleVT();
11524     const TargetRegisterClass *RC =
11525         getRegClassFor(VT, Src0.getNode()->isDivergent());
11526 
11527     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11528     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11529 
11530     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11531                                       UndefReg, Src0, SDValue());
11532 
11533     // src0 must be the same register as src1 or src2, even if the value is
11534     // undefined, so make sure we don't violate this constraint.
11535     if (Src0.isMachineOpcode() &&
11536         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11537       if (Src1.isMachineOpcode() &&
11538           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11539         Src0 = Src1;
11540       else if (Src2.isMachineOpcode() &&
11541                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11542         Src0 = Src2;
11543       else {
11544         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11545         Src0 = UndefReg;
11546         Src1 = UndefReg;
11547       }
11548     } else
11549       break;
11550 
11551     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11552     Ops[1] = Src0;
11553     Ops[3] = Src1;
11554     Ops[5] = Src2;
11555     Ops.push_back(ImpDef.getValue(1));
11556     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11557   }
11558   default:
11559     break;
11560   }
11561 
11562   return Node;
11563 }
11564 
11565 // Any MIMG instructions that use tfe or lwe require an initialization of the
11566 // result register that will be written in the case of a memory access failure.
11567 // The required code is also added to tie this init code to the result of the
11568 // img instruction.
11569 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11570   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11571   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11572   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11573   MachineBasicBlock &MBB = *MI.getParent();
11574 
11575   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11576   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11577   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11578 
11579   if (!TFE && !LWE) // intersect_ray
11580     return;
11581 
11582   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11583   unsigned LWEVal = LWE->getImm();
11584   unsigned D16Val = D16 ? D16->getImm() : 0;
11585 
11586   if (!TFEVal && !LWEVal)
11587     return;
11588 
11589   // At least one of TFE or LWE are non-zero
11590   // We have to insert a suitable initialization of the result value and
11591   // tie this to the dest of the image instruction.
11592 
11593   const DebugLoc &DL = MI.getDebugLoc();
11594 
11595   int DstIdx =
11596       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11597 
11598   // Calculate which dword we have to initialize to 0.
11599   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11600 
11601   // check that dmask operand is found.
11602   assert(MO_Dmask && "Expected dmask operand in instruction");
11603 
11604   unsigned dmask = MO_Dmask->getImm();
11605   // Determine the number of active lanes taking into account the
11606   // Gather4 special case
11607   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11608 
11609   bool Packed = !Subtarget->hasUnpackedD16VMem();
11610 
11611   unsigned InitIdx =
11612       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11613 
11614   // Abandon attempt if the dst size isn't large enough
11615   // - this is in fact an error but this is picked up elsewhere and
11616   // reported correctly.
11617   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11618   if (DstSize < InitIdx)
11619     return;
11620 
11621   // Create a register for the initialization value.
11622   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11623   unsigned NewDst = 0; // Final initialized value will be in here
11624 
11625   // If PRTStrictNull feature is enabled (the default) then initialize
11626   // all the result registers to 0, otherwise just the error indication
11627   // register (VGPRn+1)
11628   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11629   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11630 
11631   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11632   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11633     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11634     // Initialize dword
11635     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11636     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11637       .addImm(0);
11638     // Insert into the super-reg
11639     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11640       .addReg(PrevDst)
11641       .addReg(SubReg)
11642       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11643 
11644     PrevDst = NewDst;
11645   }
11646 
11647   // Add as an implicit operand
11648   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11649 
11650   // Tie the just added implicit operand to the dst
11651   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11652 }
11653 
11654 /// Assign the register class depending on the number of
11655 /// bits set in the writemask
11656 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11657                                                      SDNode *Node) const {
11658   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11659 
11660   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11661 
11662   if (TII->isVOP3(MI.getOpcode())) {
11663     // Make sure constant bus requirements are respected.
11664     TII->legalizeOperandsVOP3(MRI, MI);
11665 
11666     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11667     // This saves a chain-copy of registers and better balance register
11668     // use between vgpr and agpr as agpr tuples tend to be big.
11669     if (MI.getDesc().OpInfo) {
11670       unsigned Opc = MI.getOpcode();
11671       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11672       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11673                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11674         if (I == -1)
11675           break;
11676         MachineOperand &Op = MI.getOperand(I);
11677         if (!Op.isReg() || !Op.getReg().isVirtual())
11678           continue;
11679         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11680         if (!TRI->hasAGPRs(RC))
11681           continue;
11682         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11683         if (!Src || !Src->isCopy() ||
11684             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11685           continue;
11686         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11687         // All uses of agpr64 and agpr32 can also accept vgpr except for
11688         // v_accvgpr_read, but we do not produce agpr reads during selection,
11689         // so no use checks are needed.
11690         MRI.setRegClass(Op.getReg(), NewRC);
11691       }
11692 
11693       // Resolve the rest of AV operands to AGPRs.
11694       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11695         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11696           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11697           if (TRI->isVectorSuperClass(RC)) {
11698             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11699             MRI.setRegClass(Src2->getReg(), NewRC);
11700             if (Src2->isTied())
11701               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11702           }
11703         }
11704       }
11705     }
11706 
11707     return;
11708   }
11709 
11710   // Replace unused atomics with the no return version.
11711   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11712   if (NoRetAtomicOp != -1) {
11713     if (!Node->hasAnyUseOfValue(0)) {
11714       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11715                                                AMDGPU::OpName::cpol);
11716       if (CPolIdx != -1) {
11717         MachineOperand &CPol = MI.getOperand(CPolIdx);
11718         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11719       }
11720       MI.removeOperand(0);
11721       MI.setDesc(TII->get(NoRetAtomicOp));
11722       return;
11723     }
11724 
11725     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11726     // instruction, because the return type of these instructions is a vec2 of
11727     // the memory type, so it can be tied to the input operand.
11728     // This means these instructions always have a use, so we need to add a
11729     // special case to check if the atomic has only one extract_subreg use,
11730     // which itself has no uses.
11731     if ((Node->hasNUsesOfValue(1, 0) &&
11732          Node->use_begin()->isMachineOpcode() &&
11733          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11734          !Node->use_begin()->hasAnyUseOfValue(0))) {
11735       Register Def = MI.getOperand(0).getReg();
11736 
11737       // Change this into a noret atomic.
11738       MI.setDesc(TII->get(NoRetAtomicOp));
11739       MI.removeOperand(0);
11740 
11741       // If we only remove the def operand from the atomic instruction, the
11742       // extract_subreg will be left with a use of a vreg without a def.
11743       // So we need to insert an implicit_def to avoid machine verifier
11744       // errors.
11745       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11746               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11747     }
11748     return;
11749   }
11750 
11751   if (TII->isMIMG(MI) && !MI.mayStore())
11752     AddIMGInit(MI);
11753 }
11754 
11755 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11756                               uint64_t Val) {
11757   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11758   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11759 }
11760 
11761 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11762                                                 const SDLoc &DL,
11763                                                 SDValue Ptr) const {
11764   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11765 
11766   // Build the half of the subregister with the constants before building the
11767   // full 128-bit register. If we are building multiple resource descriptors,
11768   // this will allow CSEing of the 2-component register.
11769   const SDValue Ops0[] = {
11770     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11771     buildSMovImm32(DAG, DL, 0),
11772     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11773     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11774     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11775   };
11776 
11777   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11778                                                 MVT::v2i32, Ops0), 0);
11779 
11780   // Combine the constants and the pointer.
11781   const SDValue Ops1[] = {
11782     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11783     Ptr,
11784     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11785     SubRegHi,
11786     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11787   };
11788 
11789   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11790 }
11791 
11792 /// Return a resource descriptor with the 'Add TID' bit enabled
11793 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11794 ///        of the resource descriptor) to create an offset, which is added to
11795 ///        the resource pointer.
11796 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11797                                            SDValue Ptr, uint32_t RsrcDword1,
11798                                            uint64_t RsrcDword2And3) const {
11799   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11800   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11801   if (RsrcDword1) {
11802     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11803                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11804                     0);
11805   }
11806 
11807   SDValue DataLo = buildSMovImm32(DAG, DL,
11808                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11809   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11810 
11811   const SDValue Ops[] = {
11812     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11813     PtrLo,
11814     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11815     PtrHi,
11816     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11817     DataLo,
11818     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11819     DataHi,
11820     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11821   };
11822 
11823   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11824 }
11825 
11826 //===----------------------------------------------------------------------===//
11827 //                         SI Inline Assembly Support
11828 //===----------------------------------------------------------------------===//
11829 
11830 std::pair<unsigned, const TargetRegisterClass *>
11831 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11832                                                StringRef Constraint,
11833                                                MVT VT) const {
11834   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11835 
11836   const TargetRegisterClass *RC = nullptr;
11837   if (Constraint.size() == 1) {
11838     const unsigned BitWidth = VT.getSizeInBits();
11839     switch (Constraint[0]) {
11840     default:
11841       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11842     case 's':
11843     case 'r':
11844       switch (BitWidth) {
11845       case 16:
11846         RC = &AMDGPU::SReg_32RegClass;
11847         break;
11848       case 64:
11849         RC = &AMDGPU::SGPR_64RegClass;
11850         break;
11851       default:
11852         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11853         if (!RC)
11854           return std::make_pair(0U, nullptr);
11855         break;
11856       }
11857       break;
11858     case 'v':
11859       switch (BitWidth) {
11860       case 16:
11861         RC = &AMDGPU::VGPR_32RegClass;
11862         break;
11863       default:
11864         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11865         if (!RC)
11866           return std::make_pair(0U, nullptr);
11867         break;
11868       }
11869       break;
11870     case 'a':
11871       if (!Subtarget->hasMAIInsts())
11872         break;
11873       switch (BitWidth) {
11874       case 16:
11875         RC = &AMDGPU::AGPR_32RegClass;
11876         break;
11877       default:
11878         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11879         if (!RC)
11880           return std::make_pair(0U, nullptr);
11881         break;
11882       }
11883       break;
11884     }
11885     // We actually support i128, i16 and f16 as inline parameters
11886     // even if they are not reported as legal
11887     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11888                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11889       return std::make_pair(0U, RC);
11890   }
11891 
11892   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11893     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11894     if (RegName.consume_front("v")) {
11895       RC = &AMDGPU::VGPR_32RegClass;
11896     } else if (RegName.consume_front("s")) {
11897       RC = &AMDGPU::SGPR_32RegClass;
11898     } else if (RegName.consume_front("a")) {
11899       RC = &AMDGPU::AGPR_32RegClass;
11900     }
11901 
11902     if (RC) {
11903       uint32_t Idx;
11904       if (RegName.consume_front("[")) {
11905         uint32_t End;
11906         bool Failed = RegName.consumeInteger(10, Idx);
11907         Failed |= !RegName.consume_front(":");
11908         Failed |= RegName.consumeInteger(10, End);
11909         Failed |= !RegName.consume_back("]");
11910         if (!Failed) {
11911           uint32_t Width = (End - Idx + 1) * 32;
11912           MCRegister Reg = RC->getRegister(Idx);
11913           if (SIRegisterInfo::isVGPRClass(RC))
11914             RC = TRI->getVGPRClassForBitWidth(Width);
11915           else if (SIRegisterInfo::isSGPRClass(RC))
11916             RC = TRI->getSGPRClassForBitWidth(Width);
11917           else if (SIRegisterInfo::isAGPRClass(RC))
11918             RC = TRI->getAGPRClassForBitWidth(Width);
11919           if (RC) {
11920             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11921             return std::make_pair(Reg, RC);
11922           }
11923         }
11924       } else {
11925         bool Failed = RegName.getAsInteger(10, Idx);
11926         if (!Failed && Idx < RC->getNumRegs())
11927           return std::make_pair(RC->getRegister(Idx), RC);
11928       }
11929     }
11930   }
11931 
11932   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11933   if (Ret.first)
11934     Ret.second = TRI->getPhysRegClass(Ret.first);
11935 
11936   return Ret;
11937 }
11938 
11939 static bool isImmConstraint(StringRef Constraint) {
11940   if (Constraint.size() == 1) {
11941     switch (Constraint[0]) {
11942     default: break;
11943     case 'I':
11944     case 'J':
11945     case 'A':
11946     case 'B':
11947     case 'C':
11948       return true;
11949     }
11950   } else if (Constraint == "DA" ||
11951              Constraint == "DB") {
11952     return true;
11953   }
11954   return false;
11955 }
11956 
11957 SITargetLowering::ConstraintType
11958 SITargetLowering::getConstraintType(StringRef Constraint) const {
11959   if (Constraint.size() == 1) {
11960     switch (Constraint[0]) {
11961     default: break;
11962     case 's':
11963     case 'v':
11964     case 'a':
11965       return C_RegisterClass;
11966     }
11967   }
11968   if (isImmConstraint(Constraint)) {
11969     return C_Other;
11970   }
11971   return TargetLowering::getConstraintType(Constraint);
11972 }
11973 
11974 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11975   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11976     Val = Val & maskTrailingOnes<uint64_t>(Size);
11977   }
11978   return Val;
11979 }
11980 
11981 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11982                                                     std::string &Constraint,
11983                                                     std::vector<SDValue> &Ops,
11984                                                     SelectionDAG &DAG) const {
11985   if (isImmConstraint(Constraint)) {
11986     uint64_t Val;
11987     if (getAsmOperandConstVal(Op, Val) &&
11988         checkAsmConstraintVal(Op, Constraint, Val)) {
11989       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11990       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11991     }
11992   } else {
11993     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11994   }
11995 }
11996 
11997 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11998   unsigned Size = Op.getScalarValueSizeInBits();
11999   if (Size > 64)
12000     return false;
12001 
12002   if (Size == 16 && !Subtarget->has16BitInsts())
12003     return false;
12004 
12005   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12006     Val = C->getSExtValue();
12007     return true;
12008   }
12009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12010     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12011     return true;
12012   }
12013   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12014     if (Size != 16 || Op.getNumOperands() != 2)
12015       return false;
12016     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12017       return false;
12018     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12019       Val = C->getSExtValue();
12020       return true;
12021     }
12022     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12023       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12024       return true;
12025     }
12026   }
12027 
12028   return false;
12029 }
12030 
12031 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12032                                              const std::string &Constraint,
12033                                              uint64_t Val) const {
12034   if (Constraint.size() == 1) {
12035     switch (Constraint[0]) {
12036     case 'I':
12037       return AMDGPU::isInlinableIntLiteral(Val);
12038     case 'J':
12039       return isInt<16>(Val);
12040     case 'A':
12041       return checkAsmConstraintValA(Op, Val);
12042     case 'B':
12043       return isInt<32>(Val);
12044     case 'C':
12045       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12046              AMDGPU::isInlinableIntLiteral(Val);
12047     default:
12048       break;
12049     }
12050   } else if (Constraint.size() == 2) {
12051     if (Constraint == "DA") {
12052       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12053       int64_t LoBits = static_cast<int32_t>(Val);
12054       return checkAsmConstraintValA(Op, HiBits, 32) &&
12055              checkAsmConstraintValA(Op, LoBits, 32);
12056     }
12057     if (Constraint == "DB") {
12058       return true;
12059     }
12060   }
12061   llvm_unreachable("Invalid asm constraint");
12062 }
12063 
12064 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12065                                               uint64_t Val,
12066                                               unsigned MaxSize) const {
12067   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12068   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12069   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12070       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12071       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12072     return true;
12073   }
12074   return false;
12075 }
12076 
12077 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12078   switch (UnalignedClassID) {
12079   case AMDGPU::VReg_64RegClassID:
12080     return AMDGPU::VReg_64_Align2RegClassID;
12081   case AMDGPU::VReg_96RegClassID:
12082     return AMDGPU::VReg_96_Align2RegClassID;
12083   case AMDGPU::VReg_128RegClassID:
12084     return AMDGPU::VReg_128_Align2RegClassID;
12085   case AMDGPU::VReg_160RegClassID:
12086     return AMDGPU::VReg_160_Align2RegClassID;
12087   case AMDGPU::VReg_192RegClassID:
12088     return AMDGPU::VReg_192_Align2RegClassID;
12089   case AMDGPU::VReg_224RegClassID:
12090     return AMDGPU::VReg_224_Align2RegClassID;
12091   case AMDGPU::VReg_256RegClassID:
12092     return AMDGPU::VReg_256_Align2RegClassID;
12093   case AMDGPU::VReg_512RegClassID:
12094     return AMDGPU::VReg_512_Align2RegClassID;
12095   case AMDGPU::VReg_1024RegClassID:
12096     return AMDGPU::VReg_1024_Align2RegClassID;
12097   case AMDGPU::AReg_64RegClassID:
12098     return AMDGPU::AReg_64_Align2RegClassID;
12099   case AMDGPU::AReg_96RegClassID:
12100     return AMDGPU::AReg_96_Align2RegClassID;
12101   case AMDGPU::AReg_128RegClassID:
12102     return AMDGPU::AReg_128_Align2RegClassID;
12103   case AMDGPU::AReg_160RegClassID:
12104     return AMDGPU::AReg_160_Align2RegClassID;
12105   case AMDGPU::AReg_192RegClassID:
12106     return AMDGPU::AReg_192_Align2RegClassID;
12107   case AMDGPU::AReg_256RegClassID:
12108     return AMDGPU::AReg_256_Align2RegClassID;
12109   case AMDGPU::AReg_512RegClassID:
12110     return AMDGPU::AReg_512_Align2RegClassID;
12111   case AMDGPU::AReg_1024RegClassID:
12112     return AMDGPU::AReg_1024_Align2RegClassID;
12113   default:
12114     return -1;
12115   }
12116 }
12117 
12118 // Figure out which registers should be reserved for stack access. Only after
12119 // the function is legalized do we know all of the non-spill stack objects or if
12120 // calls are present.
12121 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12122   MachineRegisterInfo &MRI = MF.getRegInfo();
12123   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12124   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12125   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12126   const SIInstrInfo *TII = ST.getInstrInfo();
12127 
12128   if (Info->isEntryFunction()) {
12129     // Callable functions have fixed registers used for stack access.
12130     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12131   }
12132 
12133   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12134                              Info->getStackPtrOffsetReg()));
12135   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12136     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12137 
12138   // We need to worry about replacing the default register with itself in case
12139   // of MIR testcases missing the MFI.
12140   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12141     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12142 
12143   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12144     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12145 
12146   Info->limitOccupancy(MF);
12147 
12148   if (ST.isWave32() && !MF.empty()) {
12149     for (auto &MBB : MF) {
12150       for (auto &MI : MBB) {
12151         TII->fixImplicitOperands(MI);
12152       }
12153     }
12154   }
12155 
12156   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12157   // classes if required. Ideally the register class constraints would differ
12158   // per-subtarget, but there's no easy way to achieve that right now. This is
12159   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12160   // from using them as the register class for legal types.
12161   if (ST.needsAlignedVGPRs()) {
12162     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12163       const Register Reg = Register::index2VirtReg(I);
12164       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12165       if (!RC)
12166         continue;
12167       int NewClassID = getAlignedAGPRClassID(RC->getID());
12168       if (NewClassID != -1)
12169         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12170     }
12171   }
12172 
12173   TargetLoweringBase::finalizeLowering(MF);
12174 }
12175 
12176 void SITargetLowering::computeKnownBitsForFrameIndex(
12177   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12178   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12179 
12180   // Set the high bits to zero based on the maximum allowed scratch size per
12181   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12182   // calculation won't overflow, so assume the sign bit is never set.
12183   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12184 }
12185 
12186 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12187                                    KnownBits &Known, unsigned Dim) {
12188   unsigned MaxValue =
12189       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12190   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12191 }
12192 
12193 void SITargetLowering::computeKnownBitsForTargetInstr(
12194     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12195     const MachineRegisterInfo &MRI, unsigned Depth) const {
12196   const MachineInstr *MI = MRI.getVRegDef(R);
12197   switch (MI->getOpcode()) {
12198   case AMDGPU::G_INTRINSIC: {
12199     switch (MI->getIntrinsicID()) {
12200     case Intrinsic::amdgcn_workitem_id_x:
12201       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12202       break;
12203     case Intrinsic::amdgcn_workitem_id_y:
12204       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12205       break;
12206     case Intrinsic::amdgcn_workitem_id_z:
12207       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12208       break;
12209     case Intrinsic::amdgcn_mbcnt_lo:
12210     case Intrinsic::amdgcn_mbcnt_hi: {
12211       // These return at most the wavefront size - 1.
12212       unsigned Size = MRI.getType(R).getSizeInBits();
12213       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12214       break;
12215     }
12216     case Intrinsic::amdgcn_groupstaticsize: {
12217       // We can report everything over the maximum size as 0. We can't report
12218       // based on the actual size because we don't know if it's accurate or not
12219       // at any given point.
12220       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12221       break;
12222     }
12223     }
12224     break;
12225   }
12226   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12227     Known.Zero.setHighBits(24);
12228     break;
12229   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12230     Known.Zero.setHighBits(16);
12231     break;
12232   }
12233 }
12234 
12235 Align SITargetLowering::computeKnownAlignForTargetInstr(
12236   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12237   unsigned Depth) const {
12238   const MachineInstr *MI = MRI.getVRegDef(R);
12239   switch (MI->getOpcode()) {
12240   case AMDGPU::G_INTRINSIC:
12241   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12242     // FIXME: Can this move to generic code? What about the case where the call
12243     // site specifies a lower alignment?
12244     Intrinsic::ID IID = MI->getIntrinsicID();
12245     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12246     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12247     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12248       return *RetAlign;
12249     return Align(1);
12250   }
12251   default:
12252     return Align(1);
12253   }
12254 }
12255 
12256 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12257   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12258   const Align CacheLineAlign = Align(64);
12259 
12260   // Pre-GFX10 target did not benefit from loop alignment
12261   if (!ML || DisableLoopAlignment ||
12262       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12263       getSubtarget()->hasInstFwdPrefetchBug())
12264     return PrefAlign;
12265 
12266   // On GFX10 I$ is 4 x 64 bytes cache lines.
12267   // By default prefetcher keeps one cache line behind and reads two ahead.
12268   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12269   // behind and one ahead.
12270   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12271   // If loop fits 64 bytes it always spans no more than two cache lines and
12272   // does not need an alignment.
12273   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12274   // Else if loop is less or equal 192 bytes we need two lines behind.
12275 
12276   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12277   const MachineBasicBlock *Header = ML->getHeader();
12278   if (Header->getAlignment() != PrefAlign)
12279     return Header->getAlignment(); // Already processed.
12280 
12281   unsigned LoopSize = 0;
12282   for (const MachineBasicBlock *MBB : ML->blocks()) {
12283     // If inner loop block is aligned assume in average half of the alignment
12284     // size to be added as nops.
12285     if (MBB != Header)
12286       LoopSize += MBB->getAlignment().value() / 2;
12287 
12288     for (const MachineInstr &MI : *MBB) {
12289       LoopSize += TII->getInstSizeInBytes(MI);
12290       if (LoopSize > 192)
12291         return PrefAlign;
12292     }
12293   }
12294 
12295   if (LoopSize <= 64)
12296     return PrefAlign;
12297 
12298   if (LoopSize <= 128)
12299     return CacheLineAlign;
12300 
12301   // If any of parent loops is surrounded by prefetch instructions do not
12302   // insert new for inner loop, which would reset parent's settings.
12303   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12304     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12305       auto I = Exit->getFirstNonDebugInstr();
12306       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12307         return CacheLineAlign;
12308     }
12309   }
12310 
12311   MachineBasicBlock *Pre = ML->getLoopPreheader();
12312   MachineBasicBlock *Exit = ML->getExitBlock();
12313 
12314   if (Pre && Exit) {
12315     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12316             TII->get(AMDGPU::S_INST_PREFETCH))
12317       .addImm(1); // prefetch 2 lines behind PC
12318 
12319     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12320             TII->get(AMDGPU::S_INST_PREFETCH))
12321       .addImm(2); // prefetch 1 line behind PC
12322   }
12323 
12324   return CacheLineAlign;
12325 }
12326 
12327 LLVM_ATTRIBUTE_UNUSED
12328 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12329   assert(N->getOpcode() == ISD::CopyFromReg);
12330   do {
12331     // Follow the chain until we find an INLINEASM node.
12332     N = N->getOperand(0).getNode();
12333     if (N->getOpcode() == ISD::INLINEASM ||
12334         N->getOpcode() == ISD::INLINEASM_BR)
12335       return true;
12336   } while (N->getOpcode() == ISD::CopyFromReg);
12337   return false;
12338 }
12339 
12340 bool SITargetLowering::isSDNodeSourceOfDivergence(
12341     const SDNode *N, FunctionLoweringInfo *FLI,
12342     LegacyDivergenceAnalysis *KDA) const {
12343   switch (N->getOpcode()) {
12344   case ISD::CopyFromReg: {
12345     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12346     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12347     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12348     Register Reg = R->getReg();
12349 
12350     // FIXME: Why does this need to consider isLiveIn?
12351     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12352       return !TRI->isSGPRReg(MRI, Reg);
12353 
12354     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12355       return KDA->isDivergent(V);
12356 
12357     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12358     return !TRI->isSGPRReg(MRI, Reg);
12359   }
12360   case ISD::LOAD: {
12361     const LoadSDNode *L = cast<LoadSDNode>(N);
12362     unsigned AS = L->getAddressSpace();
12363     // A flat load may access private memory.
12364     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12365   }
12366   case ISD::CALLSEQ_END:
12367     return true;
12368   case ISD::INTRINSIC_WO_CHAIN:
12369     return AMDGPU::isIntrinsicSourceOfDivergence(
12370         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12371   case ISD::INTRINSIC_W_CHAIN:
12372     return AMDGPU::isIntrinsicSourceOfDivergence(
12373         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12374   case AMDGPUISD::ATOMIC_CMP_SWAP:
12375   case AMDGPUISD::ATOMIC_INC:
12376   case AMDGPUISD::ATOMIC_DEC:
12377   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12378   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12379   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12380   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12381   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12382   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12383   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12384   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12385   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12386   case AMDGPUISD::BUFFER_ATOMIC_AND:
12387   case AMDGPUISD::BUFFER_ATOMIC_OR:
12388   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12389   case AMDGPUISD::BUFFER_ATOMIC_INC:
12390   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12391   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12392   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12393   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12394   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12395   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12396     // Target-specific read-modify-write atomics are sources of divergence.
12397     return true;
12398   default:
12399     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12400       // Generic read-modify-write atomics are sources of divergence.
12401       return A->readMem() && A->writeMem();
12402     }
12403     return false;
12404   }
12405 }
12406 
12407 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12408                                                EVT VT) const {
12409   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12410   case MVT::f32:
12411     return hasFP32Denormals(DAG.getMachineFunction());
12412   case MVT::f64:
12413   case MVT::f16:
12414     return hasFP64FP16Denormals(DAG.getMachineFunction());
12415   default:
12416     return false;
12417   }
12418 }
12419 
12420 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12421                                                MachineFunction &MF) const {
12422   switch (Ty.getScalarSizeInBits()) {
12423   case 32:
12424     return hasFP32Denormals(MF);
12425   case 64:
12426   case 16:
12427     return hasFP64FP16Denormals(MF);
12428   default:
12429     return false;
12430   }
12431 }
12432 
12433 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12434                                                     const SelectionDAG &DAG,
12435                                                     bool SNaN,
12436                                                     unsigned Depth) const {
12437   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12438     const MachineFunction &MF = DAG.getMachineFunction();
12439     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12440 
12441     if (Info->getMode().DX10Clamp)
12442       return true; // Clamped to 0.
12443     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12444   }
12445 
12446   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12447                                                             SNaN, Depth);
12448 }
12449 
12450 // Global FP atomic instructions have a hardcoded FP mode and do not support
12451 // FP32 denormals, and only support v2f16 denormals.
12452 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12453   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12454   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12455   if (&Flt == &APFloat::IEEEsingle())
12456     return DenormMode == DenormalMode::getPreserveSign();
12457   return DenormMode == DenormalMode::getIEEE();
12458 }
12459 
12460 TargetLowering::AtomicExpansionKind
12461 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12462   unsigned AS = RMW->getPointerAddressSpace();
12463   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12464     return AtomicExpansionKind::NotAtomic;
12465 
12466   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12467     OptimizationRemarkEmitter ORE(RMW->getFunction());
12468     LLVMContext &Ctx = RMW->getFunction()->getContext();
12469     SmallVector<StringRef> SSNs;
12470     Ctx.getSyncScopeNames(SSNs);
12471     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12472                         ? "system"
12473                         : SSNs[RMW->getSyncScopeID()];
12474     ORE.emit([&]() {
12475       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12476              << "Hardware instruction generated for atomic "
12477              << RMW->getOperationName(RMW->getOperation())
12478              << " operation at memory scope " << MemScope
12479              << " due to an unsafe request.";
12480     });
12481     return Kind;
12482   };
12483 
12484   switch (RMW->getOperation()) {
12485   case AtomicRMWInst::FAdd: {
12486     Type *Ty = RMW->getType();
12487 
12488     // We don't have a way to support 16-bit atomics now, so just leave them
12489     // as-is.
12490     if (Ty->isHalfTy())
12491       return AtomicExpansionKind::None;
12492 
12493     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12494       return AtomicExpansionKind::CmpXChg;
12495 
12496     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12497          Subtarget->hasAtomicFaddInsts()) {
12498       if (Subtarget->hasGFX940Insts())
12499         return AtomicExpansionKind::None;
12500 
12501       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12502       // floating point atomic instructions. May generate more efficient code,
12503       // but may not respect rounding and denormal modes, and may give incorrect
12504       // results for certain memory destinations.
12505       if (RMW->getFunction()
12506               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12507               .getValueAsString() != "true")
12508         return AtomicExpansionKind::CmpXChg;
12509 
12510       if (Subtarget->hasGFX90AInsts()) {
12511         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12512           return AtomicExpansionKind::CmpXChg;
12513 
12514         auto SSID = RMW->getSyncScopeID();
12515         if (SSID == SyncScope::System ||
12516             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12517           return AtomicExpansionKind::CmpXChg;
12518 
12519         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12520       }
12521 
12522       if (AS == AMDGPUAS::FLAT_ADDRESS)
12523         return AtomicExpansionKind::CmpXChg;
12524 
12525       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12526                               : AtomicExpansionKind::CmpXChg;
12527     }
12528 
12529     // DS FP atomics do respect the denormal mode, but the rounding mode is
12530     // fixed to round-to-nearest-even.
12531     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12532     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12533       if (!Ty->isDoubleTy())
12534         return AtomicExpansionKind::None;
12535 
12536       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12537         return AtomicExpansionKind::None;
12538 
12539       return RMW->getFunction()
12540                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12541                          .getValueAsString() == "true"
12542                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12543                  : AtomicExpansionKind::CmpXChg;
12544     }
12545 
12546     return AtomicExpansionKind::CmpXChg;
12547   }
12548   default:
12549     break;
12550   }
12551 
12552   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12553 }
12554 
12555 TargetLowering::AtomicExpansionKind
12556 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12557   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12558              ? AtomicExpansionKind::NotAtomic
12559              : AtomicExpansionKind::None;
12560 }
12561 
12562 TargetLowering::AtomicExpansionKind
12563 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12564   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12565              ? AtomicExpansionKind::NotAtomic
12566              : AtomicExpansionKind::None;
12567 }
12568 
12569 TargetLowering::AtomicExpansionKind
12570 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12571   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12572              ? AtomicExpansionKind::NotAtomic
12573              : AtomicExpansionKind::None;
12574 }
12575 
12576 const TargetRegisterClass *
12577 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12578   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12579   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12580   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12581     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12582                                                : &AMDGPU::SReg_32RegClass;
12583   if (!TRI->isSGPRClass(RC) && !isDivergent)
12584     return TRI->getEquivalentSGPRClass(RC);
12585   else if (TRI->isSGPRClass(RC) && isDivergent)
12586     return TRI->getEquivalentVGPRClass(RC);
12587 
12588   return RC;
12589 }
12590 
12591 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12592 // uniform values (as produced by the mask results of control flow intrinsics)
12593 // used outside of divergent blocks. The phi users need to also be treated as
12594 // always uniform.
12595 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12596                       unsigned WaveSize) {
12597   // FIXME: We assume we never cast the mask results of a control flow
12598   // intrinsic.
12599   // Early exit if the type won't be consistent as a compile time hack.
12600   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12601   if (!IT || IT->getBitWidth() != WaveSize)
12602     return false;
12603 
12604   if (!isa<Instruction>(V))
12605     return false;
12606   if (!Visited.insert(V).second)
12607     return false;
12608   bool Result = false;
12609   for (auto U : V->users()) {
12610     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12611       if (V == U->getOperand(1)) {
12612         switch (Intrinsic->getIntrinsicID()) {
12613         default:
12614           Result = false;
12615           break;
12616         case Intrinsic::amdgcn_if_break:
12617         case Intrinsic::amdgcn_if:
12618         case Intrinsic::amdgcn_else:
12619           Result = true;
12620           break;
12621         }
12622       }
12623       if (V == U->getOperand(0)) {
12624         switch (Intrinsic->getIntrinsicID()) {
12625         default:
12626           Result = false;
12627           break;
12628         case Intrinsic::amdgcn_end_cf:
12629         case Intrinsic::amdgcn_loop:
12630           Result = true;
12631           break;
12632         }
12633       }
12634     } else {
12635       Result = hasCFUser(U, Visited, WaveSize);
12636     }
12637     if (Result)
12638       break;
12639   }
12640   return Result;
12641 }
12642 
12643 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12644                                                const Value *V) const {
12645   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12646     if (CI->isInlineAsm()) {
12647       // FIXME: This cannot give a correct answer. This should only trigger in
12648       // the case where inline asm returns mixed SGPR and VGPR results, used
12649       // outside the defining block. We don't have a specific result to
12650       // consider, so this assumes if any value is SGPR, the overall register
12651       // also needs to be SGPR.
12652       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12653       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12654           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12655       for (auto &TC : TargetConstraints) {
12656         if (TC.Type == InlineAsm::isOutput) {
12657           ComputeConstraintToUse(TC, SDValue());
12658           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12659               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12660           if (RC && SIRI->isSGPRClass(RC))
12661             return true;
12662         }
12663       }
12664     }
12665   }
12666   SmallPtrSet<const Value *, 16> Visited;
12667   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12668 }
12669 
12670 std::pair<InstructionCost, MVT>
12671 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12672                                           Type *Ty) const {
12673   std::pair<InstructionCost, MVT> Cost =
12674       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12675   auto Size = DL.getTypeSizeInBits(Ty);
12676   // Maximum load or store can handle 8 dwords for scalar and 4 for
12677   // vector ALU. Let's assume anything above 8 dwords is expensive
12678   // even if legal.
12679   if (Size <= 256)
12680     return Cost;
12681 
12682   Cost.first += (Size + 255) / 256;
12683   return Cost;
12684 }
12685 
12686 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12687   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12688   for (; I != E; ++I) {
12689     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12690       if (getBasePtrIndex(M) == I.getOperandNo())
12691         return true;
12692     }
12693   }
12694   return false;
12695 }
12696 
12697 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12698                                            SDValue N1) const {
12699   if (!N0.hasOneUse())
12700     return false;
12701   // Take care of the opportunity to keep N0 uniform
12702   if (N0->isDivergent() || !N1->isDivergent())
12703     return true;
12704   // Check if we have a good chance to form the memory access pattern with the
12705   // base and offset
12706   return (DAG.isBaseWithConstantOffset(N0) &&
12707           hasMemSDNodeUser(*N0->use_begin()));
12708 }
12709 
12710 MachineMemOperand::Flags
12711 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12712   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12713   if (I.getMetadata("amdgpu.noclobber"))
12714     return MONoClobber;
12715   return MachineMemOperand::MONone;
12716 }
12717